Cotton code
123 lines · 8.0 KB · TypeScriptRaw
/** * UPGRADE PROOF (coordinator, 26 Nov 2026): the owner's phone at an upgrade, on invented data. * *   cd apps/business && pnpm -s exec tsx scripts/__tests__/upgrade-proof.ts [<app>@<sha> ...] * * For each case in scripts/upgrade-proof/cases.json (or those named): a fresh personal object under `wrangler dev`; * the core at the OLD sha (built once by scripts/upgrade-proof/old-core.sh, cached by sha) fills a phone copy against * it in the states that matter (crates/cotton-ffi/src/phone/upgrade_writer.rs); then the core at HEAD opens that same * copy and runs passes (upgrade_proof.rs): nothing lost, nothing erased, the queue intact and then delivered, the * refused change still parked and said, the schema only forward. Here, from the object's side: nothing sent twice * (each record's version moved by exactly what the old phone left queued) and the refused note never arrived. * wrangler dev is stopped and the temp dir removed however it ends. */import { spawnSync, type ChildProcess } from "node:child_process";import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { APP, check, startDevWorker, stop } from "./dev-worker.ts";import { WS } from "./fixture.ts";import { personalSlug } from "../dev-server";const REPO = resolve(APP, "../..");const CRATES = join(REPO, "crates");type Case = { app: string; sha: string; build?: string };const all = JSON.parse(readFileSync(join(REPO, "scripts/upgrade-proof/cases.json"), "utf8")) as Case[];const named = process.argv.slice(2);const asked = named.map((n) => n.split("@") as [string, string | undefined]);const cases = named.length ? asked.map(([app, sha]) => all.find((c) => c.app === app && (!sha || c.sha === sha)) ?? { app, sha: sha ?? "head" }) : all;check(cases.length > 0, `a case to run (${named.join(", ")}; known: ${all.map((c) => `${c.app}@${c.sha}`).join(", ")})`);// The writer and the checker exist for these apps (one test each side, named by app).// The old side runs as the phone lives: each test in `old` is one launch of the old build, in order.const WRITERS: Record<string, { old: string[]; head: string }> = {  words: {    old: ["phone::personal_object::upgrade_writer::upgrade_old_side_writes_a_words_copy_synced", "phone::personal_object::upgrade_writer::upgrade_old_side_writes_a_words_copy_offline"],    head: "phone::personal_object::upgrade_proof::upgrade_head_side_opens_the_old_copy",  },};/** How many entries the object's change log holds for `id`, by kind (`list_changes`, the owner's MCP). */async function changes(base: string, token: string, id: string): Promise<Record<string, number>> {  const r = await fetch(`${base}/b/${personalSlug()}/mcp`, {    method: "POST",    headers: { "content-type": "application/json", authorization: `Bearer ${token}` },    body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "list_changes", arguments: { id, limit: 200 } } }),  });  const answer = (await r.json()) as { result?: { content?: { text: string }[]; isError?: boolean } };  const text = answer.result?.content?.[0]?.text ?? "{}";  if (answer.result?.isError) check(false, `list_changes ${id}: ${text.slice(0, 300)}`);  const kinds: Record<string, number> = {};  for (const change of (JSON.parse(text) as { changes?: { kind: string }[] }).changes ?? []) kinds[change.kind] = (kinds[change.kind] ?? 0) + 1;  return kinds;}const total = (kinds: Record<string, number>): number => Object.values(kinds).reduce((a, b) => a + b, 0);const said = (run: ReturnType<typeof spawnSync>): string => {  // Why a test failed is its panic, which may sit before a long tail of output: that first, then the tail.  const out = `${String(run.stdout ?? "")}\n${String(run.stderr ?? "")}`;  const panic = out.split("\n").flatMap((line, i, lines) => (line.includes("panicked at") ? lines.slice(i, i + 4) : [])).map((line) => line.slice(0, 1500));  return `${panic.join("\n")}\n${out.slice(-2000)}${run.error ? String(run.error) : ""}`;};let failed = 0;for (const c of cases) {  const writer = WRITERS[c.app];  check(writer !== undefined, `a writer for ${c.app} (known: ${Object.keys(WRITERS).join(", ")})`);  if (writer === undefined) {    failed += 1;    continue;  }  const tmp = mkdtempSync(join(tmpdir(), "upgrade-proof-"));  let wrangler: ChildProcess | null = null;  try {    // `head` as the sha: HEAD plays the old side too, to try a new writer before an old core is built for it.    const sameBuild = c.sha === "head";    const built = sameBuild ? null : spawnSync(join(REPO, "scripts/upgrade-proof/old-core.sh"), [c.sha], { encoding: "utf8" });    check(built === null || built.status === 0, `the core at ${c.sha} builds\n${built ? said(built) : ""}`);    const oldCore = built ? String(built.stdout).trim().split("\n").pop()! : "";    const { api, base, credential } = await startDevWorker(tmp, WS, (child) => {      wrangler = child;    });    const container = join(tmp, "phone");    mkdirSync(container);    const env = { ...process.env, COTTON_E2E_BASE: base, COTTON_E2E_CREDENTIAL: credential, COTTON_E2E_DATABASE: WS, UPGRADE_CONTAINER: container, UPGRADE_MANIFEST: join(tmp, "manifest.json") };    for (const test of writer.old) {      const old = sameBuild        ? spawnSync("cargo", ["test", "-q", "-p", "cotton-ffi", "--lib", test, "--", "--exact", "--ignored", "--nocapture"], { cwd: CRATES, encoding: "utf8", env: { ...env, CARGO_INCREMENTAL: "0" } })        : spawnSync(oldCore, [test, "--exact", "--ignored", "--nocapture", "--test-threads=1"], { cwd: tmp, encoding: "utf8", env });      check(old.status === 0, `${c.app}@${c.sha}: the old core runs ${test.split("::").pop()}\n${said(old)}`);    }    const manifest = JSON.parse(readFileSync(env.UPGRADE_MANIFEST, "utf8")) as { synced: string[]; edited: string; queued: string; parked: string };    const ids = [...manifest.synced, manifest.queued];    const minted = await api<{ token?: string }>("POST", "/v1/act", { act: "mint_token", args: { name: "upgrade proof", scopes: ["owner"], allow: "all" } }, credential);    const log = async (): Promise<Map<string, Record<string, number>>> => new Map(await Promise.all(ids.map(async (id) => [id, await changes(base, minted.token!, id)] as const)));    const before = await log();    // The old phone was offline after its last pass: the object has not its offline note.    check(total(before.get(manifest.queued)!) === 0, `the old phone sent nothing offline: ${JSON.stringify(Object.fromEntries(before))}`);    const head = spawnSync("cargo", ["test", "-q", "-p", "cotton-ffi", "--lib", writer.head, "--", "--exact", "--ignored", "--nocapture"], { cwd: CRATES, encoding: "utf8", env: { ...env, CARGO_INCREMENTAL: "0" } });    check(head.status === 0, `${c.app}@${c.sha}: HEAD opens the old copy and passes\n${said(head)}`);    const after = await log();    const moved = Object.fromEntries(ids.map((id) => [id, { before: before.get(id), after: after.get(id) }]));    console.log(`  change log ${JSON.stringify(moved)}`);    // Nothing sent twice: a synced note the old phone left alone, and the one whose edit was refused, have no new    // entry; the held edit is one more entry on its note; the offline note was created once.    for (const id of manifest.synced.filter((id) => id !== manifest.edited)) check(total(after.get(id)!) === total(before.get(id)!), `${id} untouched${id === manifest.parked ? " (its edit refused)" : ""}`);    check(total(after.get(manifest.edited)!) === total(before.get(manifest.edited)!) + 1, "the held edit went once");    check((after.get(manifest.queued)!.create ?? 0) === 1, "the offline note was created once");    const line = /UPGRADE-HEAD (\{.*\})/.exec(String(head.stdout))?.[1] ?? "{}";    console.log(`upgrade proof ${c.app}@${c.sha}: passed ${line}`);  } catch (error) {    failed += 1;    console.error(`upgrade proof ${c.app}@${c.sha}: ${(error as Error).message}`);  } finally {    stop(wrangler);    rmSync(tmp, { recursive: true, force: true });  }}process.exitCode = failed ? 1 : 0;