The reviewer's five findings on the watched catalog
Jonas Templestein, 2026-11-26 23:29 UTC · d91b7a3437cfd4071dc9cc66e7b9eb4d4c1301f2 · parent d2f663b
13 files changed
- M core/itx/src/context/awake.test.ts
- M core/itx/src/context/awake.ts
- M core/itx/src/context/built-ins.ts
- M core/itx/src/context/catalog-watch.test.ts
- M core/itx/src/context/catalog-watch.ts
- M core/itx/src/context/context-activity-stack.test.ts
- M core/itx/src/context/context-catalog.ts
- M core/itx/src/context/itx-expression-rewriting.ts
- M core/itx/src/context/reactive-catalog.test.ts
- M core/itx/src/context/reactive-catalog.ts
- M core/itx/src/iterate-context-durable-object.ts
- M core/itx/src/iterate-context.ts
- M core/lib/src/api.ts
M core/itx/src/context/awake.test.ts
@@ -5,6 +5,8 @@ import { AWAKE_ANSWER_WAIT_MS, AWAKE_CONTEXT_PATH, + AWAKE_SUMMARY_FAILED, + AWAKE_SUMMARY_KEPT, AWAKE_MAX_HOLD_MS, AWAKE_QUIET_MS, AWAKE_RECOVER_AFTER_MS, @@ -367,6 +369,87 @@ vi.useRealTimers(); }); +test("the answer to an earlier summary does not settle a later one that could not be made", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = farEnd(); + far.answers = false; + let busy = true; + let readable = true; + const unanswered = counted(); + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => busy, + summary: () => { + if (!readable) throw new Error("the log cannot be read"); + return "one"; + }, + unanswered, + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_SUMMARY_EVERY_MS + AWAKE_QUIET_MS); + expect(far).toMatchObject({ sent: ["one"], open: 1 }); + // the context goes quiet, and its last summary cannot be made while "one" is unanswered + readable = false; + busy = false; + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ sent: ["one"], open: 1 }); + // the catalog answers "one": that is no answer to the summary that never went + far.answer(); + await vi.advanceTimersByTimeAsync(1); + expect(far).toMatchObject({ open: 0 }); + expect(unanswered).toMatchObject({ tries: 1 }); + expect(awake.recoverAt()).toBe(Date.now() - 1 + AWAKE_SAY_AGAIN_AFTER_MS); +}); + +test("a summary that the catalog could not keep is owed, and the context says it again", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = farEnd(); + far.answerWith = AWAKE_SUMMARY_FAILED; + const unanswered = counted(); + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => "one", + unanswered, + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + // answered, and not kept: no wait, and the alarm has the context say it again + expect(far).toMatchObject({ sent: ["one"], open: 0 }); + expect(unanswered).toMatchObject({ tries: 1 }); + expect(awake.recoverAt()).toBe(Date.now() + AWAKE_SAY_AGAIN_AFTER_MS); + far.answerWith = AWAKE_SUMMARY_KEPT; + 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", "one"], open: 0 }); + expect(unanswered).toMatchObject({ tries: 0 }); + expect(awake.recoverAt()).toBeNull(); +}); + +test("an answer that this release does not know settles a summary, as kept does", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + const far = farEnd(); + far.answerWith = "kept-and-more"; + const awake = new AwakeSocket({ + path: "/agents/a", + dial: far.dial, + busy: () => false, + summary: () => "one", + }); + awake.entered(); + await vi.advanceTimersByTimeAsync(AWAKE_QUIET_MS); + expect(far).toMatchObject({ sent: ["one"], open: 0 }); + expect(awake.recoverAt()).toBeNull(); +}); + 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()); @@ -497,14 +580,17 @@ sent: [] as string[], refuse: false, answers: true, + /** What the catalog says of each summary. */ + answerWith: AWAKE_SUMMARY_KEPT as string, closeAll: () => closers.forEach((close) => close()), /** One answer on each open socket: what a catalog that was slow sends at last. */ answer: () => answerers.forEach((answer) => answer()), dial: async () => { far.dials += 1; if (far.refuse) return { status: 503 }; - const listeners: Record<string, (() => void)[]> = {}; - const answer = () => (listeners.message || []).forEach((listener) => listener()); + const listeners: Record<string, ((event?: { data: string }) => void)[]> = {}; + const answer = () => + (listeners.message || []).forEach((listener) => listener({ data: far.answerWith })); const close = () => { if (!closers.delete(close)) return; answerers.delete(answer); @@ -525,7 +611,7 @@ if (far.answers) queueMicrotask(answer); }, // the one cast: a test socket has only what the dialer uses - addEventListener: ((type: string, listener: () => void) => + addEventListener: ((type: string, listener: (event?: { data: string }) => void) => void (listeners[type] ||= []).push(listener)) as WebSocket["addEventListener"], }, };
M core/itx/src/context/awake.ts
@@ -55,10 +55,13 @@ export const AWAKE_ACTIVITY_DEBOUNCE_MS = 100; /** After a dial that failed, no other dial for this long. */ export const AWAKE_REDIAL_AFTER_MS = 10_000; -/** What the accepting context answers a summary with, on the same socket: it kept it as the - * context's row, or it refused it (a summary that is none, which would be refused again). */ +/** What the accepting context answers a summary with, on the same socket. `kept`: it is the + * context's row. `refused`: it is no summary, and would be refused again. Both settle it. + * `failed`: the catalog could not keep it this time, so it is owed, and the context says it + * again. Any other answer is read as `kept`, so that an answer of a later release settles too. */ export const AWAKE_SUMMARY_KEPT = "kept"; export const AWAKE_SUMMARY_REFUSED = "refused"; +export const AWAKE_SUMMARY_FAILED = "failed"; /** How long a context that went quiet keeps its socket for the answer to its last summary. It is * billed as the quiet window is. The accepting context wakes from hibernation for a summary, * which took 0.1 to 0.6 s on a deployed mind (26 November 2026). */ @@ -356,10 +359,15 @@ socket.addEventListener("close", gone); socket.addEventListener("error", gone); // each message of the far end answers one summary, in the order they were sent - socket.addEventListener("message", () => { + socket.addEventListener("message", (event: { data?: unknown }) => { if (this.#socket !== socket || this.#unanswered === 0) return; this.#unanswered -= 1; - if (this.#unanswered === 0 && this.#answerWait !== undefined) this.#closeAnswered(); + if (event?.data === AWAKE_SUMMARY_FAILED) { + // the catalog could not keep it: it is owed, and the next send says it whole + this.#sentSummary = undefined; + this.#sayAgain = true; + } + if (this.#unanswered === 0 && this.#answerWait !== undefined) this.#quietSettled(); }); // the context went quiet while the dial was on its way: its summary still goes if (this.#timer === undefined) return this.#close(); @@ -422,17 +430,22 @@ if (!this.#dialing) this.#wentQuietUnanswered("it had no socket"); 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"); - } + if (this.#unanswered === 0) return this.#quietSettled(); this.#answerWait = setTimeout(() => { this.#answerWait = undefined; this.#closeSocket(); this.#wentQuietUnanswered("the catalog did not answer in time"); }, AWAKE_ANSWER_WAIT_MS); + } + + /** Quiet, and no answer is outstanding. Nothing is owed when the catalog kept the last summary. + * A summary is still owed when it could not be made or sent, or when the catalog could not + * keep it: an answer to an EARLIER summary settles neither. */ + #quietSettled(): void { + if (!this.#sayAgain) return this.#closeAnswered(); + this.#stopAnswerWait(); + this.#closeSocket(); + this.#wentQuietUnanswered("its last summary could not be made or sent, or was not kept"); } #stopAnswerWait(): void {
M core/itx/src/context/built-ins.ts
@@ -37,7 +37,7 @@ import { unavailableError } from "../unavailable.ts"; import { facetSpecOf, hostedFacetMarkerOf } from "../stream/core-processor.ts"; import { AWAKE_CONTEXT_PATH } from "./awake.ts"; -import { catalogWatchTicket, type CatalogWatchTicket } from "./catalog-watch.ts"; +import { catalogWatchTicket, refuseLoadedCode, type CatalogWatchTicket } from "./catalog-watch.ts"; import { DurableObjectNameCodec } from "./paths.ts"; import { requestScriptRun } from "./run.ts"; import type { Connections } from "./connections.ts"; @@ -440,13 +440,19 @@ .getByName(DurableObjectNameCodec.stringify(AWAKE_CONTEXT_PATH)) .listContexts(options || {}), // A ticket opens nothing: the session's end dials the catalog with it (catalog-watch.ts). - // It is answered here so that a watch passes this table as a list does. - watch: async (query, options) => catalogWatchTicket(query, options), - // The cast: workerd's RPC types read a window's bound, a pair, as a list. - watches: (options) => - contexts() + // It is answered here so that a watch passes this table as a list does. Both calls are + // for a caller that is no code (`refuseLoadedCode`). + watch: async (query, options) => { + refuseLoadedCode(deps.caller(), "watch"); + return catalogWatchTicket(query, options); + }, + watches: async (options) => { + refuseLoadedCode(deps.caller(), "watches"); + // The cast: workerd's RPC types read a window's bound, a pair, as a list. + return (await contexts() .getByName(DurableObjectNameCodec.stringify(AWAKE_CONTEXT_PATH)) - .catalogWatches(options || {}) as unknown as Promise<CatalogWatches>, + .catalogWatches(options || {})) as unknown as CatalogWatches; + }, }, workers: workersRoot({ path,
M core/itx/src/context/catalog-watch.test.ts
@@ -4,8 +4,13 @@ // a real capnweb session, is core/mind-worker/src/context/catalog-watch.test.ts. import type { CatalogFrame } from "iterate/api"; import { expect, onTestFinished, test, vi } from "vitest"; -import { CatalogWatchRelay, catalogWatchTicket, isCatalogWatchTicket } from "./catalog-watch.ts"; import { + CatalogWatchRelay, + catalogWatchTicket, + isCatalogWatchTicket, + refuseLoadedCode, +} from "./catalog-watch.ts"; +import { RPC_STUB_PAGER_KEEPALIVE_REQUEST, RPC_STUB_PAGER_KEEPALIVE_RESPONSE, } from "./rpc-stubs.ts"; @@ -74,6 +79,70 @@ ]); }); +test("a write that the catalog sends in several messages goes to its watchers as one batch, when the last has come", async () => { + const far = catalog(); + const relay = far.relay(); + const batch: [string, string[], boolean][] = []; + const watches = ["first", "second", "third"].map((name, at) => + relay.watch(ticket({ limit: at + 1 }), (frame) => + batch.push([name, (frame.rows as { path: string }[]).map((row) => row.path), !!frame.more]), + ), + ); + const socket = await far.asked(3); + for (const sub of ["w1", "w2", "w3"]) + socket.say({ sub, q: "q", gen: "g", rev: 1, full: false, reset: [] }); + const [first, second, third] = await Promise.all(watches); + using _first = first; + using _second = second; + batch.length = 0; + // the first of two messages of one write: nothing goes yet + socket.say({ + gen: "g", + more: true, + rows: [{ path: "/a" }], + d: [ + ["w1", 1, 2, [], ["/a"]], + ["w2", 1, 2, [], ["/a"]], + ], + }); + expect(batch).toEqual([]); + // the third watch goes away between the two messages + third![Symbol.dispose](); + socket.say({ + gen: "g", + rows: [{ path: "/b" }], + d: [ + ["w3", 1, 2, [], ["/b"]], + ["w1", 2, 3, [], ["/b"]], + ], + }); + expect(batch).toEqual([ + ["first", ["/a"], true], + ["second", ["/a"], true], + ["first", ["/b"], false], + ]); +}); + +test("the rest of a write that a dropped socket was sending does not come: its frames are not handed on", async () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "info").mockImplementation(() => {}); + const far = catalog(); + const relay = far.relay(); + const frames: CatalogFrame<unknown>[] = []; + const watching = relay.watch(ticket({ limit: 5 }), (frame) => frames.push(frame)); + const socket = await far.asked(); + socket.say({ sub: "w1", q: "q", gen: "g", rev: 1, full: false, reset: [] }); + using _watch = await watching; + socket.say({ gen: "g", more: true, rows: [{ path: "/a" }], d: [["w1", 1, 2, [], ["/a"]]] }); + socket.drop(); + await vi.advanceTimersByTimeAsync(10); + const again = await far.asked(); + again.say({ sub: "w1", q: "q", gen: "g", rev: 3, full: false, reset: [{ path: "/a" }] }); + // the answer of the new socket alone: no half of the write that was cut + expect(frames.map((frame) => frame.type)).toEqual(["reset", "reset"]); +}); + test("a frame that does not follow the one before asks the query again, and the watcher gets the whole answer", async () => { const far = catalog(); const relay = far.relay(); @@ -297,6 +366,16 @@ await expect(relay.watch(ticket({ limit: 5 }), () => {})).rejects.toMatchObject({ code: "UNAVAILABLE", }); +}); + +test("loaded code is refused the watch and the list of what is watched, whatever its table lets through", () => { + for (const call of ["watch", "watches"] as const) { + expect(() => refuseLoadedCode({ app: true }, call)).toThrow( + expect.objectContaining({ code: "FORBIDDEN", message: expect.stringContaining(call) }), + ); + // a member's session, and the platform's own code + expect(() => refuseLoadedCode({}, call)).not.toThrow(); + } }); test("a ticket is the query, checked: a callback, a second option or a query the catalog cannot answer is refused", () => {
M core/itx/src/context/catalog-watch.ts
@@ -20,6 +20,7 @@ import { z } from "zod"; import type { CatalogCursor, CatalogFrame, CatalogQuery } from "iterate/api"; import { codedError } from "iterate/lib"; +import type { Caller } from "../caller.ts"; import { unavailableError } from "../unavailable.ts"; import { redial } from "./redial.ts"; import { CatalogRefusal, normalizeQuery } from "./reactive-catalog.ts"; @@ -52,6 +53,19 @@ $itxCatalogWatch: { query: CatalogQuery; cursor?: CatalogCursor }; }; +/** WHO MAY WATCH, AND WHO MAY ASK WHAT IS WATCHED: a session that is no code's (a member's, or + * the platform's own). Loaded code is refused, whatever its table lets through: `watches()` + * names the paths and the facts that other sessions ask for, which a rule that narrows + * `contexts.list` for some code does not narrow. The boundary is here, by the caller, and not by + * the name `contexts`. */ +export function refuseLoadedCode(caller: Pick<Caller, "app">, call: "watch" | "watches"): void { + if (caller.app) + throw codedError( + "FORBIDDEN", + `contexts.${call} is a session's call: loaded code reads the catalog with contexts.list(options)`, + ); +} + export function catalogWatchTicket(query: unknown, options: unknown): CatalogWatchTicket { const parsed = WatchOptions.safeParse(options); if (!parsed.success) @@ -138,6 +152,8 @@ d: z.array( z.tuple([z.string(), z.number(), z.number(), z.array(z.string()), z.array(z.string())]), ), + /** More of the same write comes in the next message. */ + more: z.literal(true).optional(), }), z.object({ sub: z.string().optional(), @@ -158,6 +174,9 @@ #keepalive: ReturnType<typeof setInterval> | undefined; #names = 0; #over = false; + /** The frames of a write that the catalog sends in several messages: they go when its last + * message has come, as one batch. */ + #heldFrames: { sub: string; watch: Watch; frame: CatalogFrame<unknown> }[] = []; constructor(deps: { /** The upgrade request to the context that accepts the awake sockets. */ @@ -249,6 +268,8 @@ #closeSocket(): void { clearInterval(this.#keepalive); this.#keepalive = undefined; + // the rest of a write that this socket was sending does not come: its watches are asked again + this.#heldFrames = []; const socket = this.#socket; this.#socket = undefined; try { @@ -396,7 +417,6 @@ } if ("d" in message) { const rows = new Map(message.rows.map((row) => [row.path, row])); - const frames: [Watch, CatalogFrame<unknown>][] = []; for (const [sub, from, rev, del, put] of message.d) { const watch = this.#watches.get(sub); // a watch that waits for its answer takes no change: the answer is newer than it @@ -406,9 +426,10 @@ continue; } watch.rev = rev; - frames.push([ + this.#heldFrames.push({ + sub, watch, - { + frame: { type: "change", gen: message.gen, from, @@ -416,12 +437,16 @@ del, rows: put.map((path) => rows.get(path)), }, - ]); + }); } - // `more` is over the frames that go: a frame that is the last one to go ends the batch, - // whatever the catalog's message held for a watch that is gone or is asked again - frames.forEach(([watch, frame], at) => - this.#send(watch, at < frames.length - 1 ? { ...frame, more: true } : frame), + // ONE WRITE IS ONE BATCH, however many messages the catalog cut it into: its frames go + // when the last message has come. `more` is over the frames that go: the last one to go + // ends the batch, whatever the catalog held for a watch that is gone or is asked again. + if (message.more) return; + const batch = this.#heldFrames.filter(({ sub, watch }) => this.#watches.get(sub) === watch); + this.#heldFrames = []; + batch.forEach(({ watch, frame }, at) => + this.#send(watch, at < batch.length - 1 ? { ...frame, more: true } : frame), ); return; }
M core/itx/src/context/context-activity-stack.test.ts
@@ -25,7 +25,7 @@ describeScriptRunActivity, withTrackedActivity, } from "./context-activity-stack.ts"; -import { ContextCatalog, type ContextSummaryMessage } from "./context-catalog.ts"; +import { ContextCatalog, type ContextSummaryMessage, NotASummary } from "./context-catalog.ts"; import { ItxExpressionResolver } from "./itx-expression-rewriting.ts"; defineItxHost({ firstPartyFacets: {} }); @@ -224,6 +224,14 @@ ).toMatchObject({ row: undefined }); expect(catalog.rowsAfter("", 10)).toEqual([extracted.row]); expect(catalog.rowsAfter("/agents/builder", 10)).toEqual([]); + // one context's row, which a write that the watched copy owes is made again from + expect(catalog.row("/agents/builder")).toEqual(extracted.row); + expect(catalog.row("/agents/nobody")).toBeUndefined(); + // a message that is no summary is refused as such: saying it again would change nothing + expect(() => catalog.store("/agents/builder", "not JSON")).toThrow(NotASummary); + expect(() => catalog.store("/agents/builder", JSON.stringify({ eventCount: "many" }))).toThrow( + NotASummary, + ); // SQLite `context_catalog.summary` must NOT contain ephemeral `activities` const storedColumns = rawRows();
M core/itx/src/context/context-catalog.ts
@@ -22,6 +22,10 @@ }); export type ContextSummaryMessage = z.infer<typeof ContextSummaryMessage>; +/** A message on an awake socket that is no summary: saying it again would be refused again. Any + * other failure of `store` is the catalog's own, and the summary is owed. */ +export class NotASummary extends Error {} + export class ContextCatalog { readonly #sql: SqlStorage; #tableMade = false; @@ -51,12 +55,18 @@ * returns the live `activities` carried on the message so the caller can attach them to the * open awake socket (never SQLite). `row` is the row as a watched query serves it, when the * message was kept: the copy beside this table takes it (reactive-catalog.ts). A message that - * is no summary is refused with a thrown error. */ + * is no summary is refused with `NotASummary`. */ store( path: string, message: string, ): { activities: ContextActivity[] | undefined; row: CatalogRowInput | undefined } { - const { activities, ...durable } = ContextSummaryMessage.parse(JSON.parse(message)); + let parsed: ContextSummaryMessage; + try { + parsed = ContextSummaryMessage.parse(JSON.parse(message)); + } catch (error) { + throw new NotASummary(error instanceof Error ? error.message : String(error)); + } + const { activities, ...durable } = parsed; this.#table(); const { rowsWritten } = this.#sql.exec( `INSERT INTO context_catalog (path, through_offset, active_at, summary) VALUES (?, ?, ?, ?) @@ -71,6 +81,17 @@ JSON.stringify(durable), ); return { activities, row: rowsWritten > 0 ? watchedRowOf(path, durable) : undefined }; + } + + /** One context's row as a watched query serves it: what the copy settles a write from that it + * could not make. Undefined when the catalog has none, or one that no longer parses. */ + row(path: string): CatalogRowInput | undefined { + this.#table(); + const stored = this.#sql + .exec<{ summary: string }>("SELECT summary FROM context_catalog WHERE path = ?", path) + .toArray()[0]; + const summary = stored && StoredContextSummary.safeParse(JSON.parse(stored.summary)); + return summary?.success ? watchedRowOf(path, summary.data) : undefined; } /** A page of the rows, in path order, after the path `after`: what the copy for watched queries
M core/itx/src/context/itx-expression-rewriting.ts
@@ -53,7 +53,7 @@ rpcStubs: "live values clients lent here: `rpcStubs.list()` · `rpcStubs.get(key)`", rewriteRules: "this table, described: `await rewriteRules.list()`", contexts: - "the mind's catalog of its contexts, the most recently active first: `await itx.cd('/').contexts.list({ search?, under?, awake?, limit? })` → [{ path, awake?, lastActivityAt, eventCount, eventTypes, recentTypes, processors, description?, metadata? }]; a context describes itself with `itx.append({ type: 'events.iterate.com/itx/described', payload: { description, metadata } })`; a session keeps a query answered with `contexts.watch({ where?, under?, childrenOf?, order?, limit? } | { keys } | { awake: true }, onFrame)`, and `contexts.watches()` says who watches what", + "the mind's catalog of its contexts, the most recently active first: `await itx.cd('/').contexts.list({ search?, under?, awake?, limit? })` → [{ path, awake?, lastActivityAt, eventCount, eventTypes, recentTypes, processors, description?, metadata? }]; a context describes itself with `itx.append({ type: 'events.iterate.com/itx/described', payload: { description, metadata } })`; a session that is no code's keeps a query answered with `contexts.watch({ where?, under?, childrenOf?, order?, limit? } | { keys } | { awake: true }, onFrame)`, and asks who watches what with `contexts.watches()`", facets: "a durable facet hosted here: `facets.get(name)` · `facets.abort(name, reason?)` resets that one facet", abort:
M core/itx/src/context/reactive-catalog.test.ts
@@ -5,7 +5,7 @@ // changed. import { DatabaseSync } from "node:sqlite"; import type { CatalogCursor, CatalogOrder, CatalogQuery } from "iterate/api"; -import { expect, test } from "vitest"; +import { expect, onTestFinished, test, vi } from "vitest"; import { CATALOG_LIMITS, compareTextBinary, @@ -450,6 +450,143 @@ expect(late.refusals.at(-1)).toMatchObject({ kind: "query" }); }); +test("no fact of a row is cut in silence: the 65th tag is found, and a row with more facts than the index takes is refused whole", () => { + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + const tags = Array.from({ length: 65 }, (_, index) => `tag-${index}`); + catalog.upsert({ path: "/agents/tagged", activeMs: 1, createdMs: 1, metadata: { tags } }); + const client = new Client(); + client.connect(catalog); + client.subscribe(catalog, "last", { where: { tags: "tag-64" } }); + expect([...client.subs.get("last")!.rows.keys()]).toEqual(["/agents/tagged"]); + + // more facts than the catalog indexes for a row: refused, with the count + const many = Array.from({ length: CATALOG_LIMITS.factsPerRow }, (_, index) => `t${index}`); + expect(() => + catalog.upsert({ path: "/agents/huge", activeMs: 2, createdMs: 2, metadata: { tags: many } }), + ).toThrow(/has 2051 facts, and the catalog indexes at most 2048/); + // as the catalog hands it over: the row leaves the copy, and a watcher sees no old row of it + catalog.upsert({ path: "/agents/huge", activeMs: 1, createdMs: 1, metadata: { tags: ["t0"] } }); + client.subscribe(catalog, "huge", { keys: ["/agents/huge"] }); + expect(client.subs.get("huge")!.rows).toMatchObject({ size: 1 }); + vi.spyOn(console, "info").mockImplementation(() => {}); + catalog.keep({ path: "/agents/huge", activeMs: 2, createdMs: 2, metadata: { tags: many } }); + expect(client.subs.get("huge")!.rows).toMatchObject({ size: 0 }); + expect(catalog.watches()).toMatchObject({ owed: 0 }); + + // a key that starts with `$` is the kernel's: a query cannot name one that it has not + client.subscribe(catalog, "bad", { where: { $owner: "ada" } }); + expect(client.refusals.at(-1)).toMatchObject({ + kind: "query", + error: expect.stringContaining('no fact "$owner"'), + }); + client.subscribe(catalog, "good", { where: { $processor: "agent" } }); + expect(client.refusals).toHaveLength(1); +}); + +test("a write that the copy cannot make is owed: it is reported, and made again from the catalog's own row", () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + const reported = vi.spyOn(console, "error").mockImplementation(() => {}); + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + const client = new Client(); + client.connect(catalog); + client.subscribe(catalog, "open", { where: { status: "open" }, limit: 5 }); + const sub = client.subs.get("open")!; + + // the copy's store fails for one context's row + const boom = task(1, "open", 10); + object.catalogRows.set(boom.path, boom); + object.failing.when = (query, params) => + query.startsWith("INSERT INTO rcat_row") && params[0] === boom.path; + catalog.keep(boom); + expect(sub.rows).toMatchObject({ size: 0 }); + expect(catalog.watches()).toMatchObject({ owed: 1, rows: 0 }); + expect(reported).toHaveBeenCalledTimes(1); + + // another context's summary, before the owed write is due: it is kept, and the debt stays + catalog.keep(task(2, "open", 20)); + expect([...sub.rows.keys()]).toEqual(["/tasks/t0002"]); + expect(catalog.watches()).toMatchObject({ owed: 1 }); + + // an object that wakes knows of the debt, and a write a minute later settles it + object.failing.when = undefined; + vi.advanceTimersByTime(60_000); + const woken = object.wake(); + woken.keep(task(3, "closed", 30)); + expect([...sub.rows.keys()].toSorted()).toEqual(["/tasks/t0001", "/tasks/t0002"]); + expect(woken.watches({ verify: true })).toMatchObject({ owed: 0, faults: [] }); + expect(reported).toHaveBeenCalledTimes(1); +}); + +test("an owed write that keeps failing is tried eight times, at longer waits, and a later summary of that context pays it", () => { + vi.useFakeTimers(); + onTestFinished(() => void vi.useRealTimers()); + vi.spyOn(console, "error").mockImplementation(() => {}); + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + const boom = task(1, "open", 10); + object.catalogRows.set(boom.path, boom); + let tries = 0; + object.failing.when = (query, params) => { + const hit = query.startsWith("INSERT INTO rcat_row") && params[0] === boom.path; + if (hit) tries += 1; + return hit; + }; + catalog.keep(boom); + const waits: number[] = []; + let tick = 0; + for (let step = 0; step < 400 && tries < CATALOG_LIMITS.owedTries; step++) { + const before = tries; + vi.advanceTimersByTime(30_000); + tick += 30_000; + // any other context's summary is a chance to settle what is due + catalog.keep(task(2, "open", 100 + step)); + if (tries > before) { + waits.push(tick); + tick = 0; + } + } + // one minute, then doubled, thirty minutes at most + expect(waits).toEqual([60_000, 120_000, 240_000, 480_000, 960_000, 1_800_000, 1_800_000]); + // and then no more: the mark stays, for a person to see + vi.advanceTimersByTime(24 * 60 * 60_000); + catalog.keep(task(2, "open", 9_999)); + expect(tries).toBe(CATALOG_LIMITS.owedTries); + expect(catalog.watches()).toMatchObject({ owed: 1 }); + // the context's own next summary, which the copy can write, pays the debt + object.failing.when = undefined; + catalog.keep(task(1, "open", 10_000)); + expect(catalog.watches()).toMatchObject({ owed: 0, rows: 2 }); +}); + +test("a write that is longer than one message comes in parts, each but the last marked", () => { + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + const client = new Client(); + client.connect(catalog); + client.subscribe(catalog, "all", { limit: 50 }); + const parts: boolean[] = []; + client.onChange = (message) => parts.push(!!message.more); + // one transaction of 30 rows, each with a description of 20,000 characters + expect( + catalog.upsertMany( + Array.from({ length: 30 }, (_, index) => ({ + ...task(index, "open", index), + description: "x".repeat(20_000), + })), + ), + ).toMatchObject({ changed: 30, frames: 30 }); + expect(parts.length).toBeGreaterThan(1); + expect(parts).toEqual([...parts.slice(0, -1).map(() => true), false]); + expect(client.subs.get("all")!.rows).toMatchObject({ size: 30 }); +}); + test("one write is one message for a socket, over all of its queries", () => { using object = fakeObject(); const catalog = object.wake(); @@ -467,11 +604,15 @@ // ── A Durable Object's SQLite, sockets and hibernation, in Node ── -function sqlOf(db: DatabaseSync) { +function sqlOf( + db: DatabaseSync, + failing: { when?: (query: string, params: unknown[]) => boolean }, +) { // prepared once for each text, as a Durable Object's own `sql.exec` keeps its statements const prepared = new Map<string, ReturnType<DatabaseSync["prepare"]>>(); return { exec(query: string, ...params: unknown[]) { + if (failing.when?.(query, params)) throw new Error("the store said no"); let statement = prepared.get(query); if (!statement) prepared.set(query, (statement = db.prepare(query))); const rows = statement.all(...(params as never[])) as Record<string, unknown>[]; @@ -503,6 +644,8 @@ const db = new DatabaseSync(":memory:"); const sockets = new Set<FakeSocket>(); const awake = new Map<string, { since: number; activities?: { key: string; text: string }[] }>(); + const catalogRows = new Map<string, CatalogRowInput>(); + const failing: { when?: (query: string, params: unknown[]) => boolean } = {}; const ctx = { getWebSockets: () => [...sockets], acceptWebSocket: (ws: FakeSocket) => void sockets.add(ws), @@ -526,7 +669,16 @@ sockets, awake, /** A new instance over the same storage and sockets: what a hibernation leaves. */ - wake: () => new ReactiveCatalog(sqlOf(db) as never, ctx as never, { awake: () => awake, seed }), + wake: () => + new ReactiveCatalog(sqlOf(db, failing) as never, ctx as never, { + awake: () => awake, + seed, + row: (path) => catalogRows.get(path), + }), + /** The catalog's own rows, which a write that the copy owes is made again from. */ + catalogRows, + /** A statement that this answers true for throws, as a store that fails does. */ + failing, [Symbol.dispose]: () => db.close(), }; } @@ -644,6 +796,7 @@ subs = new Map<string, ClientSub>(); errors: string[] = []; refusals: { kind: string; error: string }[] = []; + onChange: (message: { more?: true }) => void = () => {}; /** Messages since the test last looked. */ messages = 0; @@ -680,6 +833,7 @@ }); return; } + this.onChange(message); const rows = new Map<string, ModelRow>(message.rows.map((row: ModelRow) => [row.path, row])); for (const [name, from, rev, del, put] of message.d as [ string,
M core/itx/src/context/reactive-catalog.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/itx/src/iterate-context-durable-object.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/itx/src/iterate-context.ts
@@ -53,6 +53,7 @@ CatalogWatchRelay, catalogWatchRelayOf, isCatalogWatchTicket, + refuseLoadedCode, type CatalogWatchHandle, } from "./context/catalog-watch.ts"; import { lendRefusal } from "./context/lent-names.ts"; @@ -257,11 +258,7 @@ onFrame: unknown; options: unknown; }): Promise<CatalogWatchHandle> { - if (this.#caller.app) - throw codedError( - "FORBIDDEN", - "contexts.watch is a session's call: loaded code reads the catalog with contexts.list(options)", - ); + refuseLoadedCode(this.#caller, "watch"); if (typeof watch.onFrame !== "function") throw codedError( "INVALID_INPUT",
M core/lib/src/api.ts
Not shown: the change is larger than this page shows. A clone has it.