Lines 1–12 at 318 (were 1–8 at 158)
11import assert from "node:assert/strict"; 2−import { registerHooks } from "node:module";
2+import { createRequire, registerHooks } from "node:module"; 33import { test } from "node:test"; 4+import git from "isomorphic-git"; 45import { Project } from "../../worker/project/project.ts"; 56import { EngineProject } from "../src/engine-project.ts"; 7+import { GitDiskIntake } from "../src/git-disk-intake.ts"; 8+import { GitIntakeLimitError } from "../src/git-intake-limit.ts"; 9+import { MemoryFS } from "../src/memory-fs.ts"; 610import { memoryStorage } from "./helpers.ts"; 812const hooks = registerHooks({ Lines 22–215 at 318 (were 18–23 at 158)
1822const { ProjectObject } = await import("../src/project-object.ts"); 25+for (const disk of [false, true]) 26+ test(`failed intake retries across cold objects with disk mode ${disk}`, async (t) => { 27+ const storage = memoryStorage(); 28+ t.after(() => storage.db.close()); 29+ const values = new Map<string, unknown>(); 30+ let alarm: number | null = null; 32+ id: { toString: () => "retry" }, 35+ get: async (key: string) => values.get(key), 36+ put: async (key: string | Record<string, unknown>, value?: unknown) => { 37+ if (typeof key === "string") values.set(key, value); 38+ else for (const [name, item] of Object.entries(key)) values.set(name, item); 40+ delete: async (key: string) => values.delete(key), 41+ getAlarm: async () => alarm, 42+ setAlarm: async (value: number) => { 47+ const object = (enabled: boolean) => 51+ ABSO_DISK_FIRST: disk ? "on" : "off", 52+ ABSO_ARTIFACTS: enabled ? "on" : "off", 56+ assert.equal((await object(false).call("retry", "init", undefined, { files: { "a.txt": "first\n" } })).status, 200); 58+ for (let page = 0; page < 100; page++) { 59+ if ((await object(false).call("retry", "status", undefined, {})).status === 200) { 64+ assert.equal(ready, true); 66+ t.mock.method(ProjectObject.prototype, "gitSync", async () => { 67+ if (fails) throw Error("transient intake failure"); 70+ for (const [index, minutes] of [1, 5, 15, 15].entries()) { 72+ const before = Date.now(); 73+ await object(true).alarm(); 74+ assert.equal(values.get("git:retry-attempts"), index + 1); 75+ assert.ok(alarm !== null && alarm >= before + minutes * 60000 && alarm <= Date.now() + minutes * 60000); 76+ assert.equal(values.get("pushed"), undefined); 79+ values.set("pushed", { version: Number.MAX_SAFE_INTEGER }); 81+ await object(true).alarm(); 82+ assert.equal(values.has("git:retry-attempts"), false); 83+ assert.equal(values.has("git:error"), false); 86+test("size refusals survive cold objects, retry changed heads or policy, and prevent outgoing pushes", async (t) => { 88+ const storage = memoryStorage(); 89+ t.after(() => storage.db.close()); 90+ const values = new Map<string, unknown>(); 92+ id: { toString: () => "size-refusal" }, 95+ get: async (key: string) => values.get(key), 96+ put: async (key: string | Record<string, unknown>, value?: unknown) => { 97+ if (typeof key === "string") values.set(key, value); 98+ else for (const [name, item] of Object.entries(key)) values.set(name, item); 100+ delete: async (key: string) => values.delete(key), 101+ getAlarm: async () => null, 102+ setAlarm: async (value: number) => { 109+ info: async () => ({ remote: "https://artifacts.invalid/size" }), 110+ createToken: async () => ({ plaintext: "invented-test-token" }), 111+ [Symbol.dispose]() {}, 114+ const object = (enabled = true) => 118+ ABSO_DISK_FIRST: "on", 119+ ABSO_ARTIFACTS: enabled ? "on" : "off", 120+ ARTIFACTS: artifacts, 124+ (await object(false).call("size-refusal", "init", undefined, { files: { "a.txt": "original\n" } })).status, 128+ for (let page = 0; page < 100; page++) { 129+ const result = await object(false).call("size-refusal", "status", undefined, {}); 130+ if (result.status === 200) { 134+ assert.equal(result.status, 503); 136+ assert.equal(ready, true, "project indexing must finish before testing intake refusals"); 137+ let head = "a".repeat(40), 141+ t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: head }]); 142+ t.mock.method(git, "clone", async () => { 144+ if (transient) throw Error("temporary network failure"); 145+ throw new GitIntakeLimitError("decoded", "Git pack exceeds total decoded byte limit"); 147+ t.mock.method(git, "push", async () => { 149+ return { ok: true }; 151+ await assert.rejects(() => object().gitSync(), /decoded byte limit/); 152+ await assert.rejects(() => object().gitSync(), /decoded byte limit/); 153+ assert.equal(downloads, 1); 154+ assert.equal(values.get("git:head"), undefined); 155+ assert.equal((await object().out()).version, 0); 156+ assert.match(JSON.stringify((await object().out()).git.error), /decoded byte limit/); 157+ await object().alarm(); 158+ assert.ok(scheduled >= Date.now() + 59_000); 159+ assert.equal(values.get("git:retry-attempts"), 1); 160+ assert.equal(downloads, 1); 161+ assert.equal(pushes, 0); 162+ head = "b".repeat(40); 163+ await assert.rejects(() => object().gitSync(), /decoded byte limit/); 164+ assert.equal(downloads, 2); 165+ values.set("git:size-refusal", { ...(values.get("git:size-refusal") as object), policy: "old-policy" }); 166+ await assert.rejects(() => object().gitSync(), /decoded byte limit/); 167+ assert.equal(downloads, 3); 168+ head = "c".repeat(40); 170+ await assert.rejects(() => object().gitSync(), /temporary network failure/); 171+ await assert.rejects(() => object().gitSync(), /temporary network failure/); 172+ assert.equal(downloads, 5); 173+ assert.equal(values.has("git:size-refusal"), false); 174+ await object().alarm(); 175+ assert.equal(pushes, 0); 176+ assertGitScratchEmpty(storage); 179+function assertGitScratchEmpty(storage: ReturnType<typeof memoryStorage>) { 180+ for (const table of [ 185+ "git_object_budget", 187+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0, table); 190+/** Keep transport synthetic while exercising the real disk pack decoder and cache. */ 191+async function cloneFixture(remote: MemoryFS, options: Parameters<typeof git.clone>[0]) { 192+ const intake = (options.cache as Record<symbol, GitDiskIntake> | undefined)?.[Symbol.for("abso.git.disk-pack")]; 194+ (options.fs as MemoryFS).entries = structuredClone(remote.entries); 197+ const oids = [...remote.entries.keys()].flatMap((path) => { 198+ const match = /\/objects\/([0-9a-f]{2})\/([0-9a-f]{38})$/.exec(path); 199+ return match ? [match[1]! + match[2]!] : []; 201+ const pack = (await git.packObjects({ fs: remote, dir: "/repo", oids, write: false })).packfile!; 202+ const { Inflate } = createRequire(import.meta.url)("pako"); 203+ await intake.ingest([pack], () => new Inflate({ chunkSize: 16384 })); 204+ await git.init({ fs: options.fs, dir: options.dir, defaultBranch: "main" }); 205+ await git.writeRef({ 209+ value: await git.resolveRef({ fs: remote, dir: "/repo", ref: "main" }), 21213test("empty disk projects and unloadable legacy projects preserve lookup fallbacks", async (t) => { 22214 const storage = memoryStorage(); 23215 t.after(() => storage.db.close()); Lines 237–244 at 318 (were 45–50 at 158)
45237 const values = new Map<string, unknown>(); 46238 let alarm: number | null = null; 47239 let onReaders: (() => Promise<void>) | undefined; 240+ let failGitAcknowledgement = false; 241+ let failNamePersistence = false; 49243 id: { toString: () => "project-1" }, Lines 252–265 at 318 (were 58–63 at 158)
58252 return values.get(key); 60254 put: async (key: string | Record<string, unknown>, value?: unknown) => { 255+ if (key === "name" && failNamePersistence) { 256+ failNamePersistence = false; 257+ throw Error("injected name persistence failure"); 259+ if (failGitAcknowledgement && typeof key === "object" && "git:head" in key) { 260+ failGitAcknowledgement = false; 261+ throw Error("injected Git cursor persistence failure"); 61263 if (typeof key === "string") values.set(key, value); 62264 else for (const [name, v] of Object.entries(key)) values.set(name, v); Lines 278–286 at 318 (were 76–84 at 158)
76278 t.mock.method(Project, "load", () => { 77279 throw Error("full history replay forbidden"); 79− const call = async (op: string, agent: string | undefined, body: unknown) => {
281+ const call = async (op: string, agent: string | undefined, body: unknown, requestId?: string) => { 80282 for (let page = 0; page < 100; page++) { 81− const result = await object().call("project", op, agent, body);
283+ const result = await object().call("project", op, agent, body, false, undefined, undefined, requestId); 82284 if (result.status !== 503) { 83285 assert.notEqual(result.status, 500, JSON.stringify({ op, result })); Lines 290–403 at 318 (were 88–99 at 158)
89291 throw Error("adoption did not finish"); 91− assert.equal((await call("init", undefined, { files: { "a.txt": "one\ntwo\n" } })).status, 200);
293+ const initId = "00000000-0000-4000-8000-000000000008"; 294+ const initBody = { files: { "a.txt": "one\ntwo\n" } }; 295+ failNamePersistence = true; 296+ await assert.rejects( 297+ () => object().call("project", "init", undefined, initBody, false, undefined, undefined, initId), 298+ /name persistence failure/, 300+ const initializedLog = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 301+ assert.equal((await call("init", undefined, initBody, initId)).status, 200); 302+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), initializedLog); 92303 assert.equal((await call("sync", "alice", {})).status, 200); 93− assert.equal((await call("record", "alice", { files: { "a.txt": "changed\n" } })).status, 200);
304+ const requestId = "00000000-0000-4000-8000-000000000007"; 305+ const recordBody = { files: { "a.txt": "changed\n" } }; 306+ failNamePersistence = true; 307+ await assert.rejects( 308+ () => object().call("project", "record", "alice", recordBody, false, undefined, undefined, requestId), 309+ /name persistence failure/, 311+ const recordedLog = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 313+ (await object().call("project", "record", "alice", recordBody, false, undefined, undefined, requestId)).status, 316+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), recordedLog); 319+ await object().call( 323+ { files: { "a.txt": "different\n" } }, 94332 const published = await call("publish", "alice", { message: "Disk first" }); 95333 assert.equal(published.status, 200); 96334 assert.equal((published.body as { ok: boolean }).ok, true); 335+ const issued = await object().issueAgentKey("alice", "test-address", null, "writer"); 336+ assert.ok("key" in issued); 337+ const keyCall = { presented: issued.key, address: "test-address", write: true, route: "record" }; 338+ const crossPrincipal = await object().call( 348+ assert.equal(crossPrincipal.status, 200, "each checked principal owns its own request ID namespace"); 349+ const principalReceipts = storage.db 350+ .prepare("SELECT DISTINCT key FROM writer_state WHERE collection = 'runtime:receipts' AND key LIKE ?") 351+ .all(`http:%:${requestId}`); 352+ assert.equal(principalReceipts.length, 2); 353+ const beforeSharedReplay = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 354+ assert.equal((await call("record", "alice", recordBody, requestId)).status, 200); 355+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), beforeSharedReplay); 356+ const keyRequestId = "00000000-0000-4000-8000-000000000010"; 358+ (await object().call("project", "record", "alice", recordBody, false, undefined, keyCall, keyRequestId)).status, 361+ await object().revokeAgentKey(issued.id, "test-address"); 362+ const beforeRevokedRetry = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(); 363+ const revokedRetry = await object().call( 373+ assert.equal(revokedRetry.status, 403); 374+ assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), beforeRevokedRetry); 375+ const readerId = "00000000-0000-4000-8000-000000000009"; 376+ failNamePersistence = true; 377+ await assert.rejects( 378+ () => object().call("project", "reader", "alice", { reader: true }, false, undefined, undefined, readerId), 379+ /name persistence failure/, 381+ const nowRefused = await object().call( 392+ (nowRefused.body as { ok: boolean }).ok, 394+ "current reader authority overrides an earlier successful receipt", 397+ (await object().call("project", "reader", "alice", { reader: true }, false, undefined, undefined, readerId)).status, 400+ assert.equal((await call("reader", "alice", { reader: false })).status, 200); 97401 const file = await call("file", undefined, { path: "a.txt", version: "1" }); 98402 assert.equal(file.status, 200); 99403 assert.match(JSON.stringify(file.body), /changed/); Lines 469–670 at 318 (were 165–168 at 158)
165469 /injected after record/, 167471 assert.deepEqual(rows(), stable); 472+ // Exercise the real alarm and commit builder; only remote transport is mocked. 473+ t.mock.method(git, "listServerRefs", async () => []); 474+ t.mock.method(git, "clone", async () => { 475+ throw Error("empty test repository"); 478+ let failPush = true; 479+ let remoteFiles: MemoryFS | undefined; 480+ t.mock.method(git, "push", async (options: Parameters<typeof git.push>[0]) => { 483+ throw Error("injected Artifacts transport failure"); 485+ const oid = await git.resolveRef({ fs: options.fs, dir: options.dir, ref: "main" }); 486+ const commit = await git.readCommit({ fs: options.fs, dir: options.dir, oid }); 487+ assert.match(commit.commit.message, /abso-version: 2/); 488+ const blob = await git.readBlob({ fs: options.fs, dir: options.dir, oid, filepath: "a.txt" }); 489+ assert.equal(new TextDecoder().decode(blob.blob), "Alice's change\n"); 491+ // The remote owns its copy; the export's scratch files expire when push returns. 492+ remoteFiles = new MemoryFS(); 493+ for (const [path, entry] of (options.fs as MemoryFS).entries) { 494+ remoteFiles.entries.set( 496+ entry.kind === "file" 497+ ? { ...entry, data: new Uint8Array((await (options.fs as MemoryFS).readFile(path)) as Uint8Array) } 501+ return { ok: true }; 505+ info: async () => ({ remote: "https://artifacts.invalid/test" }), 506+ createToken: async () => ({ plaintext: "invented-test-token" }), 507+ [Symbol.dispose]() {}, 510+ const bound = () => new ProjectObject(context as never, { ABSO_DISK_FIRST: "on", ARTIFACTS: artifacts } as never); 511+ // Deliver the pending alarm: the fake storage must clear it as the host does. 513+ await bound().alarm(); 514+ assert.equal(pushed, 0); 515+ assert.equal(values.get("pushed"), undefined, "failed transport must not acknowledge a push"); 516+ assert.match(JSON.stringify(values.get("pushError")), /injected Artifacts transport failure/); 517+ assert.deepEqual(rows(), stable, "failed remote transport leaves canonical state unchanged"); 518+ assert.ok(alarm !== null && alarm > Date.now(), "failed transport schedules a retry"); 519+ await bound().alarm(); 520+ assert.equal(pushed, 1); 521+ assert.equal(values.get("pushError"), undefined, "cold retry clears the transport error"); 522+ assert.equal((await bound().out()).pushed?.version, 2); 523+ assert.deepEqual(rows(), stable, "pushing shared does not mutate canonical project state"); 524+ await bound().alarm(); 525+ assert.equal(pushed, 1, "a cold alarm does not push the same version again"); 526+ assert.ok(remoteFiles); 527+ const remote = remoteFiles; 528+ const parent = await git.resolveRef({ fs: remote, dir: "/repo", ref: "main" }); 529+ const blob = await git.writeBlob({ fs: remote, dir: "/repo", blob: new TextEncoder().encode("From Git\n") }); 530+ const tree = await git.writeTree({ 533+ tree: [{ mode: "100644", path: "a.txt", oid: blob, type: "blob" }], 535+ const incoming = await git.commit({ 540+ message: "Plain Git edit", 541+ author: { name: "Git writer", email: "test@example.invalid" }, 543+ await git.writeRef({ fs: remote, dir: "/repo", ref: "main", value: incoming, force: true }); 544+ t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: incoming }]); 545+ t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => { 546+ await cloneFixture(remote, options); 548+ const beforeIntake = rows(); 549+ const originalRead = GitDiskIntake.prototype.read; 550+ t.mock.method(GitDiskIntake.prototype, "read", function (this: GitDiskIntake, oid: string) { 551+ if (oid === blob) throw Error("whole intake text blob forbidden"); 552+ return originalRead.call(this, oid); 554+ const originalIngest = EngineProject.prototype.ingest; 555+ const failedIngest = t.mock.method( 556+ EngineProject.prototype, 558+ function (this: EngineProject, ...args: Parameters<EngineProject["ingest"]>) { 559+ originalIngest.apply(this, args); 560+ throw Error("injected after Git intake"); 563+ await assert.rejects(() => bound().gitSync(), /injected after Git intake/); 564+ assertGitScratchEmpty(storage); 565+ assert.deepEqual(rows(), beforeIntake); 566+ assert.equal((await bound().out()).git.head, parent, "failed intake must not acknowledge the remote head"); 567+ failedIngest.mock.restore(); 568+ failGitAcknowledgement = true; 569+ await assert.rejects(() => bound().gitSync(), /Git cursor persistence failure/); 570+ assertGitScratchEmpty(storage); 571+ const committedIntake = rows(); 572+ assert.equal((await bound().out()).version, 3); 573+ assert.equal((await bound().out()).git.head, parent); 574+ const intake = await bound().gitSync(); 575+ assertGitScratchEmpty(storage); 576+ assert.deepEqual(rows(), committedIntake, "retry after cursor failure returns the atomic intake receipt"); 578+ assert.equal(intake?.head, incoming); 579+ assert.equal(intake?.commits, 1); 580+ assert.equal((intake.answer as { landed: boolean }).landed, true, JSON.stringify(intake)); 581+ const imported = await call("file", undefined, { path: "a.txt", version: "3" }); 582+ assert.equal(imported.status, 200); 583+ assert.match(JSON.stringify(imported.body), /From Git/); 584+ const afterIntake = rows(); 585+ assert.equal(await bound().gitSync(), null); 586+ assert.deepEqual(rows(), afterIntake, "cold intake does not apply the same commit twice"); 589+for (const disk of [false, true]) { 590+ test(`Git refusal permits a later fixing commit with disk mode ${disk}`, async (t) => { 591+ const storage = memoryStorage(); 592+ t.after(() => storage.db.close()); 593+ const values = new Map<string, unknown>(); 595+ id: { toString: () => "refusal" }, 598+ get: async (key: string) => values.get(key), 599+ put: async (key: string | Record<string, unknown>, value?: unknown) => { 600+ if (typeof key === "string") values.set(key, value); 601+ else for (const [k, v] of Object.entries(key)) values.set(k, v); 603+ getAlarm: async () => null, 604+ setAlarm: async () => {}, 609+ info: async () => ({ remote: "https://artifacts.invalid/refusal" }), 610+ createToken: async () => ({ plaintext: "invented-test-token" }), 611+ [Symbol.dispose]() {}, 614+ const object = () => 615+ new ProjectObject(context as never, { ABSO_DISK_FIRST: disk ? "on" : "off", ARTIFACTS: artifacts } as never); 616+ const call = async (op: string, body: unknown) => { 617+ for (let page = 0; page < 100; page++) { 618+ const result = await object().call("refusal", op, undefined, body); 619+ if (result.status !== 503) return result; 621+ throw Error("preparation did not finish"); 623+ assert.equal((await call("init", { files: { "a.txt": "original\n" } })).status, 200); 624+ assert.equal((await call("status", {})).status, 200); 625+ const remote = new MemoryFS(); 626+ await git.init({ fs: remote, dir: "/repo", defaultBranch: "main" }); 627+ const commit = async (files: Record<string, string>, message: string, parent: string[]) => { 629+ for (const [path, text] of Object.entries(files)) 633+ type: "blob" as const, 634+ oid: await git.writeBlob({ fs: remote, dir: "/repo", blob: new TextEncoder().encode(text) }), 636+ const tree = await git.writeTree({ fs: remote, dir: "/repo", tree: entries }); 637+ const oid = await git.commit({ 643+ author: { name: "Git writer", email: "test@example.invalid" }, 645+ await git.writeRef({ fs: remote, dir: "/repo", ref: "main", value: oid, force: true }); 648+ const base = await commit({ "a.txt": "original\n" }, "Initial\n\nabso-version: 0", []); 649+ values.set("git:head", base); 650+ let head = await commit({ "A.TXT": "clash\n", "a.txt": "original\n" }, "Refused", [base]); 651+ t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: head }]); 652+ t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => { 653+ await cloneFixture(remote, options); 655+ const refused = await object().gitSync(); 657+ assert.match(JSON.stringify(refused.answer), /one file|clash/i); 658+ assert.equal(values.get("git:head"), head); 659+ assert.equal(await object().gitSync(), null); 660+ head = await commit({ "a.txt": "fixed\n" }, "Fixed", [head]); 661+ const fixed = await object().gitSync(); 663+ assert.equal((fixed.answer as { landed: boolean }).landed, true, JSON.stringify(fixed)); 664+ assert.equal(values.get("git:head"), head); 666+ JSON.stringify((await call("file", { path: "a.txt", version: String((await object().out()).version) })).body),