iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / mind-worker / src / library / capnweb-answer-body.test.tsmain at 949894f

// 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(),
  };
}