/** * SLOW READ, PROVEN ON DEV (coordinator, 26 Nov 2026; affa8ae186 and e475533df5). One invented +1555 account: * 1. Headers: every answer is read for cotton-object-cold, cotton-alarm-running and cotton-alarm-busy. The cold one * is seen after idling (--idle N seconds) until the runtime lets the object go: the first read after says cold. * 2. Normal answers: five list_projects and five brief over MCP answer 200 with a result, as before, and carry no * header but the three above beyond what they carried before. * 3. A forced slow answer: a dev-only plant of sealed-shaped rows holds the object in one synchronous write while a * list_projects is sent; that read waits behind it. Its time and headers are printed, with the line the front * Worker logs for it (src/http.ts `slowLine`, the same function `toldSlow` runs). The Worker's log itself is read * with `wrangler tail` (dev) or a local wrangler dev's output. * 4. A definition change is seen at once (the cached parse, e475533df5): update_definition writes a table's * instructions over MCP and the very next request reads them back through the object's parsed definitions; * then the phone's definition act renames the table and the next MCP read sees the new name. * * pnpm -s exec tsx scripts/slow-read-proof.ts [--base ] [--code-file ] [--rows N] [--bytes N] [--idle S] * * Invented data only; nothing secret is printed. */ import { readFileSync } from "node:fs"; import { homedir } from "node:os"; import { signIn } from "./dev-seed/client.ts"; import { ALARM_BUSY_HEADER, ALARM_RUNNING_HEADER, COLD_HEADER, SLOW_ANSWER_MS, slowLine } from "../src/http.ts"; import { devBase } from "./dev-server"; const arg = (name: string, fallback?: string) => { const i = process.argv.indexOf(`--${name}`); return i > 0 ? process.argv[i + 1]! : fallback; }; const BASE = arg("base", devBase())!; if (BASE !== devBase() && !/^http:\/\/127\.0\.0\.1:\d+$/.test(BASE)) throw new Error("--base is the dev Worker or a local wrangler dev"); const CODE = readFileSync(arg("code-file", `${homedir()}/.cotton-credentials/cotton/dev-otp`)!, "utf8").replace(/\D/g, ""); const ROWS = Number(arg("rows", "20000")); const BYTES = Number(arg("bytes", "4000")); const NUMBER = `+1555${String(Math.floor(1_000_000 + Math.random() * 8_999_999))}`; const OURS = [COLD_HEADER, ALARM_RUNNING_HEADER, ALARM_BUSY_HEADER]; const say = (line: string) => console.log(`[slow-read] ${line}`); let failed = 0; function check(ok: boolean, what: string): void { if (!ok) failed++; say(`${ok ? "ok " : "FAIL"} ${what}`); } type Answer = { status: number; body: Record; ms: number; headers: Headers; response: Response }; async function call(method: string, path: string, bearer: string | null, body?: unknown): Promise { const started = Date.now(); const response = await fetch(`${BASE}${path}`, { method, headers: { "content-type": "application/json", ...(path === "/mcp" ? { accept: "application/json, text/event-stream" } : {}), ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body), }); const text = await response.text(); const ms = Date.now() - started; const json = text.trimStart().startsWith("{") ? text : (text.split("\n").find((l) => l.startsWith("data:"))?.slice(5) ?? ""); let parsed: Record = {}; try { parsed = json ? (JSON.parse(json) as Record) : {}; } catch { parsed = { text: text.slice(0, 200) }; } return { status: response.status, body: parsed, ms, headers: response.headers, response }; } const ours = (h: Headers) => OURS.map((k) => `${k.replace("cotton-", "")}=${h.get(k) ?? "-"}`).join(" "); let rpc = 0; async function tool(token: string, name: string, args: Record): Promise | null; error: string | null }> { const a = await call("POST", "/mcp", token, { jsonrpc: "2.0", id: ++rpc, method: "tools/call", params: { name, arguments: args } }); const r = a.body.result as { structuredContent?: Record; content?: { text: string }[]; isError?: boolean } | undefined; let result: Record | null = r?.structuredContent ?? null; if (!result && r?.content?.[0]?.text) { try { result = JSON.parse(r.content[0].text) as Record; } catch { result = null; } } const error = r?.isError ? (r.content?.[0]?.text ?? "error") : a.body.error ? JSON.stringify(a.body.error).slice(0, 200) : null; return { ...a, result, error }; } async function main(): Promise { const s = await signIn(BASE, NUMBER, CODE); const credential = s.credential; const token = s.token; say(`signed in an invented number (database ${s.databaseId.slice(0, 8)}…)`); // 2. Normal answers. const normal: number[] = []; let shapes = true; let extra = new Set(); for (let i = 0; i < 5; i++) { for (const [name, args] of [["list_projects", {}], ["brief", { project: "Nothing invented" }]] as const) { const a = await tool(token, name, args); normal.push(a.ms); if (a.status !== 200 || (!a.result && !a.error)) shapes = false; if (name === "list_projects" && (a.error || !Array.isArray(a.result?.projects))) shapes = false; for (const [k] of a.headers) if (k.startsWith("cotton-")) extra.add(k); if (i === 0) say(` ${name}: ${a.status} in ${a.ms} ms; ${ours(a.headers)}; ${a.error ? `error ${a.error.slice(0, 80)}` : `keys ${Object.keys(a.result ?? {}).join(",")}`}`); } } normal.sort((x, y) => x - y); say(` ten normal reads: median ${normal[5]} ms, slowest ${normal[9]} ms`); check(shapes, "normal reads answer 200 with their result, list_projects with its projects"); // cotton-object-build was on every answer before (since 30 Oct 2026); anything else would be new. extra = new Set([...extra].filter((k) => !OURS.includes(k) && k !== "cotton-object-build")); check(extra.size === 0, `no cotton- header but the three and cotton-object-build, which was there before (${[...extra].join(",") || "none other"})`); check(normal.filter((ms) => ms >= SLOW_ANSWER_MS).length === 0, `no normal read past ${SLOW_ANSWER_MS} ms, so none would be logged`); // 3. A forced slow answer. const planting = call("POST", "/v1/admin/dev/plant-rows", token, { table: "note", from: 0, count: ROWS, bytes: BYTES }); await new Promise((done) => setTimeout(done, 400)); const waited = await tool(token, "list_projects", {}); const planted = await planting; say(` plant ${ROWS} rows of ${BYTES} bytes: ${planted.status} in ${planted.ms} ms (${planted.status === 200 ? `${String(planted.body.bytes)} bytes held` : JSON.stringify(planted.body).slice(0, 200)})`); say(` list_projects sent while it ran: ${waited.status} in ${waited.ms} ms; ${ours(waited.headers)}`); check(planted.status === 200, "the plant was taken"); check(waited.status === 200 && Array.isArray(waited.result?.projects), "the read sent behind it still answered with its projects"); const line = slowLine("POST", "/mcp", waited.ms, waited.response); say(` the front Worker's line for it: ${line ?? "(none: under the bar)"}`); check(line !== null, `the read behind the plant took ${SLOW_ANSWER_MS} ms or more, so the Worker logs it`); const plantLine = slowLine("POST", "/v1/admin/dev/plant-rows", planted.ms, planted.response); if (plantLine) say(` and for the plant itself: ${plantLine}`); // The alarm after the plant (row recount, order index): reads while it runs carry its headers. let seenAlarm: Answer | null = null; let seenBusy: Answer | null = null; for (let i = 0; i < 40 && !(seenAlarm && seenBusy); i++) { const a = await tool(token, "list_projects", {}); if (!seenAlarm && a.headers.get(ALARM_RUNNING_HEADER) !== null) seenAlarm = a; if (!seenBusy && a.headers.get(ALARM_BUSY_HEADER) !== null) seenBusy = a; if (!(seenAlarm && seenBusy)) await new Promise((done) => setTimeout(done, 1500)); } if (seenAlarm) say(` a read during the alarm: ${seenAlarm.ms} ms; ${ours(seenAlarm.headers)}; would log: ${slowLine("POST", "/mcp", Math.max(seenAlarm.ms, SLOW_ANSWER_MS), seenAlarm.response)}`); if (seenBusy) say(` a read after an alarm with more to do: ${seenBusy.ms} ms; ${ours(seenBusy.headers)}`); say(` alarm-running header seen: ${seenAlarm ? "yes" : "no (the alarm finished between reads)"}; alarm-busy header seen: ${seenBusy ? "yes" : "no (each alarm finished its jobs)"}`); // 4. A definition change is seen at once. const mark = `Synthetic proof ${Math.random().toString(36).slice(2, 8)}`; const wrote = await tool(token, "update_definition", { table: "book", instructions: mark }); check(!wrote.error && JSON.stringify(wrote.result?.changed) === '["instructions"]', `update_definition wrote book's instructions (${wrote.error ?? JSON.stringify(wrote.result?.changed)})`); const read = await tool(token, "update_definition", { table: "book" }); const instructions = (read.result?.definition as Record | undefined)?.instructions; say(` the next request reads book's instructions: ${JSON.stringify(instructions)}`); check(instructions === mark, "the very next request read the new instructions through the object's parsed definitions"); const again = await tool(token, "update_definition", { table: "book", instructions: `${mark} again` }); check((again.result?.before as Record | undefined)?.instructions === mark, "a second write's before is the first write's value"); const served = await call("GET", "/v1/definitions", credential); const book = ((served.body.tables ?? []) as Record[]).find((t) => t.id === "book"); const name = `Synthetic shelf ${Math.random().toString(36).slice(2, 6)}`; const acted = book ? await call("POST", "/v1/act", credential, { act: "definition", args: { kind: "table", definition: { ...book, name } } }) : null; check(acted?.status === 200, `the phone's definition act renamed book (${acted?.status ?? "no book served"})`); const after = await tool(token, "update_definition", { table: "book" }); const seenName = (after.result?.definition as Record | undefined)?.name; say(` the next MCP request reads book's name: ${JSON.stringify(seenName)}`); check(seenName === name, "the act's write was seen by the very next request"); // A cold answer the script can see: the object's first answers went to the sign-in's own calls, so the object is // left idle until the runtime lets it go, and the next read is its first since it started again. const idle = Number(arg("idle", "0")); if (idle > 0) { say(` idle ${idle} s, so the object is let go`); await new Promise((done) => setTimeout(done, idle * 1000)); const woke = await tool(token, "list_projects", {}); const next = await tool(token, "list_projects", {}); say(` the read after: ${woke.status} in ${woke.ms} ms; ${ours(woke.headers)}; the one after it: ${ours(next.headers)}`); check(woke.headers.get(COLD_HEADER) === "1" && next.headers.get(COLD_HEADER) === null, "after idling, the first read says cold and the next does not"); } say(failed ? `FAILED ${failed}` : "SLOW READ PROVEN"); process.exit(failed ? 1 : 0); } main().catch((e: unknown) => { say(`FAILED: ${e instanceof Error ? e.message : String(e)}`); process.exit(1); });