Merge kernel main (9be54f2) into reactive-catalog
Jonas Templestein, 2026-11-26 23:29 UTC · d8ca1e69cfbf952e72590e2875b31601fbc22e69 · a merge of d91b7a3 and 9be54f2, shown against d91b7a3
6 files changed
- A core/itx/src/context/answer-body.test.ts
- A core/itx/src/context/answer-body.ts
- M core/itx/src/context/residency.ts
- M core/itx/src/iterate-context-durable-object.ts
- A core/mind-worker/src/library/capnweb-answer-body.test.ts
- A core/mind-worker/src/library/fixtures/capnweb-answer-body.ts
A core/itx/src/context/answer-body.test.ts
@@ -0,0 +1,137 @@ +import { afterEach, beforeEach, expect, test, vi } from "vitest"; +import { ANSWER_BODY_UNREAD_AFTER_MS, untilBodyEnds, type BodyEnd } from "./answer-body.ts"; + +beforeEach(() => { + vi.useFakeTimers(); +}); +afterEach(() => { + vi.useRealTimers(); +}); + +const encoder = new TextEncoder(); + +/** A body of `lines` lines, one each `everyMs`, and whether its reader cancelled it. */ +function slowBody(lines: number, everyMs: number) { + const seen = { cancelled: false }; + let line = 0; + const body = new ReadableStream<Uint8Array>({ + async pull(controller) { + if (line === lines) return controller.close(); + await new Promise((resolve) => setTimeout(resolve, everyMs)); + controller.enqueue(encoder.encode(`${line++}\n`)); + }, + cancel() { + seen.cancelled = true; + }, + }); + return { body, seen }; +} + +function watchedAnswer(answer: unknown) { + const ends: (BodyEnd | null)[] = []; + return { answer: untilBodyEnds(answer, (how) => ends.push(how)), ends }; +} + +test("an answer with no body has ended at once, and is handed on as it is", () => { + const data = { some: "data" }; + const empty = new Response(null, { status: 204 }); + expect(watchedAnswer(data)).toEqual({ answer: data, ends: [null] }); + expect(watchedAnswer(empty)).toEqual({ answer: empty, ends: [null] }); +}); + +test("a body that takes two minutes arrives whole, and ends once, when it closes", async () => { + const { body } = slowBody(240, 500); + const { answer, ends } = watchedAnswer( + new Response(body, { status: 201, headers: { "content-type": "text/event-stream" } }), + ); + const response = answer as Response; + expect([response.status, response.headers.get("content-type")]).toEqual([ + 201, + "text/event-stream", + ]); + const text = response.text(); + await vi.advanceTimersByTimeAsync(119_000); + expect(ends).toEqual([]); + await vi.advanceTimersByTimeAsync(1_000); + expect(await text).toBe(Array.from({ length: 240 }, (_, line) => `${line}\n`).join("")); + expect(ends).toEqual(["closed"]); +}); + +test("a chunk that is slow to come is not an unread body: its reader waits for it", async () => { + const { body } = slowBody(1, 5 * ANSWER_BODY_UNREAD_AFTER_MS); + const { answer, ends } = watchedAnswer(body); + const text = new Response(answer as ReadableStream).text(); + await vi.advanceTimersByTimeAsync(5 * ANSWER_BODY_UNREAD_AFTER_MS - 1); + expect(ends).toEqual([]); + await vi.advanceTimersByTimeAsync(1); + expect(await text).toBe("0\n"); + expect(ends).toEqual(["closed"]); +}); + +test("a watched body is a byte stream, and an empty chunk of its source is passed over", async () => { + const chunks = ["a", "", "b"].map((text) => encoder.encode(text)); + const body = new ReadableStream<Uint8Array>({ + pull(controller) { + const chunk = chunks.shift(); + if (chunk) controller.enqueue(chunk); + else controller.close(); + }, + }); + const { answer, ends } = watchedAnswer(body); + // only a byte stream gives a reader of this kind + const reader = (answer as ReadableStream<Uint8Array>).getReader({ mode: "byob" }); + reader.releaseLock(); + expect(await new Response(answer as ReadableStream).text()).toBe("ab"); + expect(ends).toEqual(["closed"]); +}); + +test("a body that its reader drops ends as cancelled, and its source is cancelled", async () => { + const { body, seen } = slowBody(1000, 100); + const { answer, ends } = watchedAnswer(new Response(body)); + const reader = (answer as Response).body!.getReader(); + const first = reader.read(); + await vi.advanceTimersByTimeAsync(100); + expect(new TextDecoder().decode((await first).value)).toBe("0\n"); + await reader.cancel("the reader left"); + expect(ends).toEqual(["cancelled"]); + expect(seen.cancelled).toBe(true); +}); + +test("a body whose source fails ends as errored, and its reader gets the error", async () => { + let fail: (error: Error) => void = () => {}; + const body = new ReadableStream<Uint8Array>({ + start(controller) { + fail = (error) => controller.error(error); + }, + }); + const { answer, ends } = watchedAnswer(body); + const read = (answer as ReadableStream<Uint8Array>).getReader().read(); + fail(new Error("the far end hung up")); + await expect(read).rejects.toThrow("the far end hung up"); + expect(ends).toEqual(["errored"]); +}); + +test("a body that nobody reads ends as unread after the bound, once", async () => { + const { body } = slowBody(10, 100); + const { answer, ends } = watchedAnswer(new Response(body)); + await vi.advanceTimersByTimeAsync(ANSWER_BODY_UNREAD_AFTER_MS - 1); + expect(ends).toEqual([]); + await vi.advanceTimersByTimeAsync(1); + expect(ends).toEqual(["unread"]); + // the body is left as it is: a reader that comes back gets it, and no second end is said + const text = (answer as Response).text(); + await vi.advanceTimersByTimeAsync(1_000); + expect(await text).toBe(Array.from({ length: 10 }, (_, line) => `${line}\n`).join("")); + expect(ends).toEqual(["unread"]); +}); + +test("a reader that stops asking mid-body ends it as unread", async () => { + const { body } = slowBody(10, 100); + const { answer, ends } = watchedAnswer(body); + const reader = (answer as ReadableStream<Uint8Array>).getReader(); + const first = reader.read(); + await vi.advanceTimersByTimeAsync(100); + await first; + await vi.advanceTimersByTimeAsync(ANSWER_BODY_UNREAD_AFTER_MS); + expect(ends).toEqual(["unread"]); +});
A core/itx/src/context/answer-body.ts
@@ -0,0 +1,80 @@ +// answer-body.ts — WHEN AN ANSWER HAS ENDED. A call whose answer is a Response or a stream has +// answered with its first byte still to come: the body arrives later, over whatever the call used +// (a held connection's socket, a lent stub's session). `untilBodyEnds` hands the answer on with +// its body watched, and says once how the body ended. No workerd import: the unit test runs it in +// Node (answer-body.test.ts). + +/** How long a body may stay with nobody asking for its next chunk before it counts as left + * unread. A reader of a live stream asks again at once, also when the chunk is slow to come. */ +export const ANSWER_BODY_UNREAD_AFTER_MS = 60_000; + +/** `closed`: read to its end. `errored`: its source failed. `cancelled`: its reader dropped it. + * `unread`: nobody asked for a chunk for `ANSWER_BODY_UNREAD_AFTER_MS`; the body itself is left + * as it is, and a reader that comes back still gets it. */ +export type BodyEnd = "closed" | "errored" | "cancelled" | "unread"; + +/** `answer` as it is, unless it is a Response with a body or a stream: then the same answer with + * its body watched. `ended` is called once: at once (`null`) for an answer with no body, else + * when the body ends. */ +export function untilBodyEnds( + answer: unknown, + ended: (how: BodyEnd | null) => void, + unreadAfterMs = ANSWER_BODY_UNREAD_AFTER_MS, +): unknown { + if (answer instanceof Response && answer.body) + return new Response(watched(answer.body, ended, unreadAfterMs), answer); + if (answer instanceof ReadableStream) return watched(answer, ended, unreadAfterMs); + ended(null); + return answer; +} + +function watched( + body: ReadableStream<Uint8Array>, + ended: (how: BodyEnd) => void, + unreadAfterMs: number, +): ReadableStream<Uint8Array> { + const reader = body.getReader(); + let over = false; + let unread: ReturnType<typeof setTimeout> | undefined; + const end = (how: BodyEnd) => { + clearTimeout(unread); + if (over) return; + over = true; + ended(how); + }; + const nobodyAsks = () => { + unread = setTimeout(() => end("unread"), unreadAfterMs); + }; + nobodyAsks(); + // No queue of its own: `pull` runs only while a read waits, so a pull is a reader that asks. + // A byte stream, as the body was: Workers RPC carries no other kind of stream. + return new ReadableStream( + { + type: "bytes", + async pull(controller) { + clearTimeout(unread); + let next: ReadableStreamReadResult<Uint8Array>; + try { + // a byte stream takes no empty chunk + do next = await reader.read(); + while (!next.done && next.value.byteLength === 0); + } catch (error) { + end("errored"); + throw error; + } + if (next.done) { + end("closed"); + controller.close(); + return; + } + controller.enqueue(next.value); + if (!over) nobodyAsks(); + }, + async cancel(reason) { + end("cancelled"); + await reader.cancel(reason); + }, + }, + { highWaterMark: 0 }, + ); +}
M core/itx/src/context/residency.ts
@@ -68,7 +68,10 @@ } // Borrowed stubs and open sockets keep the actor resident on the edge (workerd#6800), so a timer - // releases them. A pending timer itself holds off eviction and hibernation, billed. + // releases them. A pending timer itself holds off eviction and hibernation, billed. A pin call + // is a use of them: a library hop, a call of a lent stub, and every call into the context until + // its answer's body has ended (iterate-context-durable-object.ts `invoke`), so that nothing is + // let go while an answer still arrives over it. #pinReleaseTimer: ReturnType<typeof setTimeout> | undefined; #pinCallsInFlight = 0;
M core/itx/src/iterate-context-durable-object.ts
@@ -67,6 +67,7 @@ import { ancestorPathsOf, DurableObjectNameCodec } from "./context/paths.ts"; import { expressionFetchErrorAnswer } from "./unavailable.ts"; import { contexts, deployId, itxEntrypointFor, itxHost, type LibraryItx } from "./host.ts"; +import { untilBodyEnds } from "./context/answer-body.ts"; import { Connections } from "./context/connections.ts"; import { executeScript, runSettlementOf, settlementOfRun } from "./context/run.ts"; import { metrics } from "./metrics.ts"; @@ -1479,18 +1480,40 @@ ); this.#awakeSocket.entered(); this.#residency.inboundCallStarted(); + // THE CALL USES THIS CONTEXT'S PINS UNTIL ITS ANSWER HAS ENDED, BODY AND ALL. A held + // connection's socket and a lent stub are let go 30 s after the last use of them + // (residency.ts), and an answer's body arrives over them after the call has answered: a + // model's answer through a lent AI binding takes minutes. Until 26 Nov 2026 only the hop that + // opened a connection counted, so every such body was cut 30 s after that hop ("ReadableStream + // received over RPC disconnected prematurely"). + this.#residency.pinCallStarted(); // An approved act's text is for this one call (`Caller.approvedAct`). const { approvedAct, ...asCalled } = caller; - const result = await ( - approvedAct - ? this.#callerStorage.run(asCalled, () => - this.#itxExpressionResolver.invokeApproved(approvedAct, call, args), - ) - : this.#invokeInProcess(call, args, caller) - ).finally(() => this.#residency.inboundCallEnded(caller.app === true)); + let result: unknown; + try { + result = await ( + approvedAct + ? this.#callerStorage.run(asCalled, () => + this.#itxExpressionResolver.invokeApproved(approvedAct, call, args), + ) + : this.#invokeInProcess(call, args, caller) + ).finally(() => this.#residency.inboundCallEnded(caller.app === true)); + } catch (error) { + this.#residency.pinCallEnded(); + throw error; + } // Every Workers-RPC caller arrives here, so the caller's session ends with the call, whatever // the caller disposes. - return itxAnswerDetachedFromSession(result, call, args); + return untilBodyEnds(itxAnswerDetachedFromSession(result, call, args), (how) => { + this.#residency.pinCallEnded(); + // a body that nobody reads must not keep the pins, and with them this context, for good + if (how === "unread") + console.warn({ + event: "iterate-context.answer-body-unread", + path: this.#durableObjectAddress.path, + call: normalizedItxExpression(call).map(itxExpressionStepName).join(".").slice(0, 200), + }); + }); } // A thrown error can lose its `code` between runtimes (since workerd v1.20261030.1), and a gradual
A core/mind-worker/src/library/capnweb-answer-body.test.ts
@@ -0,0 +1,118 @@ +// capnweb-answer-body.test.ts — a streamed answer of a held capnweb connection, in workerd +// (./fixtures/capnweb-answer-body.ts). A context keeps a connection's WebSocket open, and lets it +// go 30 s after its last use, so that it does not stay in memory, billed (core-itx residency.ts). +// An answer whose body still arrives is a use: on 26 Nov 2026 every model answer of iterate.com's +// agents that took longer than 30 s was cut ("ReadableStream received over RPC disconnected +// prematurely"), because the release counted only the call that opened the connection. +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; +import { Miniflare } from "miniflare"; +import { COMPATIBILITY_DATE } from "iterate/compatibility-date"; +import { expect, test } from "vitest"; + +const linesOf = (count: number) => Array.from({ length: count }, (_, line) => `${line}\n`).join(""); + +test.concurrent( + "a body that takes 36 s arrives whole, and its connection is let go after it", + { timeout: 120_000 }, + async () => { + await using mind = await mindWithUpstream(); + const answer = await mind.answer({ lines: 72, everyMs: 500 }); + expect(await answer.text()).toBe(linesOf(72)); + // let go after the body's end, not before: one socket, closed once the context is quiet + expect(await mind.seen()).toMatchObject({ opened: 1, closed: 0 }); + expect(await mind.seenWhen(({ closed }) => closed === 1)).toMatchObject({ opened: 1 }); + }, +); + +test.concurrent( + "a short body arrives whole, and a body that its reader drops ends at the upstream", + { timeout: 120_000 }, + async () => { + await using mind = await mindWithUpstream(); + const short = await mind.answer({ lines: 3, everyMs: 10 }); + expect(await short.text()).toBe(linesOf(3)); + // a bare stream, with no Response around it, crosses Workers RPC as the byte stream it was + const bare = await mind.answer({ lines: 3, everyMs: 10 }, "stream"); + expect(await bare.text()).toBe(linesOf(3)); + + const dropped = await mind.answer({ lines: 1000, everyMs: 100 }); + const reader = dropped.body!.getReader(); + expect(new TextDecoder().decode((await reader.read()).value)).toMatch(/^0\n/); + await reader.cancel(); + // the upstream stops making the body, and the connection is let go like any quiet one + expect(await mind.seenWhen(({ bodiesCancelled }) => bodiesCancelled === 1)).toMatchObject({ + opened: 1, + }); + expect(await mind.seenWhen(({ closed }) => closed === 1)).toMatchObject({ opened: 1 }); + }, +); + +type Seen = { opened: number; closed: number; bodiesCancelled: number }; + +async function mindWithUpstream() { + const bundled = await build({ + entryPoints: [ + fileURLToPath(new URL("./fixtures/capnweb-answer-body.ts", import.meta.url).href), + ], + bundle: true, + write: false, + format: "esm", + platform: "neutral", + mainFields: ["module", "main"], + conditions: ["workerd"], + target: "es2022", + external: ["cloudflare:*", "node:*"], + }); + const runtime = new Miniflare({ + workers: [ + { + config: { + name: "mind", + compatibilityDate: COMPATIBILITY_DATE, + compatibilityFlags: ["nodejs_compat", "allow_irrevocable_stub_storage"], + manifest: { + mainModule: "worker.js", + modules: { + "worker.js": { type: "esm" as const, contents: bundled.outputFiles[0]!.text }, + }, + }, + env: { + CONTEXTS: { + type: "durable-object", + worker: "mind", + exportName: "IterateContextDurableObject", + }, + UPSTREAM: { type: "durable-object", worker: "mind", exportName: "Upstream" }, + CF_VERSION_METADATA: { type: "version-metadata" }, + }, + exports: { + IterateContextDurableObject: { type: "durable-object", storage: "sqlite" }, + Upstream: { type: "durable-object", storage: "sqlite" }, + ItxEntrypoint: { type: "worker" }, + }, + }, + }, + ], + }); + await runtime.ready; + const seen = async () => + (await (await runtime.dispatchFetch("http://mind.test/seen")).json()) as Seen; + return { + answer: ( + { lines, everyMs }: { lines: number; everyMs: number }, + as: "answer" | "stream" = "answer", + ) => runtime.dispatchFetch(`http://mind.test/${as}?lines=${lines}&everyMs=${everyMs}`), + seen, + /** What the upstream saw once `reached` holds: asked each half second, for 45 s at most. */ + seenWhen: async (reached: (seen: Seen) => boolean) => { + for (let attempt = 0; ; attempt++) { + const now = await seen(); + if (reached(now)) return now; + if (attempt === 90) throw new Error(`not reached in 45 s: ${JSON.stringify(now)}`); + await new Promise((resolve) => setTimeout(resolve, 500)); + } + }, + [Symbol.asyncDispose]: () => runtime.dispose(), + }; +}
A core/mind-worker/src/library/fixtures/capnweb-answer-body.ts
@@ -0,0 +1,105 @@ +// capnweb-answer-body.ts — a context that holds a capnweb connection whose answers are streamed +// bodies, run in workerd by ../capnweb-answer-body.test.ts. One Worker: the kernel (core-itx), the +// connection of ../capnweb.ts as the root `connectToCapnweb`, and an upstream capnweb server as +// the egress, which answers a Response whose body arrives line by line (as a model's answer does +// through `itx.ai` of a mind that iterate Cloud lends its AI binding to). +import { DurableObject, env } from "cloudflare:workers"; +import { newWebSocketRpcSession, RpcTarget } from "capnweb"; +import { contextAt, defineItxHost } from "core-itx"; +import { connectToCapnweb } from "../capnweb.ts"; + +export { IterateContextDurableObject, ItxEntrypoint } from "core-itx"; + +type Env = { UPSTREAM: DurableObjectNamespace<Upstream> }; + +const upstreamOf = () => (env as unknown as Env).UPSTREAM.getByName("upstream"); + +const encoder = new TextEncoder(); + +/** What the upstream saw: sockets opened and closed, and bodies whose reader went away. */ +const seen = { opened: 0, closed: 0, bodiesCancelled: 0 }; + +class SlowAnswers extends RpcTarget { + /** A Response whose body is `lines` lines, one each `everyMs`. */ + answer({ lines, everyMs }: { lines: number; everyMs: number }): Response { + let line = 0; + return new Response( + new ReadableStream<Uint8Array>({ + async pull(controller) { + if (line === lines) return controller.close(); + await scheduler.wait(everyMs); + controller.enqueue(encoder.encode(`${line++}\n`)); + }, + cancel() { + seen.bodiesCancelled += 1; + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ); + } + /** The same lines as a bare stream, with no Response around it. */ + stream(input: { lines: number; everyMs: number }): ReadableStream<Uint8Array> { + return this.answer(input).body!; + } +} + +/** The upstream: a capnweb server on each socket. A Durable Object, so one isolate holds `seen`. */ +export class Upstream extends DurableObject { + override async fetch(request: Request): Promise<Response> { + if (new URL(request.url).pathname === "/seen") return Response.json(seen); + if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") + return new Response("capnweb over a WebSocket only\n", { status: 426 }); + const pair = new WebSocketPair(); + const server = pair[1]; + server.accept(); + seen.opened += 1; + server.addEventListener("close", () => { + seen.closed += 1; + }); + newWebSocketRpcSession(server as unknown as WebSocket, new SlowAnswers()); + return new Response(null, { status: 101, webSocket: pair[0] }); + } +} + +defineItxHost({ + firstPartyFacets: {}, + egress: (request) => upstreamOf().fetch(request), + roots: { + connectToCapnweb: { + description: "the connection of ../capnweb.ts, as the mind Worker's library gives it", + build: ({ itx, connections }) => + connections && + ((url: string) => + connections.memoized(["capnweb", url], true, () => connectToCapnweb(itx, url))), + }, + }, +}); + +export default { + async fetch(request: Request) { + const url = new URL(request.url); + if (url.pathname === "/seen") return upstreamOf().fetch("https://upstream.example/seen"); + if (url.pathname !== "/answer" && url.pathname !== "/stream") + return new Response("Not found\n", { status: 404 }); + // as a member's call: the answer is the upstream's Response, handed on by the root context's + // object over Workers RPC + const answer = await contextAt("/").invoke( + [ + "itx", + ["connectToCapnweb", "wss://upstream.example/api"], + [ + url.pathname.slice(1), + { + lines: Number(url.searchParams.get("lines")), + everyMs: Number(url.searchParams.get("everyMs")), + }, + ], + ], + [], + { principal: { actor: "usr_aaaaabbbbbccccc", email: "member@mind.example" } }, + ); + if (answer instanceof Response) return answer; + if (answer instanceof ReadableStream) return new Response(answer); + return new Response(`no body: ${JSON.stringify(answer)}\n`, { status: 500 }); + }, +} satisfies ExportedHandler;