Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): #6712 PR 4b folded stamp runs in a nested transaction so its validation timeout cannot fail the import (#5762 journey)

garrytan2a6327c460a8
diff --git a/src/core/persistence/sync-pass-fold.ts b/src/core/persistence/sync-pass-fold.ts
index a9547b0df3..e61b0dcbcd 100644
--- a/src/core/persistence/sync-pass-fold.ts
+++ b/src/core/persistence/sync-pass-fold.ts
@@ -114,16 +114,24 @@ export async function ownWritebackCommit(engine: Pick<BrainEngine, 'executeRaw'>
return [...blobs].every(([path, oid]) => { const content = sized.get(path)?.oid === oid && bytes.get(oid); return !!content && fileContentHash(content) === want.get(path); });
}
-/** Publishes the stamp in `tx` when its checks hold; else why not (`error`: a statement failed, rolled back to the savepoint). */
+/** A stamp whose checks did not hold: its savepoint rolls back, and the reason is returned. */
+class StampSkipped extends Error { constructor(readonly reason: string) { super(reason); } }
+
+/**
+ * Publishes the stamp in `tx` when its checks hold; else why not (`error`: a statement failed). The stamp runs in a nested
+ * transaction, so whatever it skips or fails rolls back to its savepoint and the import publishes alone. A raw SAVEPOINT is
+ * not enough on Postgres: postgres.js rethrows a failed statement when its transaction scope ends even after the caller
+ * caught it, so a stamp's checkpoint validation timeout would fail the whole import (#5762 recovery journey).
+ */
async function foldedStamp(tx: BrainEngine, input: { row: WriteRequest; p: SyncIntent; root: string }, outcome: Record<string, unknown>, writeback?: string): Promise<string | null> {
- await tx.executeRaw('SAVEPOINT gbrain_pass_stamp_fold');
try {
- const skipped = await provenStamp(tx, input, outcome, writeback);
- await tx.executeRaw(skipped ? 'ROLLBACK TO SAVEPOINT gbrain_pass_stamp_fold' : 'RELEASE SAVEPOINT gbrain_pass_stamp_fold');
- return skipped;
- } catch {
- await tx.executeRaw('ROLLBACK TO SAVEPOINT gbrain_pass_stamp_fold');
- return 'error';
+ await tx.transaction(async stamp => {
+ const skipped = await provenStamp(stamp, input, outcome, writeback);
+ if (skipped) throw new StampSkipped(skipped);
+ });
+ return null;
+ } catch (error) {
+ return error instanceof StampSkipped ? error.reason : 'error';
}
}
diff --git a/test/e2e/persistence-request-indexes-postgres.test.ts b/test/e2e/persistence-request-indexes-postgres.test.ts
index ac62cd57a4..a8e4e6b830 100644
--- a/test/e2e/persistence-request-indexes-postgres.test.ts
+++ b/test/e2e/persistence-request-indexes-postgres.test.ts
@@ -149,13 +149,17 @@ test('#5762 recovery journey: a checkpoint timeout with a dropped index is fixed
const f = await fixture();
await engine.executeRaw('DROP INDEX persistence_requests_sync_run_committed');
const transaction = engine.transaction;
+ // The validation statement times out in every transaction, nested ones included (the folded stamp runs in its own savepoint).
+ const slowed = (tx: PostgresEngine): PostgresEngine => new Proxy(tx, { get(target, property) {
+ if (property === 'executeRaw') return (sql: string, params?: unknown[]) => sql === OPEN_PASS_WORK_SQL
+ ? target.executeRaw('SELECT pg_sleep(8)::text AS request_id') : target.executeRaw(sql, params);
+ if (property === 'transaction') return <T>(run: (child: PostgresEngine) => Promise<T>, opts?: Parameters<PostgresEngine['transaction']>[1]) =>
+ target.transaction(child => run(slowed(child as PostgresEngine)), opts);
+ const value = Reflect.get(target, property);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } });
engine.transaction = async function<T>(this: PostgresEngine, run: (tx: PostgresEngine) => Promise<T>): Promise<T> {
- return transaction.call(this, tx => run(new Proxy(tx, { get(target, property) {
- if (property === 'executeRaw') return (sql: string, params?: unknown[]) => sql === OPEN_PASS_WORK_SQL
- ? target.executeRaw('SELECT pg_sleep(8)::text AS request_id') : target.executeRaw(sql, params);
- const value = Reflect.get(target, property);
- return typeof value === 'function' ? value.bind(target) : value;
- } }) as PostgresEngine)) as Promise<T>;
+ return transaction.call(this, tx => run(slowed(tx as PostgresEngine))) as Promise<T>;
} as PostgresEngine['transaction'];
let result: Awaited<ReturnType<typeof performManagedSync>>;
try {
diff --git a/test/fixtures/fold-hook-noop-6712.json b/test/fixtures/fold-hook-noop-6712.json
index e3ee651669..d66e124989 100644
--- a/test/fixtures/fold-hook-noop-6712.json
+++ b/test/fixtures/fold-hook-noop-6712.json
@@ -107,7 +107,7 @@
"UPDATE pages SET chunker_version=$5, text_projection_revision=CASE WHEN knowledge_revision=$4::uuid THEN knowledge_revision ELSE text_projection_revision END, search_vector=CASE WHEN knowledge_revision=$4::uuid THEN setweight(to_tsvector('english',gbrain_fts_input(COALESCE(title,''))),'A') || setweight(to_tsvector('english',gbrain_fts_input(left($3::text,65536))),'C') ELSE search_vector END WHERE source_id=$1 AND slug=$2 RETURNING id",
"SELECT COALESCE((completed_keys->0->>'count')::int,0) AS count FROM op_checkpoints WHERE op=$1 AND fingerprint=$2",
"INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb) ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()",
- "SAVEPOINT gbrain_pass_stamp_fold",
+ "SAVEPOINT gbrain_nested_1",
"SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE",
"SELECT completed_keys->0 AS value, updated_at FROM op_checkpoints WHERE op=$1 AND fingerprint=$2",
"(SELECT r.request_id::text AS request_id FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL LIMIT 1) UNION ALL (SELECT r.request_id::text FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running','recovering') AND r.request_id<>$2::uuid AND r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete','managed_sync_checkpoint') LIMIT 1) LIMIT 1",
@@ -122,7 +122,7 @@
"INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES ($1, $2, jsonb_build_array(jsonb_strip_nulls(jsonb_build_object('run_id',$3::text,'at',now(),'changed',$4::int,'extract',$5::boolean,'since',$6::text))), now()) ON CONFLICT (op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=CASE WHEN jsonb_array_length(op_checkpoints.completed_keys)>=16 THEN (op_checkpoints.completed_keys-0)||EXCLUDED.completed_keys ELSE op_checkpoints.completed_keys||EXCLUDED.completed_keys END",
"SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND sequence > $3::bigint AND state='committed' AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence",
"INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now()) ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now() WHERE $4::boolean OR op_checkpoints.completed_keys->0->>'lease_token'=$5 RETURNING 1",
- "RELEASE SAVEPOINT gbrain_pass_stamp_fold",
+ "RELEASE SAVEPOINT gbrain_nested_1",
"SELECT set_config('gbrain.write_sources',$1,true),set_config('gbrain.write_request',$2,true),set_config('gbrain.write_principal_kind',$3,true),set_config('gbrain.write_principal_id',$4,true),set_config('gbrain.write_trust_tier',$5,true),set_config('gbrain.write_origin',$6,true)",
"SELECT value FROM config WHERE key = $1",
"SELECT 1 FROM chronicle_page_state WHERE source_id=$1 AND page_id=$2 AND state='extracted' AND cardinality(event_hashes) > 0 LIMIT 1",
@@ -238,7 +238,7 @@
"UPDATE timeline_entries t SET detail=r.next FROM jsonb_to_recordset($2::text::jsonb) AS r(id integer,detail text,next text) WHERE t.page_id=$1 AND t.event_page_id IS NULL AND t.id=r.id AND t.detail=r.detail",
"SELECT k.row_num FROM takes k JOIN jsonb_to_recordset($2::text::jsonb) AS n(row_num integer,claim text,kind text,holder text) ON n.row_num=k.row_num WHERE k.page_id=$1 AND (k.claim,k.kind,k.holder) IS DISTINCT FROM (n.claim,n.kind,n.holder) ORDER BY k.row_num LIMIT $3",
"DELETE FROM takes WHERE page_id=$1 AND row_num=ANY($2::integer[])",
- "SAVEPOINT gbrain_pass_stamp_fold",
+ "savepoint \"s0\"",
"SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE",
"SELECT completed_keys->0 AS value, updated_at FROM op_checkpoints WHERE op=$1 AND fingerprint=$2",
"(SELECT r.request_id::text AS request_id FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL LIMIT 1) UNION ALL (SELECT r.request_id::text FROM persistence_requests r WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running','recovering') AND r.request_id<>$2::uuid AND r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete','managed_sync_checkpoint') LIMIT 1) LIMIT 1",
@@ -254,7 +254,6 @@
"INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES ($1, $2, jsonb_build_array(jsonb_strip_nulls(jsonb_build_object('run_id',$3::text,'at',now(),'changed',$4::int,'extract',$5::boolean,'since',$6::text))), now()) ON CONFLICT (op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=CASE WHEN jsonb_array_length(op_checkpoints.completed_keys)>=16 THEN (op_checkpoints.completed_keys-0)||EXCLUDED.completed_keys ELSE op_checkpoints.completed_keys||EXCLUDED.completed_keys END",
"SELECT intent->>'path' AS path, outcome->'fences_normalized' AS fences FROM persistence_requests WHERE worktree_id=$1::uuid AND source_id=$2 AND sequence > $3::bigint AND state='committed' AND intent->>'kind'='managed_sync_import' AND intent->>'passId' IS NOT NULL AND jsonb_typeof(outcome->'fences_normalized')='array' ORDER BY sequence",
"INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now()) ON CONFLICT (op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys, updated_at=now() WHERE $4::boolean OR op_checkpoints.completed_keys->0->>'lease_token'=$5 RETURNING 1",
- "RELEASE SAVEPOINT gbrain_pass_stamp_fold",
"SELECT set_config('gbrain.write_sources',$1,true),set_config('gbrain.write_request',$2,true),set_config('gbrain.write_principal_kind',$3,true),set_config('gbrain.write_principal_id',$4,true),set_config('gbrain.write_trust_tier',$5,true),set_config('gbrain.write_origin',$6,true)",
"SELECT value FROM config WHERE key = $1",
"SELECT 1 FROM chronicle_page_state WHERE source_id=$1 AND page_id=$2 AND state='extracted' AND cardinality(event_hashes) > 0 LIMIT 1",
diff --git a/test/fold-hook-noop-6712.test.ts b/test/fold-hook-noop-6712.test.ts
index 9b47c1fce6..6d63fea50f 100644
--- a/test/fold-hook-noop-6712.test.ts
+++ b/test/fold-hook-noop-6712.test.ts
@@ -27,11 +27,13 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OPEN_PASS_WORK_SQL } from '../src/core/persistence/checkpoint-validation.ts';
import { admitWrite } from '../src/core/persistence/journal.ts';
import { preparePageAdmission } from '../src/core/persistence/page-mutations.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { managedBrain } from './helpers/managed-brain.ts';
+import { FOLD_PASS_ROW_WRITE } from './helpers/managed-import-budget.ts';
import { countPgliteStatements, readSqlTrace, type StatementRecord } from './helpers/statement-counter.ts';
import { testBackends } from './helpers/test-backends.ts';
import { waitFor } from './helpers/wait-for.ts';
@@ -88,7 +90,7 @@ async function sequences(engine: BrainEngine, ctx: Parameters<typeof preparePage
expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A committed change of notes/a.')); commit(root, 'change a, canonical');
const canonicalImport = await recorded(engine, trace, async () => { expect((await performManagedSync(engine, OPTS)).status).toBe('synced'); },
- sql => sql === 'SAVEPOINT gbrain_pass_stamp_fold');
+ sql => sql === normalize(OPEN_PASS_WORK_SQL));
const putPage = await recorded(engine, trace, async () => {
const prepared = await preparePageAdmission(ctx, { operation: 'put_page', params: { slug: 'notes/new', request_id: randomUUID(), content: note('notes/new', 'An agent page.') } });
const { request_id } = await admitWrite(engine, prepared.admission!);
@@ -113,7 +115,7 @@ for (const backend of testBackends()) {
expect(got.put_page!.length).toBeGreaterThan(5);
expect(got.canonical_import!.length).toBeGreaterThan(5);
const want = process.env.CAPTURE_FOLD_NOOP === '1' ? got : golden[backend]!;
- const tailFrom = (sequence: string[]) => { const at = sequence.findLastIndex(sql => sql.startsWith('INSERT INTO persistence_effects (') || sql === 'RELEASE SAVEPOINT gbrain_pass_stamp_fold'); expect(at).toBeGreaterThan(0); return at; };
+ const tailFrom = (sequence: string[]) => { const at = sequence.findLastIndex(sql => sql.startsWith('INSERT INTO persistence_effects (') || FOLD_PASS_ROW_WRITE.test(sql)); expect(at).toBeGreaterThan(0); return at; };
const shape = (sequences: Record<string, string[]>) => backend === 'pglite' ? sequences : Object.fromEntries(Object.entries(sequences).map(([write, sequence]) =>
[write, { statements: [...sequence].sort(), tail: sequence.slice(tailFrom(sequence)) }]));
expect(shape(got)).toEqual(shape(want));
diff --git a/test/helpers/managed-import-budget.ts b/test/helpers/managed-import-budget.ts
index 896110d024..9739fafe4f 100644
--- a/test/helpers/managed-import-budget.ts
+++ b/test/helpers/managed-import-budget.ts
@@ -73,18 +73,25 @@ export function publicationOf(records: StatementRecord[]): StatementRecord[] {
throw new Error('no committed transaction inserted the page');
}
+/** The folded stamp's first statement (its lease check) and its last when it publishes (the pass row write). */
+export const FOLD_LEASE_READ = 'SELECT 1 FROM gbrain_cycle_locks WHERE id=$1 AND acquisition_token=$2::uuid AND ttl_expires_at > now() FOR SHARE';
+export const FOLD_PASS_ROW_WRITE = /^INSERT INTO op_checkpoints\(op,fingerprint,completed_keys,updated_at\) VALUES\(\$1,\$2,jsonb_build_array\(\$3::text::jsonb\),now\(\)\)/;
+
/**
- * #6712 PR 4b: the publication split into the folded pass stamp (its savepoint through its first release or rollback, a
- * writeback import's checkpoint published inside the page's transaction) and the import's own statements around it. A
- * publication without the fold is all import.
+ * #6712 PR 4b: the publication split into the folded pass stamp (a writeback import's checkpoint published inside the
+ * page's transaction) and the import's own statements around it. The stamp is a nested transaction: its savepoint (the one
+ * its lease check follows) through its release or rollback. postgres.js never releases a nested savepoint, so a Postgres
+ * stamp that publishes ends at its pass row write. A publication without the fold is all import.
*/
export function splitFoldBlock(publication: StatementRecord[]): { fold: StatementRecord[]; imported: StatementRecord[] } {
const statements = publication.filter(isStatement);
const texts = statements.map(record => flat(record.sql));
- const start = texts.indexOf('SAVEPOINT gbrain_pass_stamp_fold');
+ const start = texts.findIndex((text, i) => /^savepoint \S+$/i.test(text) && texts[i + 1] === FOLD_LEASE_READ);
if (start < 0) return { fold: [], imported: statements };
- const end = texts.findIndex((text, i) => i > start && /^(?:RELEASE|ROLLBACK TO) SAVEPOINT gbrain_pass_stamp_fold$/.test(text));
- if (end < 0) throw new Error('the folded stamp opened its savepoint and never released or rolled it back');
+ const name = texts[start]!.split(' ')[1]!;
+ const closed = texts.findIndex((text, i) => i > start && [`release savepoint ${name}`, `rollback to savepoint ${name}`, `rollback to ${name}`].includes(text.toLowerCase()));
+ const end = closed >= 0 ? closed : texts.findIndex((text, i) => i > start && FOLD_PASS_ROW_WRITE.test(text));
+ if (end < 0) throw new Error('the folded stamp opened its savepoint and neither closed it nor wrote the pass row');
return { fold: statements.slice(start, end + 1), imported: [...statements.slice(0, start), ...statements.slice(end + 1)] };
}