kernel / core / mind-worker / src / mind / processor.tsmain at 949894f
import type { ScheduledAppend } from "iterate/api";
import type { ItxExpression } from "iterate/expression";
import { errorCode } from "iterate/lib";
import { identitiesAfterAccepted, identitiesAfterRefused } from "iterate/mind-identity-log";
import { failureKind, isPlatformFailureKind } from "iterate/platform-retry";
import {
type ConsumedEvent,
type EmittedEventInput,
type ProcessEventArgs,
type ReduceArgs,
type StreamEventInput,
StreamProcessor,
} from "iterate/stream/processor";
import {
runningUnder,
sha256Hex,
unavailableError,
type ItxEntrypointScope,
type WorkerManifest,
} from "core-itx";
import { MindContract, type MindState } from "./contract.ts";
import { configPointer, probedConfig, type MindPublisher } from "./publication.ts";
import {
gatheredTree,
originBeside,
reposNamedIn,
treeKeyOf,
type TreeCommits,
} from "./tree.ts";
// a publication resolves its npm dependencies from esm.sh
const PUBLICATION_BUDGET_MS = 60_000;
const PUBLICATION_ATTEMPT_WAITS_MS = [0, 5_000, 30_000] as const;
// After the last give-up the commit stays owed to the mind's next incarnation.
const PUBLICATION_RERUN_WAITS_MS = [30_000, 30_000] as const;
// A BIRTH THAT FAILED IS ASKED FOR AGAIN after each of these waits, in one incarnation. A new
// mind's first request can come while its stack is still being deployed: a Worker that Alchemy
// has not finished answers "Alchemy worker is being deployed", and two tries failed so within a
// second (blimro.com, 26 Nov 2026), after which the mind had no repo until its next incarnation,
// ten minutes later. After the last wait the failure stands for this incarnation, and the next
// one starts the waits again. Each failed try is a `mind/create-failed` on the log.
const CREATION_RETRY_WAITS_MS = [0, 5_000, 15_000, 30_000, 60_000, 120_000] as const;
const ingressToConfig = () => ({
type: "events.iterate.com/itx/ingress-configured" as const,
idempotencyKey: "itx/ingress-configured",
payload: { target: ["itx", "config"] },
});
/** A repo that sits directly under `/repos`: only such a repo can be part of the mind's code
* (tree.ts). */
const isSiblingRepo = (path: string) => /^\/repos\/[^/]+$/.test(path);
type OwedCommit = MindState["unpublishedCommits"][number];
type PublicationAttempt =
| {
kind: "admitted";
tree: { commits: TreeCommits; key: string };
mainModule: string;
manifest: WorkerManifest;
missing: string[];
}
// `superseded`: a newer commit came before this one was looked at, which says nothing about it
| { kind: "refused"; error: string; superseded?: true }
// The head read is not the commit and no newer commit is known: the read is behind the commit's
// own fact (the remote's ref answered before the push, or a newer commit's fact is still on its
// way). Read again on the publication's waits; never refused.
| { kind: "behind"; error: string };
/** The schedule's key and the row's name at the root, the event that the schedule appends, and
* its period (`#armGrantRefresh`). The Cloud ends a GitHub claim that is not made again
* within its limit of days: a day is well under it, and one failed day loses nothing. */
const GRANT_REFRESH = "grant-refresh";
const GRANT_REFRESH_DUE = "events.iterate.com/secret/grants-refresh-due";
const GRANT_REFRESH_EVERY_MS = 24 * 60 * 60_000;
/** How long one look at that schedule and row holds: the root looks again at its first pass
* after it (`#armGrantRefresh`). */
const GRANT_REFRESH_LOOK_EVERY_MS = 60 * 60_000;
export class MindProcessor extends StreamProcessor<MindState, ConsumedEvent<typeof MindContract>> {
readonly contract = MindContract;
private readonly getItx: () => ItxEntrypointScope & Disposable;
private readonly publisher: () => MindPublisher;
constructor(getItx: () => ItxEntrypointScope & Disposable, publisher: () => MindPublisher) {
super();
this.getItx = getItx;
this.publisher = publisher;
}
// per incarnation; the durable ground is the state
#creating = false;
/** How many times this incarnation asked again for a birth that failed, and whether one such
* ask waits now (`CREATION_RETRY_WAITS_MS`). */
#creationRetries = 0;
#creationRetryWaits = false;
/** The repos this incarnation already made, and those it already cloned or is cloning: the
* fact of a new repo reaches the state a moment after the call. A clone that failed fails
* the birth, and the birth's next try clones again. */
#repoMade = new Set<string>();
#cloneTried = new Set<string>();
/** Whether this incarnation made the root's own subscription row match the contract, or is
* about to; false again after a try that failed. */
#ownRowMatched = false;
/** When this root last looked for the grants' daily refresh; 0 before the first look. */
#grantRefreshLookedAt = 0;
// One publication runs at a time and drains, oldest first: a commit that lands while one is in
// flight is next, without waiting for another delivery.
#unpublished: MindState["unpublishedCommits"] = [];
#handledThrough = 0;
#publishing = false;
#newestState: MindState | null = null;
override reduce({
event,
state,
}: ReduceArgs<MindState, ConsumedEvent<typeof MindContract>>): MindState | undefined {
switch (event.type) {
case "events.iterate.com/mind/create-requested":
return state.creation?.status === "created"
? undefined
: {
...state,
creation: { status: "requested", offset: event.offset },
};
case "events.iterate.com/mind/created":
return { ...state, creation: { status: "created", offset: event.offset } };
case "events.iterate.com/mind/configured":
return { ...state, configured: event.payload };
// The two identity events count only with the platform's stamp, which the append boundary
// writes and nobody else can (core/itx caller.ts `stampCaller`). The boundary refuses these
// types from anyone else today; the stamp also holds for an event that an older build of
// this Worker, which did not know the types, let somebody write. Each folds into the log
// of the mind id that it names: no deploy chooses a log, and none is emptied.
case "events.iterate.com/mind/identity-record-accepted": {
if (!event.source.platform) return undefined;
const identities = identitiesAfterAccepted(state.identities, event.payload);
if (!identities) return undefined;
return { ...state, identities };
}
case "events.iterate.com/mind/identity-record-refused": {
if (!event.source.platform) return undefined;
const identities = identitiesAfterRefused(state.identities, event.payload, event.offset);
if (!identities) return undefined;
return { ...state, identities };
}
case "events.iterate.com/mind/create-failed":
return state.creation?.status === "created"
? undefined
: {
...state,
creation: { status: "failed", offset: event.offset },
};
case "events.iterate.com/repo/created":
if (state.repos[event.payload.path]) return undefined;
return {
...state,
repos: { ...state.repos, [event.payload.path]: { createdAt: event.createdAt } },
};
case "events.iterate.com/repo/deleted": {
if (!state.repos[event.payload.path]) return undefined;
const { [event.payload.path]: _gone, ...repos } = state.repos;
return { ...state, repos };
}
case "events.iterate.com/workspace/created":
if (state.workspaces[event.payload.path]) return undefined;
return {
...state,
workspaces: { ...state.workspaces, [event.payload.path]: { createdAt: event.createdAt } },
};
case "events.iterate.com/workspace/deleted": {
if (!state.workspaces[event.payload.path]) return undefined;
const { [event.payload.path]: _gone, ...workspaces } = state.workspaces;
return { ...state, workspaces };
}
case "events.iterate.com/sandbox/created":
if (state.sandboxes[event.payload.path]) return undefined;
return {
...state,
sandboxes: { ...state.sandboxes, [event.payload.path]: { createdAt: event.createdAt } },
};
case "events.iterate.com/sandbox/deleted": {
if (!state.sandboxes[event.payload.path]) return undefined;
const { [event.payload.path]: _gone, ...sandboxes } = state.sandboxes;
return { ...state, sandboxes };
}
case "events.iterate.com/itx/child-created":
if (state.contexts[event.payload.childPath]) return undefined;
return {
...state,
contexts: {
...state.contexts,
[event.payload.childPath]: { createdAt: event.createdAt },
},
};
case "events.iterate.com/repo/commit-completed": {
const { path, commitOid } = event.payload;
if (!isSiblingRepo(path)) return undefined;
const repoTips = { ...state.repoTips, [path]: { commitOid, offset: event.offset } };
// A commit asks for a publication when its repo is part of what the mind runs, or may
// be what makes a publication possible: before the first one, and after a refused one.
const asks =
!state.published ||
state.publicationRefused ||
path === state.configured?.entry.repo ||
Object.hasOwn(state.published.commits, path);
if (!asks) return { ...state, repoTips };
return {
...state,
repoTips,
newestAsking: { path, commitOid, offset: event.offset },
unpublishedCommits: [
...state.unpublishedCommits,
{
path,
commitOid,
offset: event.offset,
...(event.source?.cause && {
cause: { ...event.source.cause, parent: `${event.path}@${event.offset}` },
}),
},
],
};
}
case "events.iterate.com/mind/worker-updated": {
const { commits, generation } = event.payload;
return {
...state,
unpublishedCommits: state.unpublishedCommits.filter(
({ offset }) => offset !== generation,
),
lastPublicationFactOffset: event.offset,
published: { commits },
publicationRefused: false,
};
}
case "events.iterate.com/mind/worker-update-failed": {
const { generation, unavailable, superseded } = event.payload;
return {
...state,
unpublishedCommits: unavailable
? state.unpublishedCommits
: state.unpublishedCommits.filter(({ offset }) => offset !== generation),
lastPublicationFactOffset: event.offset,
// the platform's own give-up and a commit that was overtaken say nothing about the code
publicationRefused: unavailable || superseded ? state.publicationRefused : true,
};
}
case "events.iterate.com/mind/sandbox-image-configured":
return { ...state, sandboxImage: event.payload.image };
default:
return undefined;
}
}
override processEvent({
state,
delivery,
append,
runInBackground,
}: ProcessEventArgs<
MindState,
ConsumedEvent<typeof MindContract>,
EmittedEventInput<typeof MindContract>
>): undefined {
this.#newestState = state;
if (!delivery.caughtUp) return;
// A commit is answered as the generation of its fact's offset, so a return to a commit published
// before is a publication of its own. A state that owes nothing starts no background work.
this.#unpublished = state.unpublishedCommits;
const publisher = this.publisher();
// A publication needs the config's entry, which `mind/configured` brings.
if (state.configured && this.#nextOwed() && !this.#publishing) {
this.#publishing = true;
runInBackground(async () => {
try {
for (let owed = this.#nextOwed(); owed; owed = this.#nextOwed()) {
// under the commit's own cause: a publication keeps the commit's depth
const commit = owed;
await runningUnder(commit.cause, async () => {
const rerunWaits = [...PUBLICATION_RERUN_WAITS_MS];
// a newer commit supersedes this one: its publication could only be refused
const stop = () => this.#unpublished.some(({ offset }) => offset > commit.offset);
while (!(await this.#publish(commit, publisher)) && rerunWaits.length > 0) {
for (let waited = 0; waited < rerunWaits[0]! && !stop(); waited += 1_000)
await new Promise((resolve) => setTimeout(resolve, 1_000));
rerunWaits.shift();
if (stop()) break;
}
});
this.#handledThrough = commit.offset;
}
} finally {
this.#publishing = false;
}
});
}
// The root's own row takes the contract's event types, once per incarnation (`#matchOwnRow`).
if (!this.#ownRowMatched) {
this.#ownRowMatched = true;
runInBackground(() => this.#matchOwnRow());
}
// The persons' grants are refreshed once a day: the root gets what does that, and looks
// again at most once an hour (`#armGrantRefresh`).
if (state.creation?.status === "created") runInBackground(() => this.#armGrantRefresh());
// A failed creation is asked for again, after a bounded row of waits in each incarnation
// (`CREATION_RETRY_WAITS_MS`): only the root's birth writes the request, so a failure that
// stood would leave the mind with no site for good.
if (state.creation?.status === "failed") {
const wait = CREATION_RETRY_WAITS_MS[this.#creationRetries];
if (wait === undefined || this.#creationRetryWaits) return;
this.#creationRetries += 1;
this.#creationRetryWaits = true;
runInBackground(async () => {
try {
if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
await append({ type: "events.iterate.com/mind/create-requested", payload: {} });
} finally {
this.#creationRetryWaits = false;
}
});
return;
}
// The config says which repos the mind is born with: nothing is made before it has come.
if (state.creation?.status !== "requested" || this.#creating || !state.configured) return;
this.#creating = true;
runInBackground(async () => {
try {
await this.#makeMissingRepos(state);
// THE MIND IS CREATED WHEN ITS CODE RUNS: after the first publication. A mind whose
// repos are empty waits here for the pushes that fill them.
if (!state.published) return;
// The publication's batch already pointed the ingress: this repeat only waits out its fence.
await append(ingressToConfig());
await append({
type: "events.iterate.com/mind/created",
payload: {},
idempotencyKey: "mind/created",
});
} catch (error) {
await append({
type: "events.iterate.com/mind/create-failed",
payload: { error: error instanceof Error ? error.message : String(error) },
});
} finally {
this.#creating = false;
}
});
}
/** THE REPOS THAT THE MIND IS BORN WITH AND DOES NOT HAVE YET are made, and cloned where there
* is somewhere to clone them from. First the repos that the deploy named (the kernel's and the
* entry repo, each with its origin). Then the repos that the entry repo's package.json names
* (tree.ts `reposNamedIn`), each from beside where the entry repo came from (`originBeside`).
* This runs while the mind is being born and never after: a repo that exists is never
* touched, and a created mind fetches nothing. One case is tried again: a repo with an origin
* and still no commit is a clone that did not finish, once in each incarnation. A clone's pull
* lands the commit's fact on `/`, which asks for the publication. */
async #makeMissingRepos(state: MindState): Promise<void> {
// one stub a call: a clone outlasts any one of them
const call = async (expression: ItxExpression) => {
using itx = this.getItx();
return await itx.invoke(expression);
};
// Through the mind's collection, as any caller reaches a repo, and never the repo's own
// facet: a pull goes out through its caller's egress, which is `/`'s `itx.fetch` here, and a
// facet that is called directly has no caller to take one from, so it refuses the pull.
const ofRepo = (path: string, verb: string, ...args: unknown[]): ItxExpression => [
"itx",
"builtins",
"repos",
["get", path],
[verb, ...args],
];
const make = async (path: string, origin: string | null) => {
if (!state.repos[path] && !this.#repoMade.has(path)) {
await call(["itx", "builtins", "repos", ["create", path]]);
this.#repoMade.add(path);
}
if (!origin || state.repoTips[path] || this.#cloneTried.has(path)) return;
this.#cloneTried.add(path);
try {
await call(ofRepo(path, "setOrigin", origin));
await call(ofRepo(path, "pull", { remote: origin }));
} catch (error) {
// the birth fails with this error, and its next try clones this repo again
this.#cloneTried.delete(path);
throw error;
}
};
const { repos, entry } = state.configured!;
for (const { path, origin } of repos) await make(path, origin);
// the entry repo has its files now, if it was cloned: null from a repo with no commit yet
const packageJson = await call(ofRepo(entry.repo, "readFile", "package.json"));
const entryOrigin = repos.find(({ path }) => path === entry.repo)?.origin || null;
for (const { path, from } of reposNamedIn(typeof packageJson === "string" ? packageJson : null))
await make(path, originBeside(entryOrigin, from));
}
/** THE ROOT'S OWN SUBSCRIPTION ROW names the event types that reach this processor, and a
* root keeps the row of its birth. A root born before a type existed, such as the two events
* of the mind's identity, would never be handed one: `processors.enable("mind")` writes the
* row again when its types are not the contract's, and nothing when they are. Never throws:
* a try that failed is made again at the next pass. */
async #matchOwnRow(): Promise<void> {
try {
using itx = this.getItx();
await itx.invoke(["itx", "builtins", "processors", ["enable", "mind"]]);
} catch (error) {
this.#ownRowMatched = false;
console.info({
event: "mind.own-row-not-matched",
namespace: "mind",
message: "the root's own subscription row was not compared with the contract's event types",
error: error instanceof Error ? error.message : String(error),
});
}
}
/** THE PERSONS' GRANTS THAT THE ITERATE CLOUD BROKERS ARE REFRESHED ONCE A DAY
* (core/secrets-worker/src/grant-refresh.ts says why). The root gets two things for it, each
* only when it is not there: a schedule under the key `grant-refresh`, whose event comes once
* a day, and the row that answers that event with `itx.secrets.refreshGrants()`. The row fans
* out, so a day whose refresh fails is said as that event's failure and holds no later day.
*
* THE ROOT LOOKS AGAIN, AT MOST ONCE AN HOUR, at its first pass after that hour. A root whose
* object stays awake (open connections keep it so) has one incarnation for days: a look once
* per incarnation left such a root with no schedule after one was cancelled.
*
* A MIND'S OWN SCHEDULE UNDER THAT KEY IS LEFT AS IT IS: with another period, or with another
* event, which turns the refresh off. A schedule that was only cancelled is set again at the
* next look.
*
* A SCHEDULE WHOSE FIRE FAILED IS PARKED, and a parked one fires no more until it is set
* again: left so, one failed day would end the refresh for good. It is set again as it is
* defined, the mind's own too, at the next look.
*
* Never throws: a look that failed is made again at the next pass. */
async #armGrantRefresh(): Promise<void> {
if (Date.now() - this.#grantRefreshLookedAt < GRANT_REFRESH_LOOK_EVERY_MS) return;
this.#grantRefreshLookedAt = Date.now();
try {
// one stub a call: no stub outlasts its call
const call = async (...steps: ItxExpression) => {
using itx = this.getItx();
return await itx.invoke(["itx", "builtins", ...steps]);
};
if (!(await call("subscriptions", ["get", GRANT_REFRESH])))
await call([
"append",
{
type: "events.iterate.com/itx/subscription-configured",
payload: {
name: GRANT_REFRESH,
consumes: [GRANT_REFRESH_DUE],
ordered: false,
target: ["itx", "builtins", "secrets", "refreshGrants"],
},
},
]);
// The table's own row, or null: `invoke` answers untyped.
const schedule = (await call("schedules", ["get", GRANT_REFRESH])) as ScheduledAppend | null;
if (!schedule || schedule.failure) {
await call("schedules", [
"set",
{
key: GRANT_REFRESH,
when: schedule?.when || { everyMs: GRANT_REFRESH_EVERY_MS },
events: schedule?.events || [{ type: GRANT_REFRESH_DUE, payload: {} }],
},
]);
if (schedule?.failure)
console.info({
event: "mind.grant-refresh-schedule-set-again",
namespace: "mind",
message: "the schedule that refreshes the persons' grants was parked by a failed fire",
error: schedule.failure.error,
failedAtOffset: schedule.failure.offset,
});
}
} catch (error) {
this.#grantRefreshLookedAt = 0;
console.info({
event: "mind.grant-refresh-not-armed",
namespace: "mind",
message: "the root did not get the schedule that refreshes the persons' grants",
error: error instanceof Error ? error.message : String(error),
});
}
}
#nextOwed(): OwedCommit | undefined {
return this.#unpublished.find(({ offset }) => offset > this.#handledThrough);
}
// The pointer and `mind/worker-updated` land in one batch, so no state of `/` holds either
// without the other. True once the outcome landed, false after a give-up.
async #publish(commit: OwedCommit, publisher: MindPublisher): Promise<boolean> {
const trigger = { path: commit.path, commitOid: commit.commitOid };
const generation = commit.offset;
const giveUpAt = Date.now() + PUBLICATION_BUDGET_MS;
let lastFailure: unknown;
for (const waitMs of PUBLICATION_ATTEMPT_WAITS_MS) {
if (Date.now() + waitMs >= giveUpAt) break;
await new Promise((resolve) => setTimeout(resolve, waitMs));
let attempt: PublicationAttempt;
// a pending timer keeps the context resident
let budget: ReturnType<typeof setTimeout> | undefined;
try {
attempt = await Promise.race([
this.#attemptPublication(commit, publisher),
new Promise<never>((_, reject) => {
budget = setTimeout(
() =>
reject(
unavailableError(
"overloaded",
`publication ${generation} did not finish within ${PUBLICATION_BUDGET_MS} ms`,
),
),
giveUpAt - Date.now(),
);
}),
]);
} catch (error) {
if (!isPlatformFailureKind(failureKind(error))) throw error;
lastFailure = error;
continue;
} finally {
clearTimeout(budget);
}
if (attempt.kind === "behind") {
lastFailure = new Error(attempt.error);
continue;
}
if (attempt.kind === "refused") {
await landOnce(publisher, {
type: "events.iterate.com/mind/worker-update-failed",
idempotencyKey: `mind/publication:${generation}`,
payload: {
trigger,
generation,
error: attempt.error,
...(attempt.superseded && { superseded: true }),
},
});
return true;
}
const { tree, mainModule, manifest, missing } = attempt;
const pointer = configPointer(
{ ...tree, entry: this.#newestState!.configured!.entry },
mainModule,
manifest,
);
const outcome = {
type: "events.iterate.com/mind/worker-updated",
idempotencyKey: `mind/publication:${generation}`,
payload: {
trigger,
commits: tree.commits,
generation,
modules: manifest.modules,
...(missing.length > 0 && { missing }),
},
};
// A mind being created gets its ingress in this batch too, so creation waits out one fence.
// Should its key name another event, the batch is refused whole and lands without it.
if (this.#newestState?.creation?.status === "requested")
try {
await publisher.appendAsPlatform(...pointer, ingressToConfig(), outcome);
return true;
} catch (error) {
if (errorCode(error) !== "IDEMPOTENCY_CONFLICT") throw error;
}
await landOnce(publisher, ...pointer, outcome);
return true;
}
await publisher.appendAsPlatform({
type: "events.iterate.com/mind/worker-update-failed",
payload: {
trigger,
generation,
error: lastFailure instanceof Error ? lastFailure.message : String(lastFailure),
unavailable: true,
},
});
return false;
}
/** ONE LOOK AT WHAT THE REPOS HOLD NOW. A publication is asked for by one commit, and it
* publishes the newest commit of every repo that the entry's imports reach: the commit that
* asked is read as itself, every other repo at its tip. */
async #attemptPublication(
commit: OwedCommit,
publisher: MindPublisher,
): Promise<PublicationAttempt> {
const state = this.#newestState!;
const generation = commit.offset;
// Only a newer commit fact that asked for a publication makes this one superseded, owed
// still or settled already: that publication reads every repo's tip, this commit's too. A
// head read is not ordered after the fact that woke this publication, so a head that is not
// the commit may be its parent.
const newer = state.newestAsking;
if (newer && newer.offset > generation)
return {
kind: "refused",
superseded: true,
error: `${newer.path} moved on to ${newer.commitOid} before this commit was published`,
};
const head = await publisher.head(commit.path);
if (head !== commit.commitOid)
return {
kind: "behind",
error: `main of ${commit.path} read ${head || "no commit (unborn)"}, not ${commit.commitOid}, and no newer commit of it is known`,
};
try {
const { files, commits } = await gatheredTree({
entry: state.configured!.entry,
// a repo the mind does not have has no commit: the tree's error names who imports from it
commitOf: async (repoPath) => {
if (repoPath === commit.path) return commit.commitOid;
return state.repos[repoPath] ? await publisher.head(repoPath) : null;
},
filesOf: (repoPath, commitOid) => publisher.files(repoPath, commitOid),
});
const { mainModule, modules, missing } = await probedConfig(files, publisher);
return {
kind: "admitted",
tree: { commits, key: await sha256Hex(treeKeyOf(commits)) },
mainModule,
manifest: { generation, modules },
missing,
};
} catch (error) {
if (isPlatformFailureKind(failureKind(error))) throw error;
return { kind: "refused", error: error instanceof Error ? error.message : String(error) };
}
}
}
// An IDEMPOTENCY_CONFLICT is an earlier attempt's landed batch: a batch lands whole or not at all.
async function landOnce(publisher: MindPublisher, ...events: StreamEventInput[]): Promise<void> {
try {
await publisher.appendAsPlatform(...events);
} catch (error) {
if (errorCode(error) !== "IDEMPOTENCY_CONFLICT") throw error;
}
}