Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

graduation G2b: E2E copy round trip and test harness

garrytan3e48b8b19134
diff --git a/src/core/persistence/graduation-copy.ts b/src/core/persistence/graduation-copy.ts
index 33be18a958..479c48a640 100644
--- a/src/core/persistence/graduation-copy.ts
+++ b/src/core/persistence/graduation-copy.ts
@@ -222,7 +222,7 @@ export async function copyTable(e: GraduationEngines, entry: InventoryEntry,
return `((r.v->>${i})::${columns[i]!.type})`;
};
const insertExprs = columns.map(c => selfFk.includes(c.name) ? 'NULL' : transforms.get(c.name)?.sql(typed) ?? typed(c.name));
- const insertSql = `INSERT INTO ${targetIdent} (${columns.map(c => c.ident).join(', ')}) SELECT ${insertExprs.join(', ')} FROM jsonb_array_elements($1::jsonb) AS r(v)`;
+ const insertSql = `INSERT INTO ${targetIdent} (${columns.map(c => c.ident).join(', ')}) SELECT ${insertExprs.join(', ')} FROM jsonb_array_elements($1::text::jsonb) AS r(v)`;
const orderBy = pkColumns.map(c => c.collatable ? `${c.ident} COLLATE "C"` : c.ident).join(', ');
const keyset = `(${orderBy}) > (${pkColumns.map((c, j) => `$${j + 1}::${c.type}${c.collatable ? ' COLLATE "C"' : ''}`).join(', ')})`;
const batchBytes = opts.batchBytes ?? DEFAULT_COPY_BATCH_BYTES;
@@ -264,7 +264,7 @@ export async function copyTable(e: GraduationEngines, entry: InventoryEntry,
if (selfFk.length) {
const fkColumns = selfFk.map(name => columns[index.get(name)!]!);
const updateSql = `UPDATE ${targetIdent} AS t SET ${fkColumns.map((c, j) => `${c.ident} = (r.v->>${pkColumns.length + j})::${c.type}`).join(', ')}
- FROM jsonb_array_elements($1::jsonb) AS r(v) WHERE ${pkColumns.map((c, j) => `t.${c.ident} = (r.v->>${j})::${c.type}`).join(' AND ')}`;
+ FROM jsonb_array_elements($1::text::jsonb) AS r(v) WHERE ${pkColumns.map((c, j) => `t.${c.ident} = (r.v->>${j})::${c.type}`).join(' AND ')}`;
await scan(`(${fkColumns.map(c => `${c.ident} IS NOT NULL`).join(' OR ')})`, async rows => {
const payload = rows.map(row => [...pkColumns.map(c => row[index.get(c.name)!]), ...fkColumns.map(c => row[index.get(c.name)!] ?? null)]);
await tx.executeRaw(updateSql, [JSON.stringify(payload)]);
diff --git a/test/e2e/graduation-copy.test.ts b/test/e2e/graduation-copy.test.ts
new file mode 100644
index 0000000000..5a94c8e861
--- /dev/null
+++ b/test/e2e/graduation-copy.test.ts
@@ -0,0 +1,205 @@
+/**
+ * Engine graduation copier, end to end: a `buildHistoryFixture` PGLite brain
+ * (1,000 pages by default, GRADUATION_COPY_PAGES overrides) is drained with
+ * the request-only consumer, frozen, and copied table by table into fresh
+ * Postgres targets, once under `session_replication_role = replica` and once
+ * under the DISABLE TRIGGER fallback behind a database fence.
+ *
+ * Protects: verbatim copy with primary keys preserved (every carried table's
+ * canonical snapshot, transforms applied to the source side, equals the
+ * target), initSchema seed rows replaced, exact sequence positions, every FK
+ * satisfied, user triggers enabled after the copy, deferred HNSW/GIN indexes
+ * rebuilt, and the fence still refusing writes that lack the run identity.
+ * Fails when: a column, key, sequence position, trigger state or index set
+ * differs, or the copy needs a session the fence would refuse.
+ * Seams: none. Requires DATABASE_URL.
+ */
+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 { randomUUID } from 'node:crypto';
+import postgres from '#postgres';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { GBrainConfig } from '../../src/core/config.ts';
+import type { InventoryEntry, TriggerBypass } from '../../src/core/persistence/engine-graduation.types.ts';
+import { localHostId } from '../../src/core/persistence/identity.ts';
+import { buildHistoryFixture, HISTORY_FIXTURE_TABLES, type HistoryFixture } from '../../scripts/persistence/history-fixture.ts';
+import { copySequences, deferIndexes, buildDeferredIndexes, detectTriggerBypass } from '../../src/core/persistence/graduation-copy.ts';
+import { drainForGraduation, freezeSource } from '../../src/core/persistence/graduation-drain.ts';
+import { embeddingColumns } from '../../src/core/persistence/graduation-target.ts';
+import { copyAll, firstDifference, localCopyInventory, tableSnapshot } from '../helpers/graduation-copy-harness.ts';
+import { requirePostgresTestDatabase } from '../helpers/test-backends.ts';
+
+const databaseUrl = requirePostgresTestDatabase();
+const PAGES = Number(process.env.GRADUATION_COPY_PAGES ?? 1000);
+const priorHome = process.env.GBRAIN_HOME;
+const home = mkdtempSync(join(tmpdir(), 'gbrain-graduation-copy-e2e-'));
+const admin = postgres(databaseUrl, { max: 1, prepare: false, onnotice: () => {} });
+const databases: string[] = [];
+let source: PGLiteEngine;
+let fixture: HistoryFixture;
+let drained: readonly string[] = [];
+const timings: Record<string, number> = {};
+
+async function freshTarget(): Promise<PostgresEngine> {
+ const name = `gbrain_test_graduation_${randomUUID().replace(/-/g, '')}`;
+ await admin.unsafe(`CREATE DATABASE ${name}`);
+ databases.push(name);
+ const url = new URL(databaseUrl); url.pathname = `/${name}`;
+ const engine = new PostgresEngine();
+ await engine.connect({ database_url: url.toString(), poolSize: 4 });
+ await engine.initSchema();
+ return engine;
+}
+
+async function indexSet(engine: BrainEngine): Promise<string[]> {
+ const rows = await engine.executeRaw<{ name: string }>(`SELECT i.relname AS name FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid
+ JOIN pg_class t ON t.oid = x.indrelid JOIN pg_namespace n ON n.oid = t.relnamespace JOIN pg_am am ON am.oid = i.relam
+ WHERE n.nspname = 'public' AND am.amname IN ('hnsw', 'gin') ORDER BY 1`);
+ return rows.map(r => r.name);
+}
+
+async function fkOrphans(engine: BrainEngine): Promise<string[]> {
+ const fks = await engine.executeRaw<{ name: string; child: string; parent: string; child_cols: string[]; parent_cols: string[] }>(`SELECT k.conname AS name,
+ format('%I', c.relname) AS child, format('%I', p.relname) AS parent,
+ ARRAY(SELECT format('%I', a.attname) FROM unnest(k.conkey) WITH ORDINALITY u(n, o) JOIN pg_attribute a ON a.attrelid = k.conrelid AND a.attnum = u.n ORDER BY u.o) AS child_cols,
+ ARRAY(SELECT format('%I', a.attname) FROM unnest(k.confkey) WITH ORDINALITY u(n, o) JOIN pg_attribute a ON a.attrelid = k.confrelid AND a.attnum = u.n ORDER BY u.o) AS parent_cols
+ FROM pg_constraint k JOIN pg_class c ON c.oid = k.conrelid JOIN pg_class p ON p.oid = k.confrelid JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE k.contype = 'f' AND n.nspname = 'public'`);
+ const orphans: string[] = [];
+ for (const fk of fks) {
+ const [row] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM ${fk.child} c WHERE ${fk.child_cols.map(col => `c.${col} IS NOT NULL`).join(' AND ')}
+ AND NOT EXISTS (SELECT 1 FROM ${fk.parent} p WHERE ${fk.child_cols.map((col, i) => `p.${fk.parent_cols[i]} = c.${col}`).join(' AND ')})`);
+ if (Number(row!.n) > 0) orphans.push(`${fk.name}: ${row!.n}`);
+ }
+ return orphans;
+}
+
+async function installTestFence(target: BrainEngine, runId: string): Promise<void> {
+ await target.executeRaw(`CREATE OR REPLACE FUNCTION test_graduation_fence() RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN
+ IF current_setting('gbrain.graduation_run', true) IS DISTINCT FROM '${runId}' THEN
+ RAISE EXCEPTION 'graduation_in_progress';
+ END IF;
+ RETURN NULL;
+ END $$`);
+ const tables = await target.executeRaw<{ ident: string }>(`SELECT format('%I', c.relname) AS ident FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'public' AND c.relkind = 'r'`);
+ for (const t of tables) {
+ await target.executeRaw(`CREATE TRIGGER gbrain_graduation_fence BEFORE INSERT OR UPDATE OR DELETE OR TRUNCATE ON ${t.ident}
+ FOR EACH STATEMENT EXECUTE FUNCTION test_graduation_fence()`);
+ await target.executeRaw(`ALTER TABLE ${t.ident} ENABLE ALWAYS TRIGGER gbrain_graduation_fence`);
+ }
+}
+
+async function graduateInto(target: PostgresEngine, bypass: TriggerBypass, runId: string, label: string): Promise<InventoryEntry[]> {
+ const e = { source, target };
+ const entries = await localCopyInventory(e);
+ const before = await indexSet(target);
+ let t = performance.now();
+ const deferred = await deferIndexes(target, { runId });
+ expect(deferred.length).toBeGreaterThan(0);
+ expect(await indexSet(target)).toEqual([]);
+ timings[`${label}.defer_ms`] = Math.round(performance.now() - t);
+ t = performance.now();
+ const counts = await copyAll(e, entries, { bypass, runId, batchBytes: 256 * 1024 });
+ timings[`${label}.copy_ms`] = Math.round(performance.now() - t);
+ t = performance.now();
+ const positions = await copySequences(e, { runId });
+ timings[`${label}.sequences_ms`] = Math.round(performance.now() - t);
+ t = performance.now();
+ await buildDeferredIndexes(target, { runId, log: () => {} });
+ timings[`${label}.indexes_ms`] = Math.round(performance.now() - t);
+ expect(await indexSet(target)).toEqual(before);
+ expect(positions.length).toBeGreaterThan(40);
+ for (const table of HISTORY_FIXTURE_TABLES) expect({ table, copied: (counts[table] ?? 0) > 0 }).toEqual({ table, copied: true });
+ return entries;
+}
+
+async function assertEqualCopy(target: PostgresEngine, entries: readonly InventoryEntry[]): Promise<void> {
+ const differences: string[] = [];
+ for (const entry of entries) {
+ const [a, b] = [await tableSnapshot(source, entry, { applyTransforms: true }), await tableSnapshot(target, entry)];
+ const diff = firstDifference(a, b);
+ if (diff) differences.push(diff);
+ if (!diff) expect(b.keys).toEqual(a.keys);
+ }
+ expect(differences).toEqual([]);
+ expect(await fkOrphans(target)).toEqual([]);
+ const disabled = await target.executeRaw(`SELECT tgrelid::regclass::text AS relation, tgname FROM pg_trigger WHERE NOT tgisinternal AND tgenabled = 'D'`);
+ expect(disabled).toEqual([]);
+ const sequences = await source.executeRaw<{ name: string }>(`SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relkind = 'S'`);
+ for (const { name } of sequences) {
+ const [present] = await target.executeRaw<{ present: boolean }>("SELECT to_regclass(format('public.%I', $1::text)) IS NOT NULL AS present", [name]);
+ if (!present!.present) continue;
+ const [s] = await source.executeRaw<{ v: string; c: boolean }>(`SELECT last_value::text AS v, is_called AS c FROM ${name}`);
+ const [t] = await target.executeRaw<{ v: string; c: boolean }>(`SELECT last_value::text AS v, is_called AS c FROM ${name}`);
+ const next = (r: { v: string; c: boolean }) => BigInt(r.v) + (r.c ? 1n : 0n);
+ expect({ name, ok: next(t!) >= next(s!) }).toEqual({ name, ok: true });
+ }
+}
+
+beforeAll(async () => {
+ process.env.GBRAIN_HOME = home;
+ source = new PGLiteEngine();
+ await source.connect({});
+ await source.initSchema();
+ const t = performance.now();
+ fixture = await buildHistoryFixture(source, { pages: PAGES, seed: 7, sources: 3, worktrees: 2, root: join(home, 'checkouts') });
+ timings.fixture_ms = Math.round(performance.now() - t);
+ const d = performance.now();
+ const result = await drainForGraduation(source, { timeoutMs: 60_000, hostId: localHostId(), config: { engine: 'pglite', embedding_disabled: true } as GBrainConfig });
+ timings.drain_ms = Math.round(performance.now() - d);
+ expect(result.blockers).toEqual([]);
+ drained = result.drained;
+ await freezeSource(source);
+}, 1_800_000);
+
+afterAll(async () => {
+ process.stderr.write(`[graduation-copy e2e] pages=${PAGES} ${JSON.stringify(timings)}\n`);
+ await source?.disconnect();
+ for (const name of databases) await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`).catch(() => {});
+ await admin.end();
+ if (priorHome === undefined) delete process.env.GBRAIN_HOME; else process.env.GBRAIN_HOME = priorHome;
+ rmSync(home, { recursive: true, force: true });
+}, 120_000);
+
+describe(`graduation copy of a ${PAGES}-page history brain`, () => {
+ test('the pending request drained before the copy', () => {
+ expect(drained).toContain(fixture.queuedRequestId);
+ });
+
+ test('replica mode: every carried table round-trips with keys, sequences, FKs, triggers and indexes intact', async () => {
+ const target = await freshTarget();
+ try {
+ expect(await embeddingColumns((sql, p) => target.executeRaw(sql, p))).toEqual(await embeddingColumns((sql, p) => source.executeRaw(sql, p)));
+ expect(await detectTriggerBypass(target)).toBe('session_replication_role');
+ const entries = await graduateInto(target, 'session_replication_role', randomUUID(), 'replica');
+ await assertEqualCopy(target, entries);
+ const [brain] = await target.executeRaw<{ brain_id: string; enabled: boolean }>('SELECT brain_id::text AS brain_id, enabled FROM persistence_brain');
+ const [sourceBrain] = await source.executeRaw<{ brain_id: string }>('SELECT brain_id::text AS brain_id FROM persistence_brain');
+ expect(brain).toEqual({ brain_id: sourceBrain!.brain_id, enabled: false });
+ const delayedSql = "SELECT state, to_char(next_attempt_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS.US') AS at FROM persistence_effects WHERE id = $1";
+ const [delayed] = await target.executeRaw<{ state: string; at: string }>(delayedSql, [fixture.delayedEffectId]);
+ const [sourceDelayed] = await source.executeRaw<{ state: string; at: string }>(delayedSql, [fixture.delayedEffectId]);
+ expect(delayed).toEqual({ state: 'queued', at: sourceDelayed!.at });
+ } finally { await target.disconnect(); }
+ }, 900_000);
+
+ test('DISABLE TRIGGER fallback behind a fence: same copy, fence stays on for everyone else', async () => {
+ const target = await freshTarget();
+ const runId = randomUUID();
+ try {
+ await installTestFence(target, runId);
+ expect(target.executeRaw("UPDATE config SET value = value WHERE key = 'version'")).rejects.toThrow(/graduation_in_progress/);
+ const entries = await graduateInto(target, 'disable_trigger', runId, 'disable_trigger');
+ await assertEqualCopy(target, entries);
+ const fences = await target.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pg_trigger WHERE tgname = 'gbrain_graduation_fence' AND tgenabled = 'A'`);
+ expect(Number(fences[0]!.n)).toBeGreaterThan(90);
+ expect(target.executeRaw("DELETE FROM pages WHERE false")).rejects.toThrow(/graduation_in_progress/);
+ } finally { await target.disconnect(); }
+ }, 900_000);
+});
diff --git a/test/helpers/graduation-copy-harness.ts b/test/helpers/graduation-copy-harness.ts
new file mode 100644
index 0000000000..ed393b684e
--- /dev/null
+++ b/test/helpers/graduation-copy-harness.ts
@@ -0,0 +1,100 @@
+/**
+ * Test-only stand-ins for the graduation inventory lane: a local inventory
+ * derived from information_schema (every base table present on both engines,
+ * with the plan's non-carry classes and transforms), an FK topological order,
+ * and canonical per-table snapshots for comparing a source with its copy.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { GraduationEngines, InventoryClass, InventoryEntry, TriggerBypass } from '../../src/core/persistence/engine-graduation.types.ts';
+import { carryRowFilter, copyTable, tableColumns, transformFor } from '../../src/core/persistence/graduation-copy.ts';
+
+export const LOCAL_NON_CARRY: Readonly<Record<string, InventoryClass>> = {
+ planner_stats_deltas: 'discard', planner_stats_state: 'discard', gbrain_cycle_locks: 'discard', budget_reservations: 'discard',
+ subagent_rate_leases: 'discard', oauth_codes: 'discard', query_cache: 'rebuild', code_traversal_cache: 'rebuild',
+ file_migration_ledger: 'schema_owned', persistence_graduation: 'schema_owned',
+};
+
+export const LOCAL_TRANSFORMS: Readonly<Record<string, readonly string[]>> = {
+ minion_jobs: ['status', 'lock_token', 'lock_until', 'timeout_at', 'started_at'],
+ persistence_worktrees: ['heartbeat_at'],
+ persistence_effects: ['state', 'execution_token', 'claim_expires_at'],
+ persistence_brain: ['enabled'],
+};
+
+async function baseTables(engine: BrainEngine): Promise<string[]> {
+ const rows = await engine.executeRaw<{ name: string }>(
+ "SELECT table_name AS name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY 1");
+ return rows.map(r => r.name);
+}
+
+/** Carry and rebind entries for every table present on both engines, in FK topological order. */
+export async function localCopyInventory(e: GraduationEngines): Promise<InventoryEntry[]> {
+ const target = new Set(await baseTables(e.target));
+ const tables = (await baseTables(e.source)).filter(t => target.has(t) && !(t in LOCAL_NON_CARRY));
+ const edges = await e.source.executeRaw<{ child: string; parent: string }>(`SELECT c.relname AS child, p.relname AS parent
+ FROM pg_constraint k JOIN pg_class c ON c.oid = k.conrelid JOIN pg_class p ON p.oid = k.confrelid
+ WHERE k.contype = 'f' AND k.conrelid <> k.confrelid`);
+ const parents = new Map(tables.map(t => [t, new Set<string>()]));
+ for (const edge of edges) if (parents.has(edge.child) && parents.has(edge.parent)) parents.get(edge.child)!.add(edge.parent);
+ const ordered: string[] = [];
+ const seen = new Set<string>();
+ const visit = (t: string, path: Set<string>) => {
+ if (seen.has(t)) return;
+ if (path.has(t)) throw new Error(`FK cycle at ${t}`);
+ path.add(t);
+ for (const p of [...parents.get(t)!].sort()) visit(p, path);
+ path.delete(t); seen.add(t); ordered.push(t);
+ };
+ for (const t of tables) visit(t, new Set());
+ return ordered.map(relation => ({
+ relation, kind: 'table', class: relation === 'persistence_brain' ? 'rebind' : 'carry', engines: { pglite: true, postgres: true },
+ lossKind: 'user_data', transforms: (LOCAL_TRANSFORMS[relation] ?? []).map(column => ({ column, rule: transformFor(relation, column).rule })),
+ reason: 'test inventory',
+ }));
+}
+
+export async function copyAll(e: GraduationEngines, entries: readonly InventoryEntry[], opts: { bypass: TriggerBypass; runId: string; batchBytes?: number }):
+ Promise<Record<string, number>> {
+ const counts: Record<string, number> = {};
+ for (const entry of entries) counts[entry.relation] = (await copyTable(e, entry, opts)).rows;
+ return counts;
+}
+
+export interface TableSnapshot { relation: string; rows: number; sha256: string; keys: string[]; lines: string[] }
+
+/**
+ * Canonical snapshot: every column (generated ones included, in name order, since
+ * the engines' physical column order differs) as text under
+ * UTC/ISO rendering, ordered by primary key with COLLATE "C". With
+ * `applyTransforms` the entry's transforms are applied, so a source snapshot
+ * compares equal to its copy.
+ */
+export async function tableSnapshot(engine: BrainEngine, entry: InventoryEntry, opts: { applyTransforms?: boolean } = {}): Promise<TableSnapshot> {
+ const columns = (await tableColumns(engine, entry.relation)).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
+ const transforms = new Map(opts.applyTransforms ? entry.transforms.map(t => [t.column, transformFor(entry.relation, t.column)]) : []);
+ const identOf = (name: string) => columns.find(c => c.name === name)!.ident;
+ const pk = await engine.executeRaw<{ name: string }>(`SELECT a.attname AS name FROM pg_constraint k CROSS JOIN LATERAL unnest(k.conkey) WITH ORDINALITY AS u(attnum, ord)
+ JOIN pg_attribute a ON a.attrelid = k.conrelid AND a.attnum = u.attnum WHERE k.contype = 'p' AND k.conrelid = to_regclass(format('public.%I', $1::text)) ORDER BY u.ord`, [entry.relation]);
+ const order = pk.map(p => { const c = columns.find(col => col.name === p.name)!; return c.collatable ? `${c.ident} COLLATE "C"` : c.ident; }).join(', ');
+ const select = columns.map((c, i) => `(${transforms.get(c.name)?.sql(identOf) ?? c.ident})::text AS c${i}`).join(', ');
+ const filter = carryRowFilter(entry.relation);
+ const [{ ident }] = await engine.executeRaw<{ ident: string }>("SELECT format('%I', $1::text) AS ident", [entry.relation]);
+ const rows = await engine.transaction(async tx => {
+ for (const s of ["SET LOCAL TimeZone = 'UTC'", "SET LOCAL DateStyle = 'ISO'", 'SET LOCAL extra_float_digits = 3']) await tx.executeRaw(s);
+ return tx.executeRaw<Record<string, string | null>>(`SELECT ${select} FROM ${ident}${filter ? ` WHERE ${filter}` : ''} ORDER BY ${order}`);
+ });
+ const pkIndex = pk.map(p => columns.findIndex(c => c.name === p.name));
+ const lines = rows.map(r => JSON.stringify(columns.map((_, i) => r[`c${i}`] ?? null)));
+ const keys = rows.map(r => JSON.stringify(pkIndex.map(i => r[`c${i}`] ?? null)));
+ return { relation: entry.relation, rows: rows.length, sha256: createHash('sha256').update(lines.join('\n')).digest('hex'), keys, lines };
+}
+
+/** First differing row between two snapshots, for a readable assertion message. */
+export function firstDifference(a: TableSnapshot, b: TableSnapshot): string | null {
+ if (a.sha256 === b.sha256) return null;
+ for (let i = 0; i < Math.max(a.lines.length, b.lines.length); i++) {
+ if (a.lines[i] !== b.lines[i]) return `${a.relation} row ${i}: source ${a.lines[i] ?? '<none>'} target ${b.lines[i] ?? '<none>'}`.slice(0, 2000);
+ }
+ return `${a.relation}: digests differ`;
+}