Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#6712 PR 4b): the fold proof judges each row against S1's snapshot, so a held cluster xmin no longer blocks the fold
garrytan51df95b35875
diff --git a/src/core/persistence/sync-pass-confirm.ts b/src/core/persistence/sync-pass-confirm.tsindex b9e9dd5c5f..9ca89cb81f 100644--- a/src/core/persistence/sync-pass-confirm.ts+++ b/src/core/persistence/sync-pass-confirm.ts@@ -26,11 +26,19 @@* - Git: HEAD must equal the previous round's and the mode be committed (both are in the reuse key); `T` is cached by commit* and the index (`X`) is re-read by every round. Working mode always takes the full read.*- * Visibility: a row is unchanged only when its `xmin` is older than S1's `xmin` (`age(xmin) > age(S1.xmin)`, both counted- * back from S2's transaction counter in the 32-bit xid space; `age` of a frozen id is the largest): every transaction- * below S1's `xmin`, a subtransaction's included (`pg_visible_in_snapshot` cannot see subtransactions, which savepoints- * create), had ended before S1. `age` and the `txid_*` snapshot functions exist on every supported Postgres and on- * PGLite. More than 2^31 xids between S1's `xmin` and S2's `xmax` takes the full read (`age` would wrap).+ * Visibility: a row is unchanged when S1 saw its writer commit. Its `xmin` is older than S1's `xmin` (`age(xmin) >+ * age(S1.xmin)`, both counted back from S2's transaction counter in the 32-bit xid space; `age` of a frozen id is the+ * largest), or (GBRA-108) S1's snapshot, recorded with its mark, shows it ended: below S1's `xmax` and not in its+ * in-progress list. S1's list names top-level transactions only, and a row written inside a savepoint carries a+ * subtransaction id it does not list (publication's nested transactions, the fold's savepoint and the statistics refresh+ * 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+ * 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).*/import { GIT_HOLD_OP, GIT_HOLD_RETRY_OP, GIT_HOLD_SUMMARY_OP, SYNC_IMPORT_PROVENANCE_OP } from './sync-holds.ts';import { MANAGED_SYNC_PASS_OP, SYNC_DELETES_WITHHELD_OP, SYNC_ORIGIN_DELETED_OP } from './sync-pass-row.ts';@@ -41,8 +49,11 @@ type Exec = Pick<BrainEngine, 'executeRaw'>;export const CONFIRM_OPS = [SYNC_IMPORT_PROVENANCE_OP, GIT_HOLD_OP, GIT_HOLD_SUMMARY_OP, GIT_HOLD_RETRY_OP, SYNC_ORIGIN_DELETED_OP, SYNC_DELETES_WITHHELD_OP, MANAGED_SYNC_PASS_OP];-/** A round's mark: its snapshot's `xmin` (64-bit), each `CONFIRM_OPS` op's row count for the incarnation and its holds' fingerprints. */-export interface LevelMark { xmin: string; ops: Record<string, number>; holds: string[] }+/**+ * A round's mark: its snapshot's `xmin` (64-bit), each `CONFIRM_OPS` op's row count for the incarnation and its holds'+ * fingerprints; `snapshot` (`txid_current_snapshot()`) and `own` (its transaction's id, if it had one) judge rows exactly.+ */+export interface LevelMark { xmin: string; ops: Record<string, number>; holds: string[]; snapshot?: string; own?: string | null }/** The incarnation's `CONFIRM_OPS` rows (`o`: the table alias's prefix; `ops` and `scope`: their placeholders). */const opScope = (o: string, ops: string, scope: string) => `${o}op = ANY(${ops}::text[]) AND (${o}fingerprint = ${scope} OR starts_with(${o}fingerprint, ${scope} || ':'))`;@@ -51,36 +62,40 @@ const opCounts = (ops: string, scope: string) => `(SELECT COALESCE(jsonb_object_/** The round's mark, read inside its snapshot (on PGLite, before the round's other reads, so whatever lands later reads as changed). */export async function readLevelMark(exec: Exec, sourceId: string, incarnation: string): Promise<LevelMark> {- const [row] = await exec.executeRaw<{ xmin: string; ops: Record<string, number> | null; holds: string[] }>(- `SELECT txid_snapshot_xmin(txid_current_snapshot())::text AS xmin, ${opCounts('$1', '$2')}`,- [CONFIRM_OPS, `${sourceId}:${incarnation}`]);- return { xmin: row!.xmin, ops: row!.ops ?? {}, holds: row!.holds };+ const [row] = await exec.executeRaw<{ xmin: string; snapshot: string; own: string | null; ops: Record<string, number> | null; holds: string[] }>(+ `SELECT txid_snapshot_xmin(txid_current_snapshot())::text AS xmin, txid_current_snapshot()::text AS snapshot, txid_current_if_assigned()::text AS own,+ ${opCounts('$1', '$2')}`, [CONFIRM_OPS, `${sourceId}:${incarnation}`]);+ return { xmin: row!.xmin, ops: row!.ops ?? {}, holds: row!.holds, snapshot: row!.snapshot, own: row!.own };}-/** Whether `col` (an xid) was committed before S1: it is older than S1's `xmin` (`age` of a frozen id is the largest). */-const unchanged = (col: string) => `age(${col}) > x.lo_age`;+/** `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)`;+/** 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))`;/*** 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),+ 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=$1AND (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 ${unchanged('p.xmin')}), '[]'::jsonb) AS changed- FROM pages p, x WHERE p.source_id=$1),+ 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 ${unchanged('o.xmin')}) AS changed- FROM op_checkpoints o, x WHERE ${opScope('o.', '$2', '$3')} GROUP BY o.op)- SELECT x.now_lo::text AS xmin, (x.hi - $4::bigint)::float8 AS span, pg.n AS pages, pg.changed AS pages_changed,+ FROM op_checkpoints o, x, s1 WHERE ${opScope('o.', '$2', '$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='${GIT_HOLD_OP}' AND starts_with(fingerprint, $3 || ':')) AS holdsFROM x, pg`;-type ProofRow = { xmin: string; span: number; ops: Record<string, number> | null; holds: string[]; pages: number;+type ProofRow = { xmin: string; snapshot: string; own: string | null; span: number; ops: Record<string, number> | null; holds: string[]; pages: number;pages_changed: Array<[string, boolean, string]>; ops_changed: Array<[string, string, string | null, string | null]> };/**@@ -118,13 +133,13 @@ export type ConfirmProof = { ok: true; mark: LevelMark; pages: string[]; recordsexport async function proveConfirm(exec: Exec, input: { sourceId: string; incarnation: string; passId: string; base: LevelMark; recorded?: ReadonlySet<number>; postgres: boolean;parallel?: boolean; self?: string }): Promise<ConfirmProof> {const scope = `${input.sourceId}:${input.incarnation}`;- const params = [input.sourceId, CONFIRM_OPS, scope, input.base.xmin, input.passId, input.self ?? null];+ const params = [input.sourceId, CONFIRM_OPS, scope, input.base.xmin, input.passId, input.self ?? null, input.base.snapshot ?? null, input.base.own ?? null];// Two plain scans: compiling them (JIT, which the planner's cost picks at 600k) cost more than running them (about 200 ms).const jit = input.postgres ? exec.executeRaw('SET LOCAL jit = off') : Promise.resolve([]);jit.catch(() => undefined);const [row] = input.postgres && input.parallel ? await parallelProof(exec, input.sourceId, params) : await exec.executeRaw<ProofRow>(PROOF, params);await jit;- const mark: LevelMark = { xmin: row!.xmin, ops: row!.ops ?? {}, holds: row!.holds };+ const mark: LevelMark = { xmin: row!.xmin, ops: row!.ops ?? {}, holds: row!.holds, snapshot: row!.snapshot, own: row!.own };if (!(Number(row!.span) >= 0 && Number(row!.span) < 2 ** 31)) return { ok: false, reason: 'xid_span', mark };const revisions = new Map<string, string>();for (const [id, ours, revision] of row!.pages_changed) {diff --git a/test/e2e/sync-pass-fold-xmin-6712-postgres.test.ts b/test/e2e/sync-pass-fold-xmin-6712-postgres.test.tsnew file mode 100644index 0000000000..89dcf223f1--- /dev/null+++ b/test/e2e/sync-pass-fold-xmin-6712-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../sync-pass-fold-xmin-6712.test.ts'));diff --git a/test/fixtures/fold-hook-noop-6712.json b/test/fixtures/fold-hook-noop-6712.jsonindex 7d55cff99b..66e4d141c3 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), 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), '[]'::jsonb) AS changed FROM pages p, x 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) AS changed FROM op_checkpoints o, x 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.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 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","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), 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), '[]'::jsonb) AS changed FROM pages p, x 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) AS changed FROM op_checkpoints o, x 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.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 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:","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/managed-sync-drain.test.ts b/test/managed-sync-drain.test.tsindex d5034471c6..ce58a9763c 100644--- a/test/managed-sync-drain.test.ts+++ b/test/managed-sync-drain.test.ts@@ -76,7 +76,7 @@ test('a drain re-enters sliced passes over one cursor until it is synced and rec}}), 180_000);-test('a transaction open elsewhere in the cluster keeps the drain from folding its stamp: the last import publishes alone and a checkpoint request stamps the pass', async () => withEnv({ GBRAIN_HOME: home }, async () => {+test('a transaction open elsewhere in the cluster, holding back the cluster xmin, does not keep the drain from folding its stamp into the last import', async () => withEnv({ GBRAIN_HOME: home }, async () => {const engine = engines.find(candidate => candidate.kind === 'postgres');if (!engine) return;const f = await fixture(engine, 3);@@ -97,8 +97,7 @@ test('a transaction open elsewhere in the cluster keeps the drain from folding ioutcome->>'pass_stamp_skipped' AS skipped FROM persistence_requests WHERE source_id=$1 ORDER BY sequence`, [f.id]);expect(requests).toEqual([...Array.from({ length: 2 }, () => ({ kind: 'managed_sync_import', state: 'committed', stamp: null, skipped: null })),- { kind: 'managed_sync_import', state: 'committed', stamp: null, skipped: 'foreign_page_write' },- { kind: 'managed_sync_checkpoint', state: 'committed', stamp: null, skipped: null }]);+ { kind: 'managed_sync_import', state: 'committed', stamp: 'folded', skipped: null }]);const [source] = await engine.executeRaw<{ last_commit: string | null }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]);expect(source!.last_commit).toBe(git(f.root, 'rev-parse', 'HEAD'));}), 180_000);diff --git a/test/sync-pass-fold-xmin-6712.test.ts b/test/sync-pass-fold-xmin-6712.test.tsnew file mode 100644index 0000000000..0b767c4734--- /dev/null+++ b/test/sync-pass-fold-xmin-6712.test.ts@@ -0,0 +1,142 @@+/**+ * #6712 PR 4b (GBRA-108): the fold proof (sync-pass-confirm.ts) judges each row against S1's snapshot, not against its+ * xmin alone, so a transaction that holds the cluster's xmin back (a stuck idle-in-transaction session) no longer makes the+ * pass's earlier, already-visible writes read as foreign; a write S1 could not see is still caught, a subtransaction's+ * included.+ *+ * Protects:+ * - with an idle-in-transaction session (an assigned xid) opened before the brain's pages are written, a one-file+ * writeback still folds its stamp;+ * - with that session open, a foreign write committed between the round's level read and its fold is caught: the stamp+ * publishes alone (foreign_page_write) and the confirm round reads in full;+ * - a transaction in flight at S1 that writes an import record and commits mid-pass is caught, also when it writes it+ * inside a savepoint (its row's xmin is a subtransaction id S1's snapshot does not list, below S1's xmax once a later+ * transaction has ended).+ *+ * Postgres only (test/e2e/sync-pass-fold-xmin-6712-postgres.test.ts): each case needs a second transaction open beside+ * the pass, which PGLite's single connection cannot hold; on PGLite S1's snapshot never lists a running transaction.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import postgres from '#postgres';+import type { BrainEngine } from '../src/core/engine.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { testBackends } from './helpers/test-backends.ts';++const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, 'commit', '-qm', message); };+const note = (title: string, body: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ git(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');+ for (const slug of ['a', 'b']) writeFileSync(join(root, `notes/${slug}.md`), note(`notes/${slug}`, `The committed body of notes/${slug}.`));+ commit(root, 'notes');+};+/** A one-file commit whose file is not canonical: its import rewrites it (a writeback). */+const writebackCommit = (root: string) => { writeFileSync(join(root, 'notes/a.md'), '---\ntitle: notes/a\n---\nA committed change of notes/a.\n'); commit(root, 'change a, not canonical'); };+const lastSequence = async (engine: BrainEngine) => Number((await engine.executeRaw<{ s: number }>('SELECT COALESCE(max(sequence),0) AS s FROM persistence_requests'))[0]!.s);+/** The requests after `after` that carried the pass stamp, and how each published it. */+const stamped = (engine: BrainEngine, after: number) => engine.executeRaw<{ kind: string; stamp: string | null; skipped: string | null }>(+ "SELECT intent->>'kind' AS kind, outcome->>'pass_stamp' AS stamp, outcome->>'pass_stamp_skipped' AS skipped FROM persistence_requests WHERE sequence > $1 AND intent ? 'stamp' ORDER BY sequence", [after]);+/** A page write outside the pass, as another writer of the source makes it (inside the caller's transaction). */+const foreignWrite = async (tx: BrainEngine) => {+ await tx.executeRaw("SELECT set_config('gbrain.write_sources','[\"default\"]',true)");+ await tx.executeRaw("UPDATE pages SET title=title||' (edited)' WHERE source_id='default' AND slug='notes/b'");+};+/**+ * A write of notes/b's import record outside the pass. A page write queues its projection rebuild, whose own later write+ * would be caught whatever the proof made of the first; the record write stands alone.+ */+const foreignRecordWrite = async (tx: BrainEngine) => {+ await tx.executeRaw("SELECT set_config('gbrain.write_sources','[\"default\"]',true)");+ const [row] = await tx.executeRaw<{ n: number }>(`WITH w AS (UPDATE op_checkpoints SET completed_keys=completed_keys WHERE op='sync-import-provenance'+ AND fingerprint LIKE 'default:%:' || (SELECT id FROM pages WHERE source_id='default' AND slug='notes/b')::text RETURNING 1) SELECT count(*)::int AS n FROM w`);+ expect(row!.n).toBe(1);+};+/** A session on the cluster that holds an assigned xid open until released (a read-only session, pg_dump's, holds none). */+function idleSession(url: string): { opened: Promise<void>; release: () => Promise<void> } {+ const sql = postgres(url, { max: 1 });+ let done: (() => void) | undefined, ready!: () => void;+ const opened = new Promise<void>(resolve => { ready = resolve; });+ const held = sql.begin(async tx => { await tx`SELECT txid_current()`; ready(); await new Promise<void>(resolve => { done = resolve; }); });+ return { opened, release: async () => { done?.(); await held.catch(() => undefined); await sql.end(); } };+}++const databaseUrl = process.env.DATABASE_URL;+afterEach(() => installFaultHook(undefined));++for (const backend of testBackends()) {+ if (backend !== 'postgres' || !databaseUrl) continue;+ const brain = (run: Parameters<typeof managedBrain>[0]) => managedBrain(run, { databaseUrl, setup });++ describe(`#6712 PR 4b fold proof under a held xmin (${backend})`, () => {+ test('an idle-in-transaction session opened before the pages were written: a one-file writeback still folds its stamp', () => brain(async ({ engine, root }) => {+ const session = idleSession(databaseUrl);+ await session.opened;+ try {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ writebackCommit(root);+ const after = await lastSequence(engine);+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');+ expect(await stamped(engine, after)).toEqual([{ kind: 'managed_sync_import', stamp: 'folded', skipped: null }]);+ } finally { await session.release(); }+ }), 180_000);++ test('with that session open, a foreign write between the level read and the fold is caught: the stamp publishes alone and the confirm round reads in full', () => brain(async ({ engine, root }) => {+ const session = idleSession(databaseUrl);+ await session.opened;+ try {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ writebackCommit(root);+ const after = await lastSequence(engine);+ const rounds: Array<{ round: number; taken: boolean | null; reason: string | null }> = [];+ installFaultHook(async (point, detail) => {+ if (point !== 'sync:level_read') return;+ rounds.push({ round: detail.round as number, taken: detail.level?.confirm?.taken ?? null, reason: detail.level?.confirm?.reason ?? null });+ if (detail.round === 1) await engine.transaction(async tx => { await foreignWrite(tx); });+ });+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');+ installFaultHook(undefined);+ expect((await stamped(engine, after)).map(row => [row.kind, row.stamp, row.skipped])).toEqual([+ ['managed_sync_import', null, 'foreign_page_write'], ['managed_sync_checkpoint', null, null]]);+ expect(rounds.find(round => round.round === 2)).toMatchObject({ taken: false, reason: 'foreign_page_write' });+ } finally { await session.release(); }+ }), 180_000);++ for (const savepoint of [false, true]) {+ test(`a transaction in flight at S1 that writes an import record${savepoint ? ' inside a savepoint' : ''} and commits mid-pass is caught`, () => brain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ writebackCommit(root);+ const after = await lastSequence(engine);+ let commitNow!: () => void, written!: () => void;+ const wrote = new Promise<void>(resolve => { written = resolve; });+ let inFlight: Promise<void> | null = null;+ installFaultHook(async (point, detail) => {+ if (point === 'sync:round_start' && detail.round === 1) {+ inFlight = engine.transaction(async tx => {+ await tx.executeRaw('SELECT txid_current()');+ if (savepoint) await tx.executeRaw('SAVEPOINT foreign_edit');+ await foreignRecordWrite(tx);+ if (savepoint) await tx.executeRaw('RELEASE SAVEPOINT foreign_edit');+ written();+ await new Promise<void>(resolve => { commitNow = resolve; });+ });+ await wrote;+ // A later transaction ends before S1, so S1's xmax passes the write's id: only its in-progress list can tell.+ await engine.executeRaw('SELECT txid_current()');+ }+ if (point === 'sync:level_read' && detail.round === 1) { commitNow(); await inFlight; }+ });+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');+ installFaultHook(undefined);+ expect((await stamped(engine, after)).map(row => [row.kind, row.stamp, row.skipped])).toEqual([+ ['managed_sync_import', null, 'foreign_checkpoint_write'], ['managed_sync_checkpoint', null, null]]);+ }), 180_000);+ }+ });+}