Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(#6712 PR 4b): the fold proof judges rows in the 32-bit xid space

garrytan649b05023d88
diff --git a/src/core/persistence/sync-pass-confirm.ts b/src/core/persistence/sync-pass-confirm.ts
index 9ca89cb81f..eb0ad8dea8 100644
--- a/src/core/persistence/sync-pass-confirm.ts
+++ b/src/core/persistence/sync-pass-confirm.ts
@@ -34,9 +34,11 @@
* write inside savepoints), which reads as ended though its transaction was in flight at S1. Such an id is larger than its
* transaction's own, and its row is visible to S2 only when that transaction committed before S2: so an id at or above the
* smallest listed transaction S2 sees committed counts as changed, and so does S1's own transaction's id. A transaction
- * that held no id at S1 takes one at or above S1's `xmax`. The 64-bit id of a 32-bit `xmin` is S2's `xmax` less their
- * distance modulo 2^32, exact while the row is within 2^31 of S2 (unfrozen rows always are; a frozen `xmin` is unchanged
- * by its `age`). A round without S1's snapshot (a stamp frozen before it was recorded) judges by `xmin` alone. `age` and
+ * that held no id at S1 takes one at or above S1's `xmax`. Each row is judged in the 32-bit xid space: S1's 64-bit
+ * `cut`, list and own id become xids, `age(xmin) > age(cut)` (both counted back from S2's counter) is `xmin < cut`, and
+ * xid equality is id equality, exact while every id is within 2^31 of S2 (unfrozen rows always are; a frozen `xmin` is
+ * unchanged by its `age`; test/sync-pass-xid-arms-gbra108.test.ts checks the verdicts against the 64-bit ids). A round
+ * without S1's snapshot (a stamp frozen before it was recorded) judges by `xmin` alone. `age` and
* the `txid_*` snapshot functions exist on every supported Postgres and on PGLite, where one connection leaves S1's list
* empty. More than 2^31 xids between S1's `xmin` and S2's `xmax` takes the full read (`age` would wrap).
*/
@@ -68,19 +70,27 @@ export async function readLevelMark(exec: Exec, sourceId: string, incarnation: s
return { xmin: row!.xmin, ops: row!.ops ?? {}, holds: row!.holds, snapshot: row!.snapshot, own: row!.own };
}
-/** `col`'s (a 32-bit xid) 64-bit id: S2's `xmax` less their distance modulo 2^32. */
-const full = (col: string) => `(x.hi - ((x.hi % 4294967296) - ${col}::text::bigint + 4294967296) % 4294967296)`;
+/** A 64-bit id's 32-bit xid (the same id within 2^31 of S2; a txid never has the special low words 0-2). */
+const xid32 = (id: string) => `((${id}) % 4294967296)::text::xid`;
+/** `age` of S1's 64-bit `xmin`: rows older than it are unchanged. */
+export const loAge = (lo: string) => `age(${xid32(lo)})`;
+/**
+ * S1's arms in the 32-bit xid space, from its 64-bit `cut`, in-progress list and own id: `age` counts back from S2's
+ * transaction counter, so `age(xmin) > cut_age` is `xmin < cut` and xid equality is 64-bit equality, both exact within 2^31.
+ */
+export const s1XidArms = (cut: string, xip: string, own: string) =>
+ `age(${xid32(cut)}) AS cut_age, ARRAY(SELECT ${xid32('t')} FROM unnest(${xip}) t) AS xip, ${xid32(own)} AS own`;
/** Whether `col` (an xid) was committed before S1 (see the header). */
-const unchanged = (col: string) => `(age(${col}) > x.lo_age OR COALESCE(${full(col)} < s1.cut AND ${full(col)} <> ALL(s1.xip) AND ${full(col)} IS DISTINCT FROM s1.own, false))`;
+export const unchanged = (col: string) => `(age(${col}) > x.lo_age OR COALESCE(age(${col}) > s1.cut_age AND ${col} <> ALL(s1.xip) AND ${col} IS DISTINCT FROM s1.own, false))`;
/**
* One scan of the source's pages and one of the incarnation's op rows: the counts, and the rows S1 does not prove unchanged.
* `$6`: the request publishing in this transaction (a folded checkpoint, sync-pass-fold.ts), whose page is not committed yet.
*/
const PROOF = `WITH x AS MATERIALIZED (SELECT txid_snapshot_xmin(txid_current_snapshot()) AS now_lo, txid_snapshot_xmax(txid_current_snapshot()) AS hi,
- age(($4::bigint % 4294967296)::text::xid) AS lo_age, txid_current_snapshot()::text AS now_snapshot, txid_current_if_assigned()::text AS now_own),
- s1 AS MATERIALIZED (SELECT ARRAY(SELECT txid_snapshot_xip($7::txid_snapshot)) AS xip, $8::bigint AS own,
- LEAST(txid_snapshot_xmax($7::txid_snapshot), (SELECT min(t) FROM txid_snapshot_xip($7::txid_snapshot) t WHERE txid_visible_in_snapshot(t, txid_current_snapshot()))) AS cut),
+ ${loAge('$4::bigint')} AS lo_age, txid_current_snapshot()::text AS now_snapshot, txid_current_if_assigned()::text AS now_own),
+ s1 AS MATERIALIZED (SELECT ${s1XidArms('c.cut', 'c.xip', 'c.own')} FROM (SELECT ARRAY(SELECT txid_snapshot_xip($7::txid_snapshot)) AS xip, $8::bigint AS own,
+ LEAST(txid_snapshot_xmax($7::txid_snapshot), (SELECT min(t) FROM txid_snapshot_xip($7::txid_snapshot) t WHERE txid_visible_in_snapshot(t, txid_current_snapshot()))) AS cut) c),
pg AS (SELECT count(*) FILTER (WHERE p.source_path IS NOT NULL)::int AS n,
COALESCE(jsonb_agg(jsonb_build_array(p.id::text, EXISTS (SELECT 1 FROM persistence_requests r WHERE r.id=p.revision_write_request_id AND r.source_id=$1
AND (r.id=$6::uuid OR r.state='committed' AND r.intent->>'passId'=$5 AND r.outcome->>'revision'=p.knowledge_revision::text)), p.knowledge_revision::text))
diff --git a/test/e2e/sync-pass-xid-arms-gbra108-postgres.test.ts b/test/e2e/sync-pass-xid-arms-gbra108-postgres.test.ts
new file mode 100644
index 0000000000..a4d809a251
--- /dev/null
+++ b/test/e2e/sync-pass-xid-arms-gbra108-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sync-pass-xid-arms-gbra108.test.ts'));
diff --git a/test/fixtures/fold-hook-noop-6712.json b/test/fixtures/fold-hook-noop-6712.json
index 66e4d141c3..327b06c7ae 100644
--- a/test/fixtures/fold-hook-noop-6712.json
+++ b/test/fixtures/fold-hook-noop-6712.json
@@ -114,7 +114,7 @@
"SELECT GREATEST((SELECT max(sequence) FROM persistence_requests WHERE worktree_id=$1::uuid), (SELECT max(sequence) FROM persistence_requests WHERE worktree_id IS NULL AND source_id=$2 AND source_incarnation=$3::uuid))::text AS hwm",
"(SELECT 'r:'||request_id::text AS id FROM persistence_requests WHERE state IN ('queued','running','recovering') AND (worktree_id=$1::uuid OR worktree_id IS NULL AND source_id=$4 AND source_incarnation=$5::uuid) AND request_id IS DISTINCT FROM $2::uuid LIMIT $3) UNION ALL (SELECT 'e:'||e.id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.worktree_id=$1::uuid AND e.kind='git' AND e.state IN ('queued','running') LIMIT $3)",
"SELECT last_commit, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1 AND incarnation=$2::uuid",
- "WITH x AS MATERIALIZED (SELECT txid_snapshot_xmin(txid_current_snapshot()) AS now_lo, txid_snapshot_xmax(txid_current_snapshot()) AS hi, age(($4::bigint % 4294967296)::text::xid) AS lo_age, txid_current_snapshot()::text AS now_snapshot, txid_current_if_assigned()::text AS now_own), s1 AS MATERIALIZED (SELECT ARRAY(SELECT txid_snapshot_xip($7::txid_snapshot)) AS xip, $8::bigint AS own, LEAST(txid_snapshot_xmax($7::txid_snapshot), (SELECT min(t) FROM txid_snapshot_xip($7::txid_snapshot) t WHERE txid_visible_in_snapshot(t, txid_current_snapshot()))) AS cut), pg AS (SELECT count(*) FILTER (WHERE p.source_path IS NOT NULL)::int AS n, COALESCE(jsonb_agg(jsonb_build_array(p.id::text, EXISTS (SELECT 1 FROM persistence_requests r WHERE r.id=p.revision_write_request_id AND r.source_id=$1 AND (r.id=$6::uuid OR r.state='committed' AND r.intent->>'passId'=$5 AND r.outcome->>'revision'=p.knowledge_revision::text)), p.knowledge_revision::text)) FILTER (WHERE NOT (age(p.xmin) > x.lo_age OR COALESCE((x.hi - ((x.hi % 4294967296) - p.xmin::text::bigint + 4294967296) % 4294967296) < s1.cut AND (x.hi - ((x.hi % 4294967296) - p.xmin::text::bigint + 4294967296) % 4294967296) <> ALL(s1.xip) AND (x.hi - ((x.hi % 4294967296) - p.xmin::text::bigint + 4294967296) % 4294967296) IS DISTINCT FROM s1.own, false))), '[]'::jsonb) AS changed FROM pages p, x, s1 WHERE p.source_id=$1), oc AS (SELECT o.op, count(*)::int AS n, jsonb_agg(jsonb_build_array(o.op, o.fingerprint, o.completed_keys->0->>'revision', o.completed_keys->0->>'run_id')) FILTER (WHERE NOT (age(o.xmin) > x.lo_age OR COALESCE((x.hi - ((x.hi % 4294967296) - o.xmin::text::bigint + 4294967296) % 4294967296) < s1.cut AND (x.hi - ((x.hi % 4294967296) - o.xmin::text::bigint + 4294967296) % 4294967296) <> ALL(s1.xip) AND (x.hi - ((x.hi % 4294967296) - o.xmin::text::bigint + 4294967296) % 4294967296) IS DISTINCT FROM s1.own, false))) AS changed FROM op_checkpoints o, x, s1 WHERE o.op = ANY($2::text[]) AND (o.fingerprint = $3 OR starts_with(o.fingerprint, $3 || ':')) GROUP BY o.op) SELECT x.now_lo::text AS xmin, x.now_snapshot AS snapshot, x.now_own AS own, (x.hi - $4::bigint)::float8 AS span, pg.n AS pages, pg.changed AS pages_changed, (SELECT COALESCE(jsonb_object_agg(op, n), '{}'::jsonb) FROM oc) AS ops, (SELECT COALESCE(jsonb_agg(c), '[]'::jsonb) FROM oc, jsonb_array_elements(COALESCE(oc.changed, '[]'::jsonb)) c) AS ops_changed, (SELECT COALESCE(jsonb_agg(fingerprint), '[]'::jsonb) FROM op_checkpoints WHERE op='sync-hold' AND starts_with(fingerprint, $3 || ':')) AS holds FROM x, pg",
+ "WITH x AS MATERIALIZED (SELECT txid_snapshot_xmin(txid_current_snapshot()) AS now_lo, txid_snapshot_xmax(txid_current_snapshot()) AS hi, age((($4::bigint) % 4294967296)::text::xid) AS lo_age, txid_current_snapshot()::text AS now_snapshot, txid_current_if_assigned()::text AS now_own), s1 AS MATERIALIZED (SELECT age(((c.cut) % 4294967296)::text::xid) AS cut_age, ARRAY(SELECT ((t) % 4294967296)::text::xid FROM unnest(c.xip) t) AS xip, ((c.own) % 4294967296)::text::xid AS own FROM (SELECT ARRAY(SELECT txid_snapshot_xip($7::txid_snapshot)) AS xip, $8::bigint AS own, LEAST(txid_snapshot_xmax($7::txid_snapshot), (SELECT min(t) FROM txid_snapshot_xip($7::txid_snapshot) t WHERE txid_visible_in_snapshot(t, txid_current_snapshot()))) AS cut) c), pg AS (SELECT count(*) FILTER (WHERE p.source_path IS NOT NULL)::int AS n, COALESCE(jsonb_agg(jsonb_build_array(p.id::text, EXISTS (SELECT 1 FROM persistence_requests r WHERE r.id=p.revision_write_request_id AND r.source_id=$1 AND (r.id=$6::uuid OR r.state='committed' AND r.intent->>'passId'=$5 AND r.outcome->>'revision'=p.knowledge_revision::text)), p.knowledge_revision::text)) FILTER (WHERE NOT (age(p.xmin) > x.lo_age OR COALESCE(age(p.xmin) > s1.cut_age AND p.xmin <> ALL(s1.xip) AND p.xmin IS DISTINCT FROM s1.own, false))), '[]'::jsonb) AS changed FROM pages p, x, s1 WHERE p.source_id=$1), oc AS (SELECT o.op, count(*)::int AS n, jsonb_agg(jsonb_build_array(o.op, o.fingerprint, o.completed_keys->0->>'revision', o.completed_keys->0->>'run_id')) FILTER (WHERE NOT (age(o.xmin) > x.lo_age OR COALESCE(age(o.xmin) > s1.cut_age AND o.xmin <> ALL(s1.xip) AND o.xmin IS DISTINCT FROM s1.own, false))) AS changed FROM op_checkpoints o, x, s1 WHERE o.op = ANY($2::text[]) AND (o.fingerprint = $3 OR starts_with(o.fingerprint, $3 || ':')) GROUP BY o.op) SELECT x.now_lo::text AS xmin, x.now_snapshot AS snapshot, x.now_own AS own, (x.hi - $4::bigint)::float8 AS span, pg.n AS pages, pg.changed AS pages_changed, (SELECT COALESCE(jsonb_object_agg(op, n), '{}'::jsonb) FROM oc) AS ops, (SELECT COALESCE(jsonb_agg(c), '[]'::jsonb) FROM oc, jsonb_array_elements(COALESCE(oc.changed, '[]'::jsonb)) c) AS ops_changed, (SELECT COALESCE(jsonb_agg(fingerprint), '[]'::jsonb) FROM op_checkpoints WHERE op='sync-hold' AND starts_with(fingerprint, $3 || ':')) AS holds FROM x, pg",
"SELECT 1 FROM persistence_requests r WHERE r.source_id=$1 AND r.slug='__managed_sync_checkpoint__' AND r.intent IS NOT NULL AND NOT r.compacted AND r.operation='submit_job' AND r.intent->>'kind'='managed_sync_checkpoint' AND r.state IN ('failed','conflict','cancelled') AND NOT EXISTS (SELECT 1 FROM persistence_requests c WHERE (c.source_id=r.source_id AND c.slug=r.slug AND c.sequence>r.sequence AND ( (c.digest=r.digest AND c.state IN ('committed','failed','queued','running','recovering')) OR (c.state IN ('committed','queued','running','recovering') AND (c.operation IN ('delete_page','purge_page') OR r.operation='put_page')) OR (r.slug='__managed_sync_checkpoint__' AND r.operation='submit_job' AND c.state='committed' AND c.operation='submit_job' AND COALESCE((SELECT k.intent->>'kind' FROM persistence_requests k WHERE k.id=r.id),'managed_sync_checkpoint')='managed_sync_checkpoint' AND COALESCE(c.intent->>'kind','managed_sync_checkpoint')='managed_sync_checkpoint') OR (r.operation='put_page' AND c.state='failed' AND c.operation='put_page' AND COALESCE(NOT (c.intent ? 'kind'), false))))) LIMIT 1",
"SELECT p.id, p.slug, p.source_path, p.knowledge_revision::text AS revision, p.deleted_at IS NOT NULL AS deleted, p.revision_write_request_id::text AS request_id, c.fingerprint IS NOT NULL AS has_record, c.origin IS NOT DISTINCT FROM p.source_path AS rec_origin_same, CASE WHEN c.origin IS DISTINCT FROM p.source_path THEN c.origin END AS rec_origin, c.blob_oid AS rec_blob_oid, c.disk_blob_oid IS NOT DISTINCT FROM c.blob_oid AS rec_disk_same, CASE WHEN c.disk_blob_oid IS DISTINCT FROM c.blob_oid THEN c.disk_blob_oid END AS rec_disk_blob_oid, c.revision IS NULL AS rec_revision_null, NULLIF(c.revision, p.knowledge_revision::text) AS rec_revision, CASE WHEN c.parser IS DISTINCT FROM $4::jsonb THEN c.parser::text END AS rec_parser, c.parser = $4::jsonb AS rec_parser_expected, c.full_episode AS rec_full_episode, c.working AS rec_working FROM pages p LEFT JOIN (SELECT fingerprint, completed_keys->0->>'origin' AS origin, completed_keys->0->>'blob_oid' AS blob_oid, completed_keys->0->>'disk_blob_oid' AS disk_blob_oid, completed_keys->0->>'revision' AS revision, completed_keys->0->'parser' AS parser, completed_keys->0->>'full_episode' AS full_episode, (completed_keys->0->'working')::text AS working FROM op_checkpoints WHERE op=$2) c ON c.fingerprint=$3||p.id::text WHERE p.source_id=$1 AND p.source_path IS NOT NULL AND p.id = ANY($5::bigint[]) ORDER BY p.id",
"SELECT p.id::text AS id, r.intent->>'level' AS level, r.intent->>'path' AS path FROM pages p JOIN persistence_requests r ON r.id=p.revision_write_request_id WHERE p.source_id=$1 AND p.id = ANY($2::bigint[])",
@@ -245,7 +245,7 @@
"SELECT GREATEST((SELECT max(sequence) FROM persistence_requests WHERE worktree_id=$1::uuid), (SELECT max(sequence) FROM persistence_requests WHERE worktree_id IS NULL AND source_id=$2 AND source_incarnation=$3::uuid))::text AS hwm",
"SELECT last_commit, config->>'slug_root_mode' AS mode FROM sources WHERE id=$1 AND incarnation=$2::uuid",
"SET LOCAL jit = off",
- "WITH x AS MATERIALIZED (SELECT txid_snapshot_xmin(txid_current_snapshot()) AS now_lo, txid_snapshot_xmax(txid_current_snapshot()) AS hi, age(($4::bigint % 4294967296)::text::xid) AS lo_age, txid_current_snapshot()::text AS now_snapshot, txid_current_if_assigned()::text AS now_own), s1 AS MATERIALIZED (SELECT ARRAY(SELECT txid_snapshot_xip($7::txid_snapshot)) AS xip, $8::bigint AS own, LEAST(txid_snapshot_xmax($7::txid_snapshot), (SELECT min(t) FROM txid_snapshot_xip($7::txid_snapshot) t WHERE txid_visible_in_snapshot(t, txid_current_snapshot()))) AS cut), pg AS (SELECT count(*) FILTER (WHERE p.source_path IS NOT NULL)::int AS n, COALESCE(jsonb_agg(jsonb_build_array(p.id::text, EXISTS (SELECT 1 FROM persistence_requests r WHERE r.id=p.revision_write_request_id AND r.source_id=$1 AND (r.id=$6::uuid OR r.state='committed' AND r.intent->>'passId'=$5 AND r.outcome->>'revision'=p.knowledge_revision::text)), p.knowledge_revision::text)) FILTER (WHERE NOT (age(p.xmin) > x.lo_age OR COALESCE((x.hi - ((x.hi % 4294967296) - p.xmin::text::bigint + 4294967296) % 4294967296) < s1.cut AND (x.hi - ((x.hi % 4294967296) - p.xmin::text::bigint + 4294967296) % 4294967296) <> ALL(s1.xip) AND (x.hi - ((x.hi % 4294967296) - p.xmin::text::bigint + 4294967296) % 4294967296) IS DISTINCT FROM s1.own, false))), '[]'::jsonb) AS changed FROM pages p, x, s1 WHERE p.source_id=$1), oc AS (SELECT o.op, count(*)::int AS n, jsonb_agg(jsonb_build_array(o.op, o.fingerprint, o.completed_keys->0->>'revision', o.completed_keys->0->>'run_id')) FILTER (WHERE NOT (age(o.xmin) > x.lo_age OR COALESCE((x.hi - ((x.hi % 4294967296) - o.xmin::text::bigint + 4294967296) % 4294967296) < s1.cut AND (x.hi - ((x.hi % 4294967296) - o.xmin::text::bigint + 4294967296) % 4294967296) <> ALL(s1.xip) AND (x.hi - ((x.hi % 4294967296) - o.xmin::text::bigint + 4294967296) % 4294967296) IS DISTINCT FROM s1.own, false))) AS changed FROM op_checkpoints o, x, s1 WHERE o.op = ANY($2:",
+ "WITH x AS MATERIALIZED (SELECT txid_snapshot_xmin(txid_current_snapshot()) AS now_lo, txid_snapshot_xmax(txid_current_snapshot()) AS hi, age((($4::bigint) % 4294967296)::text::xid) AS lo_age, txid_current_snapshot()::text AS now_snapshot, txid_current_if_assigned()::text AS now_own), s1 AS MATERIALIZED (SELECT age(((c.cut) % 4294967296)::text::xid) AS cut_age, ARRAY(SELECT ((t) % 4294967296)::text::xid FROM unnest(c.xip) t) AS xip, ((c.own) % 4294967296)::text::xid AS own FROM (SELECT ARRAY(SELECT txid_snapshot_xip($7::txid_snapshot)) AS xip, $8::bigint AS own, LEAST(txid_snapshot_xmax($7::txid_snapshot), (SELECT min(t) FROM txid_snapshot_xip($7::txid_snapshot) t WHERE txid_visible_in_snapshot(t, txid_current_snapshot()))) AS cut) c), pg AS (SELECT count(*) FILTER (WHERE p.source_path IS NOT NULL)::int AS n, COALESCE(jsonb_agg(jsonb_build_array(p.id::text, EXISTS (SELECT 1 FROM persistence_requests r WHERE r.id=p.revision_write_request_id AND r.source_id=$1 AND (r.id=$6::uuid OR r.state='committed' AND r.intent->>'passId'=$5 AND r.outcome->>'revision'=p.knowledge_revision::text)), p.knowledge_revision::text)) FILTER (WHERE NOT (age(p.xmin) > x.lo_age OR COALESCE(age(p.xmin) > s1.cut_age AND p.xmin <> ALL(s1.xip) AND p.xmin IS DISTINCT FROM s1.own, false))), '[]'::jsonb) AS changed FROM pages p, x, s1 WHERE p.source_id=$1), oc AS (SELECT o.op, count(*)::int AS n, jsonb_agg(jsonb_build_array(o.op, o.fingerprint, o.completed_keys->0->>'revision', o.completed_keys->0->>'run_id')) FILTER (WHERE NOT (age(o.xmin) > x.lo_age OR COALESCE(age(o.xmin) > s1.cut_age AND o.xmin <> ALL(s1.xip) AND o.xmin IS DISTINCT FROM s1.own, false))) AS changed FROM op_checkpoints o, x, s1 WHERE o.op = ANY($2::text[]) AND (o.fingerprint = $3 OR starts_with(o.fingerprint, $3 || ':')) GROUP BY o.op) SELECT x.now_lo::text AS xmin, x.now_snapshot AS snapshot, x.now_own AS own, (x.hi - $4::bigint)::float8 AS span, pg.n AS pages, pg.changed AS pa",
"SELECT 1 FROM persistence_requests r WHERE r.source_id=$1 AND r.slug='__managed_sync_checkpoint__' AND r.intent IS NOT NULL AND NOT r.compacted AND r.operation='submit_job' AND r.intent->>'kind'='managed_sync_checkpoint' AND r.state IN ('failed','conflict','cancelled') AND NOT EXISTS (SELECT 1 FROM persistence_requests c WHERE (c.source_id=r.source_id AND c.slug=r.slug AND c.sequence>r.sequence AND ( (c.digest=r.digest AND c.state IN ('committed','failed','queued','running','recovering')) OR (c.state IN ('committed','queued','running','recovering') AND (c.operation IN ('delete_page','purge_page') OR r.operation='put_page')) OR (r.slug='__managed_sync_checkpoint__' AND r.operation='submit_job' AND c.state='committed' AND c.operation='submit_job' AND COALESCE((SELECT k.intent->>'kind' FROM persistence_requests k WHERE k.id=r.id),'managed_sync_checkpoint')='managed_sync_checkpoint' AND COALESCE(c.intent->>'kind','managed_sync_checkpoint')='managed_sync_checkpoint') OR (r.operation='put_page' AND c.state='failed' AND c.operation='put_page' AND COALESCE(NOT (c.intent ? 'kind'), false))))) LIMIT 1",
"(SELECT 'r:'||request_id::text AS id FROM persistence_requests WHERE state IN ('queued','running','recovering') AND (worktree_id=$1::uuid OR worktree_id IS NULL AND source_id=$4 AND source_incarnation=$5::uuid) AND request_id IS DISTINCT FROM $2::uuid LIMIT $3) UNION ALL (SELECT 'e:'||e.id::text FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE r.worktree_id=$1::uuid AND e.kind='git' AND e.state IN ('queued','running') LIMIT $3)",
"SELECT p.id, p.slug, p.source_path, p.knowledge_revision::text AS revision, p.deleted_at IS NOT NULL AS deleted, p.revision_write_request_id::text AS request_id, c.fingerprint IS NOT NULL AS has_record, c.origin IS NOT DISTINCT FROM p.source_path AS rec_origin_same, CASE WHEN c.origin IS DISTINCT FROM p.source_path THEN c.origin END AS rec_origin, c.blob_oid AS rec_blob_oid, c.disk_blob_oid IS NOT DISTINCT FROM c.blob_oid AS rec_disk_same, CASE WHEN c.disk_blob_oid IS DISTINCT FROM c.blob_oid THEN c.disk_blob_oid END AS rec_disk_blob_oid, c.revision IS NULL AS rec_revision_null, NULLIF(c.revision, p.knowledge_revision::text) AS rec_revision, CASE WHEN c.parser IS DISTINCT FROM $4::jsonb THEN c.parser::text END AS rec_parser, c.parser = $4::jsonb AS rec_parser_expected, c.full_episode AS rec_full_episode, c.working AS rec_working FROM pages p LEFT JOIN (SELECT fingerprint, completed_keys->0->>'origin' AS origin, completed_keys->0->>'blob_oid' AS blob_oid, completed_keys->0->>'disk_blob_oid' AS disk_blob_oid, completed_keys->0->>'revision' AS revision, completed_keys->0->'parser' AS parser, completed_keys->0->>'full_episode' AS full_episode, (completed_keys->0->'working')::text AS working FROM op_checkpoints WHERE op=$2) c ON c.fingerprint=$3||p.id::text WHERE p.source_id=$1 AND p.source_path IS NOT NULL AND p.id = ANY($5::bigint[]) ORDER BY p.id",
diff --git a/test/sync-pass-xid-arms-gbra108.test.ts b/test/sync-pass-xid-arms-gbra108.test.ts
new file mode 100644
index 0000000000..7494c84336
--- /dev/null
+++ b/test/sync-pass-xid-arms-gbra108.test.ts
@@ -0,0 +1,131 @@
+/**
+ * GBRA-108: the confirm round's fold proof (src/core/persistence/sync-pass-confirm.ts) judges each row against S1's
+ * snapshot in the 32-bit xid space: S1's 64-bit cut, in-progress list and own id become xids, and a row is unchanged when
+ * \`age(xmin) > age(S1.xmin)\` or \`age(xmin) > age(cut)\`, its xmin is not listed and is not S1's own. This replaced the
+ * 64-bit form (each xmin widened against S2's xmax and compared as a 64-bit id), which cost a per-row cast and three
+ * widenings on every row a held older transaction kept from the \`age\` short-circuit.
+ *
+ * Protects: for generated xid layouts the 32-bit predicate's verdict equals the 64-bit form's on every row, under the
+ * proof's bound (every id within 2^31 of S2; a txid never has the low words 0-2). The layouts cover S1 with and without
+ * in-progress transactions, an idle older transaction holding S1's xmin, subtransaction ids above the cut, rows exactly at
+ * the cut, at S1's xmax and at S1's own id, frozen and bootstrap xmins, rows newer than S2's own id, no recorded snapshot,
+ * and the 32-bit wrap: \`age\` counts back from this transaction's real id, the 64-bit ids are that id's low word placed in
+ * a synthetic epoch, and rows below it cross into the previous epoch's top words.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { loAge, s1XidArms, unchanged } from '../src/core/persistence/sync-pass-confirm.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const W = 4294967296n;
+const SPAN = 2n ** 31n;
+/** The replaced 64-bit form: a 32-bit xmin widened against S2's xmax, compared with S1's 64-bit cut, list and own id. */
+const full = (col: string) => '(x.hi - ((x.hi % 4294967296) - ' + col + '::text::bigint + 4294967296) % 4294967296)';
+const sixtyFour = (col: string) => '(age(' + col + ') > x.lo_age OR COALESCE(' + full(col) + ' < s1.cut64 AND ' + full(col) + ' <> ALL(s1.xip64) AND '
+ + full(col) + ' IS DISTINCT FROM s1.own64, false))';
+const VERDICTS = 'WITH x AS (SELECT $1::bigint AS hi, ' + loAge('$2::bigint') + ' AS lo_age),\n'
+ + ' c AS (SELECT $3::bigint AS cut, $4::bigint[] AS xip, $5::bigint AS own),\n'
+ + ' s1 AS (SELECT ' + s1XidArms('c.cut', 'c.xip', 'c.own') + ', c.cut AS cut64, c.xip AS xip64, c.own AS own64 FROM c),\n'
+ + ' v AS (SELECT n, t::xid AS xmin FROM unnest($6::text[]) WITH ORDINALITY AS r(t, n))\n'
+ + 'SELECT v.n::int AS n, ' + unchanged('v.xmin') + ' AS xid32, ' + sixtyFour('v.xmin') + ' AS id64, age(v.xmin) > x.lo_age AS by_lo FROM v, x, s1 ORDER BY v.n';
+
+/** A seeded generator (mulberry32), so a failing layout reproduces. */
+function rng(seed: number) {
+ let a = seed >>> 0;
+ const next = () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
+ return { int: (lo: number, hi: number) => lo + Math.floor(next() * (hi - lo + 1)), pick: <T>(xs: readonly T[]) => xs[Math.floor(next() * xs.length)]!, chance: (p: number) => next() < p };
+}
+/** A real txid never takes the special low words 0 (invalid), 1 (bootstrap) or 2 (frozen). */
+const normal = (id: bigint) => id % W > 2n;
+
+interface Layout { hi: bigint; lo: bigint; cut: bigint | null; xip: bigint[]; own: bigint | null; rows: string[]; crossing: boolean }
+
+/** One layout around \`now\` (this transaction's real id): every 64-bit id is shifted by \`epoch\` words, keeping its low word. */
+function layout(now: bigint, seed: number): Layout {
+ const r = rng(seed);
+ const epoch = BigInt(r.pick([1, 2, 7, 1 << 20]));
+ const shift = epoch * W;
+ const base = shift + now;
+ const hi = base + BigInt(r.int(1, 800));
+ // How far below S2 S1 sits: near, past the 32-bit wrap below the real id, or near the 2^31 bound.
+ const reach = r.pick([BigInt(r.int(5, 2000)), now % W + BigInt(r.int(1, 5000)), SPAN - BigInt(r.int(5000, 20000))]);
+ const s1Max = base + BigInt(r.int(-1500, 400)) - (r.chance(0.5) ? reach : 0n);
+ const shape = r.pick(['empty', 'listed', 'idle-older', 'no-snapshot'] as const);
+ const xip: bigint[] = [];
+ if (shape === 'listed' || shape === 'idle-older') for (let i = r.int(1, 5); i > 0; i--) xip.push(s1Max - BigInt(r.int(1, 1500)));
+ if (shape === 'idle-older') xip.push(hi - reach - BigInt(r.int(0, 3)));
+ const listed = [...new Set(xip.filter(normal).filter(id => hi - id < SPAN))].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
+ const xmin = listed.length ? listed[0]! : s1Max;
+ const committed = listed.filter(() => r.chance(0.5));
+ const cut = shape === 'no-snapshot' ? null : committed.reduce((m, id) => (id < m ? id : m), s1Max);
+ const own = shape !== 'no-snapshot' && r.chance(0.6) ? (() => { for (let i = 0; i < 20; i++) { const id = xmin + BigInt(r.int(0, Number(s1Max - xmin))); if (!listed.includes(id) && normal(id)) return id; } return null; })() : null;
+ const near = (id: bigint | null) => (id === null ? [] : [id - 1n, id, id + 1n]);
+ const ids = [...near(cut), ...near(s1Max), ...near(own), ...near(xmin), ...listed.flatMap(near), ...near(hi - 1n), ...near(base),
+ ...Array.from({ length: 6 }, () => (cut ?? s1Max) + BigInt(r.int(1, 300))),
+ ...Array.from({ length: 10 }, () => hi - 1n - BigInt(r.int(0, Number(hi - xmin + 2000n)))),
+ ...Array.from({ length: 4 }, () => shift - BigInt(r.int(0, 3000))), ...Array.from({ length: 4 }, () => shift + BigInt(r.int(3, 3000)))];
+ const rows = [...new Set(ids.filter(id => id < hi && hi - id < SPAN && normal(id)).map(id => String(id % W))), '2', '1'];
+ const crossing = [hi, xmin, ...ids].some(id => id < shift) && [hi, xmin].some(id => id >= shift);
+ return { hi, lo: xmin, cut, xip: listed, own, rows, crossing };
+}
+
+const backends = testBackends();
+const engines: Array<[string, BrainEngine]> = [];
+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-xid-arms-'));
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(['pglite', engine]);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(['postgres', pg.engine]); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const [, engine] of engines) await engine.disconnect();
+ await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });
+});
+
+for (const backend of backends) {
+ describe('GBRA-108: the fold proof\'s 32-bit xid arms (' + backend + ')', () => {
+ test('agree with the 64-bit form on every row of every generated layout', async () => {
+ const engine = engines.find(([kind]) => kind === backend)![1];
+ const seen = { rows: 0, bySnapshot: 0, changedBySnapshot: 0, crossing: 0, idleOlder: 0, noSnapshot: 0 };
+ const disagreements: string[] = [];
+ await engine.transaction(async tx => {
+ // \`age\` counts back from this transaction's own id once it has one.
+ const [{ now }] = await tx.executeRaw<{ now: string }>('SELECT txid_current()::text AS now');
+ for (let seed = 1; seed <= 400; seed++) {
+ const l = layout(BigInt(now), seed);
+ const rows = await tx.executeRaw<{ n: number; xid32: boolean; id64: boolean; by_lo: boolean }>(VERDICTS,
+ [String(l.hi), String(l.lo), l.cut === null ? null : String(l.cut), '{' + l.xip.join(',') + '}', l.own === null ? null : String(l.own), '{' + l.rows.join(',') + '}']);
+ expect(rows.length).toBe(l.rows.length);
+ for (const row of rows) {
+ seen.rows++;
+ if (!row.by_lo) { seen.bySnapshot++; if (!row.id64) seen.changedBySnapshot++; }
+ if (row.xid32 !== row.id64) disagreements.push('seed ' + seed + ' xmin ' + l.rows[row.n - 1] + ': 32-bit ' + row.xid32 + ', 64-bit ' + row.id64 + ' ' + JSON.stringify(l, (_k, v) => typeof v === 'bigint' ? String(v) : v));
+ }
+ if (l.crossing) seen.crossing++;
+ if (l.cut === null) seen.noSnapshot++;
+ if (l.xip.length && l.lo < l.hi - 1_000_000n) seen.idleOlder++;
+ }
+ });
+ expect(disagreements.slice(0, 5)).toEqual([]);
+ // The layouts reach the snapshot arm on both verdicts, the 32-bit wrap, an idle older xmin and a missing snapshot.
+ expect(seen.bySnapshot).toBeGreaterThan(1000);
+ expect(seen.changedBySnapshot).toBeGreaterThan(100);
+ expect(seen.bySnapshot - seen.changedBySnapshot).toBeGreaterThan(100);
+ expect(seen.crossing).toBeGreaterThan(20);
+ expect(seen.idleOlder).toBeGreaterThan(20);
+ expect(seen.noSnapshot).toBeGreaterThan(20);
+ }, 180_000);
+ });
+}