The alarm that an entry leaves says the summary in an object that never entered
Jonas Templestein, 2026-11-26 22:57 UTC · ba63085fd317a1d14d92e53e97dd68311f6b34d3 · parent f4b4eff
3 files changed
- M core/itx/src/context/awake.test.ts
- M core/itx/src/context/awake.ts
- M core/itx/src/iterate-context-durable-object.ts
M core/itx/src/context/awake.test.ts
@@ -1,7 +1,7 @@ // The dialing side of the awake socket: when a context opens it, how long it holds it and when it // closes it. The accepting side is the runtime's hibernation API, which only a deployed stack has // (core/alchemy/scripts/smoke). -import { expect, test, vi } from "vitest"; +import { expect, onTestFinished, test, vi } from "vitest"; import { AWAKE_ANSWER_WAIT_MS, AWAKE_CONTEXT_PATH, @@ -14,6 +14,7 @@ AWAKE_SUMMARY_EVERY_MS, AwakeSocket, decideAwakeSocket, + unansweredSummaryTries, } from "./awake.ts"; test.for([ @@ -364,6 +365,115 @@ expect(unanswered).toMatchObject({ tries: 1 }); expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS); vi.useRealTimers(); +}); + +test("an alarm in an object that never entered says the summary: the object before it may have died with it unsaid", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + const far = farEnd(); + // a new object: nothing in its memory says whether a summary is owed + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => "one", + }); + expect(awake.recoverAt()).toBeNull(); + expect(awake.recover(Date.now())).toBe(true); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ dials: 1, sent: ["one"], open: 0 }); + // the catalog answered: nothing is owed, and a later alarm of another kind says nothing + expect(awake.recoverAt()).toBeNull(); + expect(awake.recover(Date.now())).toBe(false); + expect(far).toMatchObject({ dials: 1 }); +}); + +test("an alarm while the context works moves the recovery on and makes no entry", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + const far = farEnd(); + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => true, + summary: () => "one", + }); + const enteredAt = Date.now(); + awake.entered(); + // real entries, the last in the fifth minute, keep the socket past the time of the alarm that + // the first one left + for (let minute = 1; minute <= 5; minute++) { + await vi.advanceTimersByTimeAsync(60_000); + awake.entered(); + } + await vi.advanceTimersByTimeAsync(AWAKE_RECOVER_AFTER_MS - 5 * 60_000); + expect(awake.recoverAt()).toBe(enteredAt + AWAKE_RECOVER_AFTER_MS); + expect(awake.recover(Date.now())).toBe(false); + expect(awake.recoverAt()).toBe(Date.now() + AWAKE_RECOVER_AFTER_MS); + expect(far).toMatchObject({ dials: 1, open: 1 }); + // No entry was made by the alarm: the longest hold still ends the socket five minutes after + // the entry in the fifth minute. + await vi.advanceTimersByTimeAsync( + enteredAt + 5 * 60_000 + AWAKE_MAX_HOLD_MS - Date.now() - AWAKE_QUIET_MS, + ); + expect(far).toMatchObject({ open: 1 }); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ dials: 1, open: 0 }); + expect(awake.recoverAt()).toBeNull(); +}); + +test("a summary that cannot be made is owed, as an unanswered one is", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = farEnd(); + const unanswered = counted(); + let readable = false; + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => { + if (!readable) throw new Error("the log cannot be read"); + return "one"; + }, + unanswered, + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + // no wait for an answer that cannot come + expect(far).toMatchObject({ sent: [], open: 0 }); + expect(unanswered).toMatchObject({ tries: 1 }); + expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS); + readable = true; + await vi.advanceTimersByTimeAsync(AWAKE_SAY_AGAIN_AFTER_MS); + expect(awake.recover(Date.now())).toBe(true); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ sent: ["one"], open: 0 }); + expect(unanswered).toMatchObject({ tries: 0 }); + expect(awake.recoverAt()).toBeNull(); +}); + +test("the tries that a context keeps are in a row by time: a count older than an hour counts for nothing", () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + const stored = new Map<string, unknown>(); + const tries = unansweredSummaryTries({ + get: (key: string) => stored.get(key), + put: (key: string, value: unknown) => void stored.set(key, value), + delete: (key: string) => stored.delete(key), + } as Pick<SyncKvStorage, "get" | "put" | "delete">); + expect(tries.count()).toBe(0); + tries.set(3); + vi.advanceTimersByTime(59 * 60_000); + expect(tries.count()).toBe(3); + // the object died before the catalog answered, and the context next went unanswered a day later + vi.advanceTimersByTime(24 * 60 * 60_000); + expect(tries.count()).toBe(0); + tries.set(1); + expect(tries.count()).toBe(1); + tries.set(0); + expect(stored).toMatchObject({ size: 0 }); }); /** Where a context keeps how often its summary went unanswered: its own storage, here a field. */
M core/itx/src/context/awake.ts
@@ -25,14 +25,18 @@ // - after it went quiet, by its own alarm, on the durable ladder (`AWAKE_SAY_AGAIN_AFTER_MS`, // doubled to at most 30 minutes, `AWAKE_SAY_AGAIN_TRIES` times, then a warning and no more); // - after its object died with the summary unsaid, by the alarm that every entry leaves no later -// than `AWAKE_RECOVER_AFTER_MS` ahead, and that a quiet close with every answer takes away. +// than `AWAKE_RECOVER_AFTER_MS` ahead, and that a quiet close with every answer takes away. The +// object that this alarm wakes has nothing in memory of the one before it, so an alarm in an +// object that never entered says the summary (`recover`). // So a row of the catalog is behind its context's log for a bounded time, and a row that stays -// behind is in the log of the context that gave up. It costs a context that has no earlier alarm -// two alarm writes for each time it works. +// behind is in the log of the context that gave up. The alarm is the one durable mark of a summary +// that is owed: it costs a context that has no earlier alarm two alarm writes for each time it +// works, and nothing else is written while the catalog answers. // // The accepting context is not `/`: every wake of `/` restarts the root's facets, and the root // would wake twice for each wake of any other context. +import { z } from "zod"; import type { ContextActivity } from "iterate/api"; export const AWAKE_CONTEXT_PATH = "/awake"; @@ -193,6 +197,8 @@ type AwakeDialedSocket = Pick<WebSocket, "accept" | "close" | "addEventListener" | "send">; +const UnansweredTries = z.object({ tries: z.number().int().positive(), at: z.number() }); + type AwakeSocketDeps = { path: string; /** The upgrade request to the accepting context. */ @@ -259,10 +265,21 @@ return this.#recoverAt ?? null; } - /** The context's alarm fired. When that time has come, the context enters as for work, and so - * says its summary again: true. It writes no wake record: the summary is of the log as it is. */ + /** The context's alarm fired with nothing else due. True when the context then enters as for + * work, and so says its summary again: its time to say it has come, or THIS OBJECT NEVER + * ENTERED. The second case is the object after one that died with its summary unsaid: nothing + * in its memory says so, and the alarm that woke it is all that is left of the one before. It + * writes no wake record: the summary is of the log as it is. */ recover(now: number): boolean { - if (this.#recoverAt === undefined || this.#recoverAt > now) return false; + if (this.#deps.path === AWAKE_CONTEXT_PATH) return false; + const neverEntered = this.#lastEntryAt === 0; + if (!neverEntered && (this.#recoverAt === undefined || this.#recoverAt > now)) return false; + if (this.#timer !== undefined) { + // The context works now: it says its summary as it goes, and its quiet close settles what + // is owed. No entry is made here, so the longest hold still counts from its last real one. + this.#recoverBy(now + AWAKE_RECOVER_AFTER_MS); + return false; + } this.#counted = true; this.entered(); return true; @@ -367,7 +384,8 @@ }); } - // A summary that fails to be made or sent is sent at a later wake: the log it folds stays. + // A summary that fails to be made or sent is owed, as an unanswered one is: the log it folds + // stays, and it is said again. #sendSummary(): void { if (!this.#socket || !this.#deps.summary) return; try { @@ -379,6 +397,7 @@ this.#sayAgain = false; this.#unanswered += 1; } catch (error) { + this.#sayAgain = true; console.info({ event: "context.awake-summary-failed", path: this.#deps.path, @@ -404,6 +423,11 @@ return; } if (this.#unanswered === 0 && !this.#sayAgain) return this.#closeAnswered(); + if (this.#unanswered === 0) { + // nothing went that an answer could come for + this.#closeSocket(); + return this.#wentQuietUnanswered("its summary could not be made or sent"); + } this.#answerWait = setTimeout(() => { this.#answerWait = undefined; this.#closeSocket(); @@ -463,4 +487,23 @@ Date.now() + Math.min(AWAKE_SAY_AGAIN_AFTER_MS * 2 ** (tries - 1), 30 * 60_000), ); } +} + +/** How often in a row a context went quiet with a summary unanswered, kept in the context's own + * storage, where the end of its object does not lose it (`AwakeSocketDeps.unanswered`). "In a + * row" is by time: each try comes at most 30 minutes after the one before, so a count that is + * older than an hour is of an earlier row of tries, and counts for nothing. */ +export function unansweredSummaryTries( + kv: Pick<SyncKvStorage, "get" | "put" | "delete">, +): NonNullable<AwakeSocketDeps["unanswered"]> { + return { + count: () => { + const kept = UnansweredTries.safeParse(kv.get("awake-summary-unanswered")).data; + return kept && Date.now() - kept.at < 60 * 60_000 ? kept.tries : 0; + }, + set: (tries) => { + if (tries > 0) kv.put("awake-summary-unanswered", { tries, at: Date.now() }); + else kv.delete("awake-summary-unanswered"); + }, + }; }
M core/itx/src/iterate-context-durable-object.ts
@@ -101,6 +101,7 @@ awakeContexts, isAwakeWebSocket, setAwakeActivities, + unansweredSummaryTries, } from "./context/awake.ts"; import { CATALOG_WATCH_HEADER } from "./context/catalog-watch.ts"; import { @@ -1164,15 +1165,7 @@ }, }), recoveryChanged: () => this.#alarmCoordinator.reconcile(), - // A count that the end of this object does not lose: written only when the catalog left a - // summary unanswered, and taken away when it answers. - unanswered: { - count: () => Number(this.ctx.storage.kv.get("awake-summary-unanswered")) || 0, - set: (count) => { - if (count > 0) this.ctx.storage.kv.put("awake-summary-unanswered", count); - else this.ctx.storage.kv.delete("awake-summary-unanswered"); - }, - }, + unanswered: unansweredSummaryTries(this.ctx.storage.kv), }); // Live in-flight activities in RAM only (never persisted to KV/SQLite), streaming deltas via @@ -1337,9 +1330,10 @@ !(schedule || delivery || facetClaim) ) { await this.#alarmCoordinator.pass(async () => { - // The catalog did not answer what this context last said of itself: it says it again. No - // wake record: nothing happened here, and the summary is of the log as it is. Inside the - // pass, so its next alarm is written once, when the pass ends. + // Nothing durable is due, so this may be the alarm that an entry leaves until the catalog + // has answered all that the context said of itself (context/awake.ts): the context then + // says its summary again. No wake record: nothing happened here, and the summary is of + // the log as it is. Inside the pass, so its next alarm is written once, when the pass ends. this.#awakeSocket.recover(wokeAt); await this.#residency.alarmPassStarted(wokeAt); });