Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(#6712 PR 4b): the drain's fold assertion waits for a settled cluster snapshot

garrytan4a4e2da538f9
diff --git a/test/managed-sync-drain.test.ts b/test/managed-sync-drain.test.ts
index fa15bd4614..d5034471c6 100644
--- a/test/managed-sync-drain.test.ts
+++ b/test/managed-sync-drain.test.ts
@@ -4,6 +4,7 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { execFileSync } from 'node:child_process';
+import postgres from '#postgres';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import type { BrainEngine } from '../src/core/engine.ts';
@@ -30,6 +31,23 @@ async function fixture(engine: BrainEngine, count: number) {
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
return { id, root };
}
+/**
+ * The fold's proof (sync-pass-confirm.ts) counts a row unchanged since its round's snapshot only when the row's xid is older
+ * than that snapshot's xmin, and any open transaction in the cluster holds the xmin back. A page an earlier pass of the drain
+ * wrote then reads as written since the snapshot by another pass (`foreign_page_write`), and the stamp takes its own
+ * checkpoint request: correct, and what the parallel Postgres lane does when another file's brain in the same cluster has a
+ * transaction open. A pass whose fold is asserted starts once every transaction older than the writes before it has ended.
+ */
+async function clusterSettled(engine: BrainEngine): Promise<void> {
+ if (engine.kind !== 'postgres') return;
+ const [{ next }] = await engine.executeRaw<{ next: string }>('SELECT txid_snapshot_xmax(txid_current_snapshot())::text AS next');
+ for (const deadline = Date.now() + 60_000; ;) {
+ const [{ low }] = await engine.executeRaw<{ low: string }>('SELECT txid_snapshot_xmin(txid_current_snapshot())::text AS low');
+ if (BigInt(low) >= BigInt(next)) return;
+ if (Date.now() > deadline) throw new Error(`a transaction in the cluster held the snapshot xmin below ${next} for 60 s`);
+ await Bun.sleep(20);
+ }
+}
beforeAll(async () => {
const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
@@ -47,8 +65,7 @@ test('a drain re-enters sliced passes over one cursor until it is synced and rec
for (const engine of engines) {
const f = await fixture(engine, 5);
const drainStartedAt = Date.now();
- const result = await runDrain({ pass: (signal, onProgress) =>
- performManagedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, signal, onProgress, drainStartedAt }, { maxPages: 1, maxMs: 60_000 }) });
+ const result = await runDrain({ pass: async (signal, onProgress) => { await clusterSettled(engine); return performManagedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, signal, onProgress, drainStartedAt }, { maxPages: 1, maxMs: 60_000 }); } });
expect(result.status).toBe('first_sync');
expect(result.added).toBe(5);
expect(result.drain).toMatchObject({ outcome: 'synced', written: 5, waived: 0, remaining: 0 });
@@ -59,6 +76,33 @@ 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 () => {
+ const engine = engines.find(candidate => candidate.kind === 'postgres');
+ if (!engine) return;
+ const f = await fixture(engine, 3);
+ const other = postgres(process.env.DATABASE_URL!, { max: 1 });
+ let release!: () => void;
+ const released = new Promise<void>(resolve => { release = resolve; });
+ let opened!: () => void;
+ const open = new Promise<void>(resolve => { opened = resolve; });
+ const held = other.begin(async sql => { await sql`SELECT txid_current()`; opened(); await released; });
+ try {
+ await open;
+ const drainStartedAt = Date.now();
+ const result = await runDrain({ pass: (signal, onProgress) =>
+ performManagedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, signal, onProgress, drainStartedAt }, { maxPages: 1, maxMs: 60_000 }) });
+ expect(result.drain).toMatchObject({ outcome: 'synced', written: 3, remaining: 0 });
+ } finally { release(); await held; await other.end(); }
+ const requests = await engine.executeRaw<{ kind: string; state: string; stamp: string | null; skipped: string | null }>(`SELECT intent->>'kind' AS kind, state, outcome->>'pass_stamp' AS stamp,
+ outcome->>'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 }]);
+ 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);
+
test('a stopped drain is resumable, its backlog is readable from any process, and a rerun finishes it', async () => withEnv({ GBRAIN_HOME: home }, async () => {
for (const engine of engines) {
const f = await fixture(engine, 6);