A refusal of a watch has its own code, a batch ends with the last frame that goes, and the copy's failure stays above the catalog
Jonas Templestein, 2026-11-26 23:11 UTC · 3f3c365d3cffd88bc31b7b6b3f027427c878f02a · parent f250467
7 files changed
- M core/itx/src/context/catalog-watch.test.ts
- M core/itx/src/context/catalog-watch.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/lib/src/api.ts
- M core/lib/src/lib.ts
M core/itx/src/context/catalog-watch.test.ts
@@ -196,17 +196,74 @@ ); }); -test("a query that the catalog refuses rejects the call, and leaves no watch and no socket", async () => { +test.for([ + { kind: "query", error: "not a query of the catalog", code: "INVALID_INPUT" }, + { + kind: "limit", + error: "the catalog holds at most 512 different live queries", + code: "WATCH_LIMIT", + }, + // the catalog's own failure has no code: a watcher reads the catalog in another way + { kind: "failed", error: "the catalog failed, and its log says why", code: undefined }, +])( + "a refusal of the catalog ($kind) rejects the call with its own code, and leaves no watch and no socket", + async ({ kind, error, code }) => { + const far = catalog(); + const relay = far.relay(); + const watching = relay.watch(ticket({ limit: 5 }), () => {}); + const socket = await far.asked(); + socket.say({ sub: "w1", kind, error }); + const refusal = await watching.then( + () => undefined, + (thrown: Error & { code?: string }) => thrown, + ); + expect(refusal).toMatchObject({ message: `contexts.watch: ${error}` }); + expect(refusal?.code).toBe(code); + expect(socket).toMatchObject({ closed: true }); + }, +); + +test("a batch ends with the last frame that goes: an entry for a watch that is gone, or is asked again, ends none", async () => { const far = catalog(); const relay = far.relay(); - const watching = relay.watch(ticket({ limit: 5 }), () => {}); - const socket = await far.asked(); - socket.say({ sub: "w1", error: "the catalog holds at most 512 live queries" }); - await expect(watching).rejects.toMatchObject({ - code: "INVALID_INPUT", - message: expect.stringContaining("at most 512 live queries"), + const batch: [string, boolean][] = []; + const watches = ["first", "second", "third"].map((name, at) => + relay.watch(ticket({ limit: at + 1 }), (frame) => batch.push([name, !!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 third watch is gone when the catalog's message for all three comes + third![Symbol.dispose](); + socket.say({ + gen: "g", + rows: [{ path: "/a" }], + d: [ + ["w1", 1, 2, [], ["/a"]], + ["w2", 1, 2, [], ["/a"]], + ["w3", 1, 2, [], ["/a"]], + ], }); - expect(socket).toMatchObject({ closed: true }); + expect(batch).toEqual([ + ["first", true], + ["second", false], + ]); + // and the second has a gap in the next one: it is asked again, and the first ends the batch + batch.length = 0; + socket.say({ + gen: "g", + rows: [{ path: "/b" }], + d: [ + ["w1", 2, 3, [], ["/b"]], + ["w2", 7, 8, [], ["/b"]], + ], + }); + expect(batch).toEqual([["first", false]]); + expect(socket.sent.at(-1)).toEqual({ op: "subscribe", sub: "w2", query: { limit: 2 } }); }); test("the watcher's dispose takes the query off, and the last watch closes the socket", async () => {
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 { unavailableError } from "../unavailable.ts"; import { redial } from "./redial.ts"; import { CatalogRefusal, normalizeQuery } from "./reactive-catalog.ts"; import { @@ -138,7 +139,11 @@ z.tuple([z.string(), z.number(), z.number(), z.array(z.string()), z.array(z.string())]), ), }), - z.object({ sub: z.string().optional(), error: z.string() }), + z.object({ + sub: z.string().optional(), + error: z.string(), + kind: z.enum(["query", "limit", "failed"]).optional(), + }), ]); type DialAnswer = { status: number; webSocket?: WebSocket | null; body?: ReadableStream | null }; @@ -169,7 +174,7 @@ * where the call's answer and a call of the function travel apart, in no order. Rejects with * the catalog's reason when it refuses the query. */ async watch(ticket: CatalogWatchTicket, onFrame: FrameCallback): Promise<CatalogWatchHandle> { - if (this.#over) throw codedError("UNAVAILABLE", "contexts.watch: the session ended"); + if (this.#over) throw unavailableError("disconnected", "contexts.watch: the session ended"); const { query, cursor } = ticket.$itxCatalogWatch; // dup first: the stub is the call's alone, and a watch outlives the call const callback = onFrame.dup ? onFrame.dup() : onFrame; @@ -187,7 +192,7 @@ this.#watches.delete(sub); if (watch.answered) { clearTimeout(watch.answered.timer); - watch.answered.reject(codedError("UNAVAILABLE", `contexts.watch: ${reason}`)); + watch.answered.reject(unavailableError("disconnected", `contexts.watch: ${reason}`)); } disposeRpcStub(callback); settleEnded(reason); @@ -206,7 +211,9 @@ resolve, reject, timer: setTimeout( - () => reject(codedError("UNAVAILABLE", "contexts.watch: the catalog did not answer")), + // our own deadline is an overload: the caller may ask again later, never at once + () => + reject(unavailableError("overloaded", "contexts.watch: the catalog did not answer")), ANSWER_DEADLINE_MS, ), }; @@ -257,8 +264,8 @@ .then(async (answer) => { if (answer.status !== 101 || !answer.webSocket) { await answer.body?.cancel(); - throw codedError( - "UNAVAILABLE", + throw unavailableError( + "disconnected", `contexts.watch: the catalog answered the dial ${answer.status}`, ); } @@ -266,7 +273,7 @@ // the session ended, or its last watch went, while the dial was on its way if (this.#over || this.#watches.size === 0) { answer.webSocket.close(1000, "no watch is left"); - throw codedError("UNAVAILABLE", "contexts.watch: the session ended"); + throw unavailableError("disconnected", "contexts.watch: the session ended"); } this.#attach(answer.webSocket); return answer.webSocket; @@ -313,7 +320,7 @@ () => this.#over || this.#watches.size === 0, REDIAL_DEADLINE_MS, ).then((redialed) => { - if (!redialed) throw codedError("UNAVAILABLE", "contexts.watch: the session ended"); + if (!redialed) throw unavailableError("disconnected", "contexts.watch: the session ended"); if ("gaveUp" in redialed) { console.error({ event: "catalog-watch.redial-failed", @@ -324,8 +331,8 @@ }); for (const watch of [...this.#watches.values()]) watch.end("the catalog could not be reached again: watch again"); - throw codedError( - "UNAVAILABLE", + throw unavailableError( + "disconnected", "contexts.watch: the catalog could not be reached again: watch again", ); } @@ -372,30 +379,50 @@ if ("error" in message) { const watch = this.#watches.get(message.sub || ""); if (!watch) return; - const refusal = codedError("INVALID_INPUT", `contexts.watch: ${message.error}`); if (!watch.answered) return watch.end(message.error); clearTimeout(watch.answered.timer); - watch.answered.reject(refusal); + // Each kind has its own code, so that a watcher knows what to do: write another query, + // dispose a watch, or read the catalog in another way (`contexts.list`). The catalog's own + // failure has no code: it is a defect, and the catalog reported it. + const text = `contexts.watch: ${message.error}`; + watch.answered.reject( + message.kind === "query" + ? codedError("INVALID_INPUT", text) + : message.kind === "limit" + ? codedError("WATCH_LIMIT", text) + : new Error(text), + ); return; } if ("d" in message) { const rows = new Map(message.rows.map((row) => [row.path, row])); - message.d.forEach(([sub, from, rev, del, put], at) => { + 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 - if (!watch || watch.rev < 0) return; - if (watch.gen !== message.gen || watch.rev !== from) return this.#askAgain(sub); + if (!watch || watch.rev < 0) continue; + if (watch.gen !== message.gen || watch.rev !== from) { + this.#askAgain(sub); + continue; + } watch.rev = rev; - void this.#send(watch, { - type: "change", - gen: message.gen, - from, - rev, - del, - rows: put.map((path) => rows.get(path)), - ...(at < message.d.length - 1 && { more: true }), - }); - }); + frames.push([ + watch, + { + type: "change", + gen: message.gen, + from, + rev, + 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), + ); return; } const watch = this.#watches.get(message.sub);
M core/itx/src/context/reactive-catalog.test.ts
@@ -399,6 +399,57 @@ expect(later.watches({ verify: true })).toMatchObject({ active: true, rows: 2, faults: [] }); }); +test("a full socket and a full catalog refuse a query as a limit, not as a fault of the query", () => { + using object = fakeObject(); + const catalog = object.wake(); + catalog.fill(); + // eight sockets, each with as many queries as one may hold, all of them different + const clients = Array.from( + { length: CATALOG_LIMITS.windows / CATALOG_LIMITS.subsPerSocket }, + () => { + const client = new Client(); + client.connect(catalog); + return client; + }, + ); + clients.forEach((client, at) => { + for (let index = 0; index < CATALOG_LIMITS.subsPerSocket; index++) + client.subscribe(catalog, `s${index}`, { + where: { n: at * CATALOG_LIMITS.subsPerSocket + index }, + }); + }); + expect(catalog.watches().windows).toHaveLength(CATALOG_LIMITS.windows); + // one more for a socket that is full + clients[0]!.subscribe(catalog, "one-more", { limit: 3 }); + expect(clients[0]!).toMatchObject({ + refusals: [{ kind: "limit", error: expect.stringContaining("at most 64 watches") }], + }); + // one more for the catalog, on a socket that has room + const late = new Client(); + late.connect(catalog); + late.subscribe(catalog, "q", { limit: 3 }); + expect(late).toMatchObject({ + refusals: [ + { kind: "limit", error: expect.stringContaining("at most 512 different live queries") }, + ], + }); + // a query that another socket watches already is no new one + late.subscribe(catalog, "shared", { where: { n: 5 } }); + expect(late.refusals).toHaveLength(1); + // a socket that ended with no close event: at the limit its windows go, and there is room + clients[1]!.socket!.close(); + object.sockets.delete(clients[1]!.socket!); + const woken = object.wake(); + late.subscribe(woken, "q", { limit: 3 }); + expect(late.refusals).toHaveLength(1); + expect(woken.watches().windows).toHaveLength( + CATALOG_LIMITS.windows - CATALOG_LIMITS.subsPerSocket + 1, + ); + // a query that cannot be answered is the query's own fault + late.subscribe(woken, "bad", { limit: 0 }); + expect(late.refusals.at(-1)).toMatchObject({ kind: "query" }); +}); + test("one write is one message for a socket, over all of its queries", () => { using object = fakeObject(); const catalog = object.wake(); @@ -592,6 +643,7 @@ socket: FakeSocket | undefined; subs = new Map<string, ClientSub>(); errors: string[] = []; + refusals: { kind: string; error: string }[] = []; /** Messages since the test last looked. */ messages = 0; @@ -606,7 +658,10 @@ const message = JSON.parse(raw); if (message.hello) return; this.messages += 1; - if (message.error) return void this.errors.push(message.error); + if (message.error) { + this.refusals.push({ kind: message.kind, error: message.error }); + return void this.errors.push(message.error); + } if (message.unsubscribed) return; if (message.sub) { const sub = this.subs.get(message.sub)!;
M core/itx/src/context/reactive-catalog.ts
@@ -48,7 +48,10 @@ // a change: { gen, rows: [rows], d: [[sub, from, rev, [paths to delete], [paths to put]]] } // ONE message for each socket and write (or batch of writes), over all of the // socket's queries, so a join never sees half of a write. `from` is the revision -// of the query's frame before. +// of the query's frame before. (A batch of writes that is longer than +// `CATALOG_LIMITS.messageChars` is cut into several messages.) +// a refusal: { sub, kind: "query" | "limit" | "failed", error }: the query cannot be +// answered, a limit is reached, or the catalog itself failed // // A watcher that comes back sends its cursor `{ gen, rev, q, bound }`: the generation, the // revision of its last frame, the name of what the query selects, and the sort key of the last row @@ -57,6 +60,7 @@ // and the watcher never had it. import { z } from "zod"; import type { CatalogOrder, CatalogWatches } from "iterate/api"; +import { reportIssue } from "iterate/lib"; import type { AwakeContextState } from "./awake.ts"; import { activeContextActivities } from "./context-activity-stack.ts"; @@ -89,6 +93,10 @@ /** A refusal that the watcher or the writer caused: its message goes back to them. */ export class CatalogRefusal extends Error {} +/** A refusal that is no fault of the query: the catalog, or the watcher's socket, holds as many + * live queries as it may. */ +export class CatalogLimit extends Error {} + // ── The order ── /** No lone surrogate: such a text has one UTF-8 form, which is what SQLite stores and compares. */ @@ -1184,19 +1192,27 @@ if (windowId !== undefined) this.#unwatch(windowId, sid, request.sub); this.#send(ws, JSON.stringify({ sub: request.sub, unsubscribed: true })); } catch (error) { - const refused = error instanceof CatalogRefusal; - if (!refused) { + // What the watcher is told: its query cannot be answered, a limit is reached, or the + // catalog itself failed. The session's end gives each its own code (catalog-watch.ts). + const kind = + error instanceof CatalogRefusal + ? "query" + : error instanceof CatalogLimit + ? "limit" + : "failed"; + if (kind === "failed") { this.#forget(); - console.info({ - event: "context.reactive-catalog-failed", - message: error instanceof Error ? error.message : String(error), - }); + reportIssue("reactive-catalog.watch", error, { sub: request?.sub }); } this.#send( ws, JSON.stringify({ sub: request?.sub, - error: refused ? error.message : "the catalog failed, and its log says why", + kind, + error: + kind !== "failed" && error instanceof Error + ? error.message + : "the catalog failed, and its log says why", }), ); } @@ -1206,7 +1222,9 @@ const { query, key } = normalizeQuery(spec); const had = socket.subs.get(sub); if (had === undefined && socket.subs.size >= CATALOG_LIMITS.subsPerSocket) - throw new CatalogRefusal(`a socket holds at most ${CATALOG_LIMITS.subsPerSocket} queries`); + throw new CatalogLimit( + `a session holds at most ${CATALOG_LIMITS.subsPerSocket} watches: dispose one first`, + ); // the awake list is the sockets: it needs no row if (query.kind !== "awake") this.fill(); const windows = this.#loadWindows(); @@ -1219,8 +1237,8 @@ for (const stale of [...windows.values()]) if (!this.#watchers.get(stale.id)?.size) this.#dropWindow(stale); if (windows.size >= CATALOG_LIMITS.windows) - throw new CatalogRefusal( - `the catalog holds at most ${CATALOG_LIMITS.windows} live queries`, + throw new CatalogLimit( + `the catalog holds at most ${CATALOG_LIMITS.windows} different live queries`, ); const driver = query.kind === "range" ? this.#chooseDriver(query) : 0; rows = query.kind === "range" ? this.#windowRows(query, driver) : undefined;
M core/itx/src/iterate-context-durable-object.ts
@@ -24,6 +24,7 @@ } from "iterate/expression"; import type { CatalogWatches, + ContextActivity, ContextListing, ContextListOptions, RewriteRuleListEntry, @@ -114,11 +115,7 @@ } from "./context/context-activity-stack.ts"; import { ContextCatalog, type ContextSummaryMessage } from "./context/context-catalog.ts"; import { CONTEXT_DESCRIBED_TYPE, ContextSummaryTracker } from "./context/context-summary.ts"; -import { - CatalogRefusal, - ReactiveCatalog, - type CatalogRowInput, -} from "./context/reactive-catalog.ts"; +import { CatalogRefusal, ReactiveCatalog } from "./context/reactive-catalog.ts"; import { egress } from "./context/egress.ts"; import { SNAPSHOT_TTL_MS, @@ -1213,10 +1210,15 @@ /** A context woke, said what it does now, or went quiet: who watches the awake list hears of * it. `closing` is the socket whose close is being handled. With no watcher this reads - * nothing. */ + * nothing. It never throws. */ #awakeListChanged(path: string, closing?: WebSocket): void { - if (!this.#reactiveCatalog.awakeWatched()) return; - this.#reactiveCatalog.awakeChanged(path, awakeContexts(this.ctx, closing).get(path)); + try { + if (!this.#reactiveCatalog.awakeWatched()) return; + this.#reactiveCatalog.awakeChanged(path, awakeContexts(this.ctx, closing).get(path)); + } catch (error) { + // the awake socket's accept, summary and close go on, whatever the watched copy does + reportIssue("iterate-context.reactive-catalog", error, { path }); + } } #traceAlarm( @@ -1712,18 +1714,11 @@ // A context's summary: one durable row written, live activities kept on the socket attachment. if (isAwakeWebSocket(this.ctx, ws)) { const { path, activities: saidBefore } = awakeContextOf(ws); - let answer = AWAKE_SUMMARY_KEPT; + let kept: ReturnType<ContextCatalog["store"]> | undefined; try { - const { activities, row } = this.#contextCatalog.store( - path, - typeof message === "string" ? message : "", - ); - setAwakeActivities(ws, activities); - if (JSON.stringify(activities || []) !== JSON.stringify(saidBefore || [])) - this.#awakeListChanged(path); - if (row && this.#reactiveCatalog.active()) this.#keepWatchedRow(row); + kept = this.#contextCatalog.store(path, typeof message === "string" ? message : ""); + setAwakeActivities(ws, kept.activities); } catch (error) { - answer = AWAKE_SUMMARY_REFUSED; console.info({ event: "context.catalog-summary-refused", path, @@ -1733,10 +1728,11 @@ // The context waits for this before it closes its socket (context/awake.ts). The runtime // holds it until the row is durable. try { - ws.send(answer); + ws.send(kept ? AWAKE_SUMMARY_KEPT : AWAKE_SUMMARY_REFUSED); } catch { // a socket that is closing: the context says its summary again } + if (kept) this.#tellWatchers(path, kept, saidBefore); return; } if (this.#reactiveCatalog.isWatchWebSocket(ws)) @@ -1745,19 +1741,36 @@ this.#rpcStubFetch.handleWebSocketMessage(ws, message); } - /** A row that the catalog kept is also the row of the copy that answers watched queries. One - * that the copy refuses (a path it cannot order) is taken out of it: a watcher then sees no - * row of that context, and never an old one. */ - #keepWatchedRow(row: CatalogRowInput): void { + /** WHAT THE CATALOG KEPT GOES ON TO WHOEVER WATCHES: the awake list when the context's live + * activities changed, and the copy that answers watched queries (context/reactive-catalog.ts) + * once a mind has watched. A row that the copy refuses (a path it cannot order) is taken out + * of it: a watcher then sees no row of that context, and never an old one. + * + * THE COPY IS ABOVE THE CATALOG, AND ITS FAILURE STAYS THERE: the catalog's row is kept and the + * context has its answer before this runs, and what fails here is reported and goes no + * further. */ + #tellWatchers( + path: string, + kept: ReturnType<ContextCatalog["store"]>, + saidBefore: ContextActivity[] | undefined, + ): void { + if (JSON.stringify(kept.activities || []) !== JSON.stringify(saidBefore || [])) + this.#awakeListChanged(path); try { - this.#reactiveCatalog.upsert(row); + if (!kept.row || !this.#reactiveCatalog.active()) return; + try { + this.#reactiveCatalog.upsert(kept.row); + } catch (error) { + if (!(error instanceof CatalogRefusal)) throw error; + console.info({ + event: "context.reactive-catalog-row-refused", + path, + message: error.message, + }); + this.#reactiveCatalog.deleteMany([path]); + } } catch (error) { - if (error instanceof CatalogRefusal) this.#reactiveCatalog.deleteMany([row.path]); - console.info({ - event: "context.reactive-catalog-row-refused", - path: row.path, - message: error instanceof Error ? error.message : String(error), - }); + reportIssue("iterate-context.reactive-catalog", error, { path }); } }
M core/lib/src/api.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/lib.ts
@@ -30,6 +30,7 @@ /** The stable machine-readable codes — SCREAMING_SNAKE, defined once, both ends import this. */ type ErrorCode = | "SCHEDULE_LIMIT" // bounded pending/failed scheduled batches per context + | "WATCH_LIMIT" // itx.contexts.watch: the session holds its 64 watches, or the mind's catalog its 512 different live queries (core/itx/src/context/reactive-catalog.ts `CATALOG_LIMITS`): dispose a watch first | "PERSON_CALL_LIMIT" // one person's calls of person methods on one context, over the count for a minute (core/itx/src/context/facet-public-methods.ts): ask again in the next minute | "INVALID_INPUT" | "IDENTITY_CONFLICT" // verified login cannot replace another linked identity