Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(gfs): real-PG concurrency coverage for rename/replace/copy write paths
Alfredo Lopez5d0a8dd707c9
diff --git a/control-api/test/gfsCopy.realPostgres.integration.test.ts b/control-api/test/gfsCopy.realPostgres.integration.test.tsindex 55e0eff92..710a2463a 100644--- a/control-api/test/gfsCopy.realPostgres.integration.test.ts+++ b/control-api/test/gfsCopy.realPostgres.integration.test.ts@@ -292,4 +292,83 @@ describeRealPostgres('GFS Copy publication on real PostgreSQL and filesystem bloexpect(manifests.rows[0]?.count).toBe(0)expect(outcome.rows).toEqual([{ mutation_outcome: 'failed' }])})++ // Concurrency — the optimistic If-Match path. replace() locks the row and+ // re-checks the version inside the writer transaction; two replaces of the+ // same file racing with the SAME If-Match can only be adjudicated by real row+ // locks, so this belongs in the real-PG suite, not the scripted-client unit.+ it('serializes two concurrent replaces of the same file: one version bump, the loser is precondition_failed', async () => {+ const tree = await seedTree('race-replace')+ // first.txt was seeded at version 1. Each replace runs on its own pooled+ // connection: the writer that locks the row first bumps version 1->2 and+ // commits; the other then sees version 2 != If-Match 1 and must fail.+ const fileId = tree.firstFileId+ const contentA = Buffer.from('replacement-A-payload')+ const contentB = Buffer.from('replacement-B-different-length')+ const attempt = (content: Buffer) =>+ writes.replace({ drive: tree.drive, resourceId: fileId, ifMatch: 1, content })++ const results = await Promise.allSettled([attempt(contentA), attempt(contentB)])+ const fulfilled = results.filter(+ (r): r is PromiseFulfilledResult<Awaited<ReturnType<typeof writes.replace>>> =>+ r.status === 'fulfilled'+ )+ const rejected = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected')+ expect(fulfilled).toHaveLength(1)+ expect(rejected).toHaveLength(1)+ expect(rejected[0]!.reason).toMatchObject({ code: 'precondition_failed' })++ // Business truth: version bumped exactly once (1->2), and the bytes served+ // from the real blob store are the winner's — never a torn blend.+ const row = await pool.query(+ `SELECT version, bytes, blob_key FROM gfs_resources WHERE drive=$1 AND resource_id=$2`,+ [tree.drive, fileId]+ )+ expect(Number(row.rows[0]?.version)).toBe(2)+ const served = await readAll(await blobs.read(fileId, String(row.rows[0]?.blob_key)))+ expect([contentA, contentB].some(candidate => candidate.equals(served))).toBe(true)+ expect(Number(row.rows[0]?.bytes)).toBe(served.length)+ })++ // Concurrency — the per-drive advisory lock + destination re-check. Two copies+ // into the SAME destination name, both passing preflight before either+ // publishes, must not both land.+ it('serializes two concurrent copies into the same destination name: one wins, the loser is already_exists', async () => {+ const tree = await seedTree('race-copy')+ // Independent frozen plans for the same '/archive/dup' name. Under the+ // per-drive advisory lock the first copy inserts the subtree; the second+ // re-checks the destination name inside the writer txn, finds it taken, and+ // fails already_exists — the loser inserts nothing.+ const planA = await planFor(tree, 'dup')+ const planB = await planFor(tree, 'dup')+ const attempt = (plan: Awaited<ReturnType<typeof planFor>>, tag: string) =>+ writes.copy({+ requestId: randomUUID(),+ subject: `host:sandbox-recipes/copy-race-${tag}`,+ audit,+ drive: tree.drive,+ destinationParentId: tree.destinationId,+ plan: plan.plan,+ destination: plan.destination,+ deadlineAtMs: Date.now() + 30_000,+ })++ const results = await Promise.allSettled([attempt(planA, 'a'), attempt(planB, 'b')])+ const fulfilled = results.filter(+ (r): r is PromiseFulfilledResult<Awaited<ReturnType<typeof writes.copy>>> =>+ r.status === 'fulfilled'+ )+ const rejected = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected')+ expect(fulfilled).toHaveLength(1)+ expect(rejected).toHaveLength(1)+ expect(rejected[0]!.reason).toMatchObject({ code: 'already_exists' })++ // Business truth: exactly ONE copied subtree root exists at the contended+ // destination name.+ const roots = await pool.query(+ `SELECT count(*)::integer AS n FROM gfs_resources WHERE drive=$1 AND path_cache='/archive/dup'`,+ [tree.drive]+ )+ expect(roots.rows[0]?.n).toBe(1)+ })})diff --git a/gfs-controller/src/db/renamePublication.realPostgres.integration.test.ts b/gfs-controller/src/db/renamePublication.realPostgres.integration.test.tsindex a22e71247..46dd7cdb5 100644--- a/gfs-controller/src/db/renamePublication.realPostgres.integration.test.ts+++ b/gfs-controller/src/db/renamePublication.realPostgres.integration.test.ts@@ -217,4 +217,69 @@ describeRealPostgres("renamePublication on real PostgreSQL", () => {);expect(after.rows[0]).toMatchObject({ name: "big" });});++ // Concurrency: the served rename holds an advisory lock + `FOR UPDATE` and+ // re-checks the If-Match version inside the transaction. Two renames of the+ // same root racing with the SAME If-Match can ONLY be adjudicated by real+ // PostgreSQL row locks — the scripted-client unit suite cannot observe the+ // serialization, so this lives here.+ it("serializes two concurrent renames of the same root: exactly one wins, the loser is precondition_failed", async () => {+ const seeded = await pool.query(`+ WITH drive_root AS (+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache)+ VALUES ('race', NULL, '', 'directory', '/')+ RETURNING resource_id+ ),+ root AS (+ INSERT INTO gfs_resources (drive, parent_resource_id, name, kind, path_cache, version)+ SELECT 'race', resource_id, 'contended', 'directory', '/contended', 7 FROM drive_root+ RETURNING resource_id+ )+ SELECT root.resource_id::text AS root_id FROM root;+ `);+ const rootId = (seeded.rows[0] as { root_id: string }).root_id;++ // Each attempt runs on its OWN real transactor (its own pooled connection),+ // both launched together. Same If-Match=7: whichever transaction acquires+ // the row lock first bumps the version 7->8 and commits; the other then sees+ // version 8 != If-Match 7 and must fail precondition_failed. Deterministic —+ // the lock decides the order, the If-Match decides that only one may win.+ const attempt = (newName: string) =>+ publishRename(new PgTransactor(pool), {+ requestId: `req-rename-race-${newName}`,+ subject: "host:1st:mcp-host/agent-a",+ audit: noopAudit,+ drive: "race",+ resourceId: rootId,+ newName,+ ifMatch: 7,+ maxObjects: 1000,+ deadlineAtMs: Date.now() + 30_000,+ });++ const results = await Promise.allSettled([attempt("winner-a"), attempt("winner-b")]);+ const fulfilled = results.filter(+ (r): r is PromiseFulfilledResult<Awaited<ReturnType<typeof publishRename>>> =>+ r.status === "fulfilled"+ );+ const rejected = results.filter(+ (r): r is PromiseRejectedResult => r.status === "rejected"+ );+ expect(fulfilled).toHaveLength(1);+ expect(rejected).toHaveLength(1);+ expect(rejected[0]!.reason).toMatchObject({ code: "precondition_failed" });++ // Business truth: exactly one mutation landed — the version bumped once+ // (7->8), and the persisted name/path is the winner's, never a blend of both.+ const winnerName = fulfilled[0]!.value.name;+ const after = await pool.query(+ `SELECT name, path_cache, version FROM gfs_resources WHERE drive='race' AND resource_id=$1`,+ [rootId]+ );+ expect(after.rows[0]).toMatchObject({+ name: winnerName,+ path_cache: `/${winnerName}`,+ version: 8,+ });+ });});