Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

graduation G2b: drain and target tests

garrytan80e9bd6a5128
diff --git a/test/graduation-drain.test.ts b/test/graduation-drain.test.ts
new file mode 100644
index 0000000000..cceb0f999e
--- /dev/null
+++ b/test/graduation-drain.test.ts
@@ -0,0 +1,115 @@
+/**
+ * Engine graduation drain (`src/core/persistence/graduation-drain.ts`) and the
+ * consumer's request-only mode (`requestsOnly` in `consumer.ts`).
+ *
+ * Protects: the pending request of a `buildHistoryFixture` brain drains to a
+ * terminal state through a request-only consumer that runs no effects (the
+ * drained request's effects stay queued for the target's worker), no resident
+ * service is left running, the blocker taxonomy (queued request drained;
+ * foreign host binding, writer admin lock and recovering effect refuse up
+ * front with their structured actions and the drain starts nothing), the
+ * `--drain-timeout` refusal shape, and the frozen source (writes fail,
+ * custody writes through `withSourceWritable` succeed).
+ * Fails when: the drain runs effect work, leaves a publication in flight,
+ * cancels or skips a request, or a frozen source accepts a background write.
+ * Seams: none; PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { GBrainConfig } from '../src/core/config.ts';
+import { buildHistoryFixture } from '../scripts/persistence/history-fixture.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { persistenceConsumerStatus } from '../src/core/persistence/service.ts';
+import { WRITER_ADMIN_LOCK_KEY } from '../src/core/persistence/admin-contract.ts';
+import { drainForGraduation, drainTimeoutError, freezeSource, graduationBlockers, unfreezeSource, withSourceWritable } from '../src/core/persistence/graduation-drain.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const config = (engine: string) => ({ engine, embedding_disabled: true }) as GBrainConfig;
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ test(`${backend}: request-only drain of a history brain, blockers, and the frozen source`, async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-graduation-drain-test-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ const fixture = await buildHistoryFixture(engine, { pages: 12, seed: 5, sources: 2, worktrees: 1, root: join(home, 'checkouts') });
+ const hostId = localHostId();
+ const before = await graduationBlockers(engine, hostId);
+ expect(before).toEqual([expect.objectContaining({ kind: 'request', id: fixture.queuedRequestId, needsUser: false })]);
+ expect(before[0]!.argv).toBeUndefined();
+ const delayedBefore = await engine.executeRaw('SELECT state, attempts, next_attempt_at::text AS at FROM persistence_effects WHERE id = $1', [fixture.delayedEffectId]);
+
+ const result = await drainForGraduation(engine, { timeoutMs: 30_000, hostId, config: config(engine.kind), pollMs: 50 });
+ expect(result).toEqual({ drained: [fixture.queuedRequestId], blockers: [] });
+ const [request] = await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id = $1::uuid', [fixture.queuedRequestId]);
+ expect(request!.state).toBe('committed');
+ const effects = await engine.executeRaw<{ state: string }>(`SELECT e.state FROM persistence_effects e JOIN persistence_requests r ON r.id = e.request_id
+ WHERE r.request_id = $1::uuid`, [fixture.queuedRequestId]);
+ expect(effects.length).toBeGreaterThan(0);
+ expect(effects.every(e => e.state === 'queued')).toBe(true);
+ expect(await engine.executeRaw('SELECT state, attempts, next_attempt_at::text AS at FROM persistence_effects WHERE id = $1', [fixture.delayedEffectId])).toEqual(delayedBefore);
+ expect(persistenceConsumerStatus(engine).state).toBe('not_running');
+ expect(await drainForGraduation(engine, { timeoutMs: 1000, hostId, config: config(engine.kind) })).toEqual({ drained: [], blockers: [] });
+
+ const [worktree] = await engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_worktrees LIMIT 1');
+ const foreignHost = randomUUID();
+ await engine.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL session_replication_role = replica');
+ await tx.executeRaw(`INSERT INTO persistence_host_bindings (worktree_id, host_id, local_path, coordination_path) VALUES ($1::uuid, $2::uuid, '/elsewhere', '/elsewhere/.coord')`,
+ [worktree!.id, foreignHost]);
+ await tx.executeRaw(`INSERT INTO config (key, value) VALUES ($1, '{"locked": true, "set_at": "2026-10-04T00:00:00Z"}')
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`, [WRITER_ADMIN_LOCK_KEY]);
+ await tx.executeRaw(`UPDATE persistence_effects SET recovery = '{"kind": "test"}'::jsonb WHERE id = $1`, [fixture.delayedEffectId]);
+ });
+ const blocked = await drainForGraduation(engine, { timeoutMs: 1000, hostId, config: config(engine.kind) });
+ expect(blocked.drained).toEqual([]);
+ expect(blocked.blockers).toEqual(expect.arrayContaining([
+ expect.objectContaining({ kind: 'writer_admin_lock', argv: ['gbrain', 'sources', 'writer', 'unlock'], needsUser: true }),
+ expect.objectContaining({ kind: 'foreign_host_binding', id: `${worktree!.id}:${foreignHost}`, needsUser: true,
+ argv: expect.arrayContaining(['gbrain', 'sources', 'writer', 'transfer', 'prepare']) }),
+ expect.objectContaining({ kind: 'effect_recovery', id: String(fixture.delayedEffectId), needsUser: false }),
+ ]));
+
+ if (engine.kind === 'pglite') {
+ await freezeSource(engine);
+ await expect(engine.executeRaw("UPDATE config SET value = value WHERE key = 'version'")).rejects.toThrow(/read-only transaction/);
+ expect(await engine.executeRaw("SELECT 1 FROM config WHERE key = 'version'")).toHaveLength(1);
+ await withSourceWritable(engine, tx => tx.executeRaw("INSERT INTO config (key, value) VALUES ('graduation.test', 'custody')"));
+ expect(await engine.executeRaw("SELECT value FROM config WHERE key = 'graduation.test'")).toEqual([{ value: 'custody' }]);
+ await expect(engine.executeRaw("DELETE FROM config WHERE key = 'graduation.test'")).rejects.toThrow(/read-only transaction/);
+ await unfreezeSource(engine);
+ await engine.executeRaw("DELETE FROM config WHERE key = 'graduation.test'");
+ } else {
+ await expect(freezeSource(engine)).rejects.toThrow(/PGLite source/);
+ }
+ } finally { await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }, 300_000);
+}
+
+describe('drainTimeoutError', () => {
+ test('progressing requests resume with twice the timeout', () => {
+ const json = drainTimeoutError([{ kind: 'request', id: 'r1', detail: 'put_page running (source a)', needsUser: false }], 60_000).toJSON() as Record<string, any>;
+ expect(json.code).toBe('graduation_drain_timeout');
+ expect(json.fix.argv).toEqual(['gbrain', 'migrate', '--resume', '--drain-timeout', '120', '--json']);
+ expect(json.fix.verify.argv).toEqual(['gbrain', 'migrate', '--status', '--json']);
+ expect(json.why).toContain('source is unchanged and still writable');
+ });
+
+ test('a blocker with its own action is named instead of a longer wait', () => {
+ const json = drainTimeoutError([
+ { kind: 'request', id: 'r1', detail: 'running', needsUser: false },
+ { kind: 'request', id: 'r2', detail: 'recovering', argv: ['gbrain', 'sync', '--source', 'a', '--no-pull', '--retry-failed'], needsUser: false },
+ ], 5_000).toJSON() as Record<string, any>;
+ expect(json.fix.argv).toEqual(['gbrain', 'sync', '--source', 'a', '--no-pull', '--retry-failed']);
+ expect(json.fix.actor).toBe('agent');
+ });
+});
diff --git a/test/graduation-target.test.ts b/test/graduation-target.test.ts
new file mode 100644
index 0000000000..e6ee4da3f9
--- /dev/null
+++ b/test/graduation-target.test.ts
@@ -0,0 +1,201 @@
+/**
+ * Engine graduation target side (`src/core/persistence/graduation-target.ts`).
+ *
+ * Protects: route resolution (`--url` / `--url-env`, explicit and derived DDL
+ * routes, no automatic session-pooler route), the target identity hash that
+ * excludes the password, redaction (no display form, refusal or blocker
+ * carries the password), plan blockers from a probe, and on Postgres the
+ * read-only probes (empty database, initialised seed-only schema, a schema
+ * with user rows, denied replica mode with table ownership, a non-owner with
+ * no bypass, wrong password), the nonce cross-check between routes (same
+ * database passes, a different database refuses) and the target engine pair.
+ * Fails when: a secret leaks into output, a password rotation changes the
+ * identity, a probe writes, or routes naming different databases pass.
+ * Seams: none; the Postgres cases need DATABASE_URL.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import postgres from '#postgres';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import type { TargetProbe } from '../src/core/persistence/engine-graduation.types.ts';
+import {
+ assertTargetReachable, chooseTriggerBypass, connectTargetEngines, crossCheckRoutes, probeTarget, redactTargetUrl, resolveTargetRoutes,
+ targetIdentity, targetProbeBlockers,
+} from '../src/core/persistence/graduation-target.ts';
+import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';
+
+const SECRET = 's3cr3t-Pa55';
+const thrown = (fn: () => unknown): Record<string, any> => {
+ try { fn(); } catch (error) { return (error as { toJSON(): Record<string, any> }).toJSON(); }
+ throw new Error('expected a refusal');
+};
+
+describe('routes, identity and redaction', () => {
+ test('--url-env reads the URL from the named variable; displays never carry the password', () => {
+ const routes = resolveTargetRoutes({ urlEnv: 'GBRAIN_TARGET_URL', env: { GBRAIN_TARGET_URL: `postgresql://alice:${SECRET}@db.example.com:6432/brain?sslmode=require&password=${SECRET}` } });
+ expect(routes).toMatchObject({ main: 'postgres://[email protected]:6432/brain', ddl: 'postgres://[email protected]:6432/brain', urlEnv: 'GBRAIN_TARGET_URL' });
+ expect(routes.ddlUrl).toBe(routes.mainUrl);
+ expect(JSON.stringify({ main: routes.main, ddl: routes.ddl })).not.toContain(SECRET);
+ });
+
+ test('Supabase transaction pooler derives the direct DDL route; an explicit override wins and is final', () => {
+ const url = `postgresql://postgres.abcdefghijklmnop:${SECRET}@aws-0-us-east-1.pooler.supabase.com:6543/postgres`;
+ const derived = resolveTargetRoutes({ url, env: {} });
+ expect(derived.ddl).toBe('postgres://[email protected]:5432/postgres');
+ const session = `postgresql://postgres.abcdefghijklmnop:${SECRET}@aws-0-us-east-1.pooler.supabase.com:5432/postgres`;
+ const explicit = resolveTargetRoutes({ url, env: { GBRAIN_DIRECT_DATABASE_URL: session } });
+ expect(explicit.ddlUrl).toBe(session);
+ expect(explicit.ddl).not.toContain(SECRET);
+ });
+
+ test('missing, doubled and non-Postgres targets refuse with --url-env commands', () => {
+ const missing = thrown(() => resolveTargetRoutes({ urlEnv: 'MY_TARGET', env: {} }));
+ expect(missing).toMatchObject({ code: 'graduation_target_unsupported' });
+ expect(missing.fix.argv).toEqual(['gbrain', 'migrate', '--to', 'postgres', '--url-env', 'MY_TARGET', '--plan', '--json']);
+ expect(thrown(() => resolveTargetRoutes({ url: 'postgres://a@h/d', urlEnv: 'X', env: { X: 'postgres://a@h/d' } })).code).toBe('graduation_target_unsupported');
+ const mysql = thrown(() => resolveTargetRoutes({ url: `mysql://root:${SECRET}@h/d`, env: {} }));
+ expect(JSON.stringify(mysql)).not.toContain(SECRET);
+ });
+
+ test('the identity hashes host, port, database and user, never the password', () => {
+ const a = targetIdentity(`postgres://alice:${SECRET}@DB.example.com/brain`);
+ const b = targetIdentity('postgres://alice:[email protected]:5432/brain');
+ expect(a).toEqual(b);
+ expect(a).toMatchObject({ host: 'db.example.com', port: 5432, database: 'brain', user: 'alice' });
+ expect(JSON.stringify(a)).not.toContain(SECRET);
+ expect(targetIdentity('postgres://alice:[email protected]/other').id).not.toBe(a.id);
+ expect(targetIdentity('postgres://bob:[email protected]/brain').id).not.toBe(a.id);
+ expect(targetIdentity('postgres://[email protected]').database).toBe('alice');
+ expect(redactTargetUrl(`postgres://alice:${SECRET}@h:1/d?password=${SECRET}`)).toBe('postgres://alice@h:1/d');
+ });
+});
+
+const baseProbe: TargetProbe = {
+ reachable: true, auth: true, ddl: { reachable: true, auth: true }, serverVersion: '16.4', serverVersionNum: 160004,
+ vector: { installed: null, available: '0.8.0', halfvec: true }, createPrivilege: { database: true, schema: true },
+ replicaRole: true, ownsTables: true, triggerBypass: 'session_replication_role', gbrainSchema: false, empty: true, nonEmptyTables: [],
+ embeddingColumns: [], otherSessions: 0,
+};
+
+describe('plan blockers from a probe', () => {
+ const routes = { main: 'postgres://alice@h:5432/d', ddl: 'postgres://alice@h:5432/d', urlEnv: 'GBRAIN_TARGET_URL' };
+ test('a ready target has none', () => { expect(targetProbeBlockers(baseProbe, routes)).toEqual([]); });
+
+ test('each unmet prerequisite names itself', () => {
+ const probe: TargetProbe = { ...baseProbe, serverVersion: '13.9', serverVersionNum: 130009, vector: { installed: '0.6.0', available: '0.6.0', halfvec: false },
+ createPrivilege: { database: false, schema: false }, replicaRole: false, ownsTables: false, triggerBypass: null, empty: false, nonEmptyTables: ['pages'],
+ embeddingColumns: [{ relation: 'content_chunks', column: 'embedding', type: 'vector(768)', dims: 768 }] };
+ const ids = targetProbeBlockers(probe, routes, [{ relation: 'content_chunks', column: 'embedding', type: 'vector(1536)', dims: 1536 }]).map(b => `${b.kind}:${b.id}`);
+ expect(ids).toEqual(['target_unsupported:server_version', 'target_unsupported:vector_halfvec', 'target_unsupported:create_privilege',
+ 'target_unsupported:trigger_bypass', 'target_not_empty:target', 'embedding_dimension:content_chunks.embedding']);
+ });
+
+ test('auth failure, unreachable DDL route and the forced bypass', () => {
+ const auth = thrown(() => assertTargetReachable({ ...baseProbe, auth: false, error: { code: '28P01', message: 'password authentication failed' } }, routes));
+ expect(auth).toMatchObject({ code: 'graduation_target_auth_failed' });
+ expect(auth.fix.argv).toContain('--url-env');
+ const ddl = thrown(() => assertTargetReachable({ ...baseProbe, ddl: { reachable: false, auth: false, error: { code: 'ENETUNREACH', message: 'x' } } }, routes));
+ expect(ddl).toMatchObject({ code: 'graduation_target_ddl_unreachable' });
+ expect(ddl.suggestion).toContain('GBRAIN_DIRECT_DATABASE_URL');
+ expect(chooseTriggerBypass({ replicaRole: false, triggerBypass: 'disable_trigger' }, 'session_replication_role')).toBeNull();
+ expect(chooseTriggerBypass({ replicaRole: true, triggerBypass: 'session_replication_role' }, 'disable_trigger')).toBe('disable_trigger');
+ });
+});
+
+const databaseUrl = process.env.DATABASE_URL;
+describe.skipIf(!databaseUrl)('Postgres probes and the route cross-check', () => {
+ const created: string[] = [];
+ const roles: string[] = [];
+ const admin = databaseUrl ? (assertSafeE2eDatabaseUrl(databaseUrl), postgres(databaseUrl, { max: 1, prepare: false, onnotice: () => {} })) : null;
+ const urlFor = (database: string, user?: string, password?: string) => {
+ const url = new URL(databaseUrl!); url.pathname = `/${database}`;
+ if (user) { url.username = user; url.password = password ?? ''; }
+ return url.toString();
+ };
+ const freshDatabase = async (owner?: string) => {
+ const name = `gbrain_test_graduation_target_${randomUUID().replace(/-/g, '')}`;
+ await admin!.unsafe(`CREATE DATABASE ${name}${owner ? ` OWNER ${owner}` : ''}`);
+ created.push(name);
+ return name;
+ };
+ afterAll(async () => {
+ for (const name of created) await admin!.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`).catch(() => {});
+ for (const role of roles) await admin!.unsafe(`DROP ROLE IF EXISTS ${role}`).catch(() => {});
+ await admin?.end();
+ });
+
+ test('empty, seed-only and non-empty targets; probes never write', async () => {
+ const name = await freshDatabase();
+ const routes = resolveTargetRoutes({ url: urlFor(name), env: {} });
+ const empty = await probeTarget(routes);
+ expect(empty).toMatchObject({ reachable: true, auth: true, empty: true, gbrainSchema: false, replicaRole: true, triggerBypass: 'session_replication_role',
+ createPrivilege: { database: true, schema: true }, ddl: { reachable: true, auth: true } });
+ expect(empty.serverVersionNum).toBeGreaterThanOrEqual(140000);
+ expect(empty.vector.halfvec).toBe(true);
+ expect(targetProbeBlockers(empty, routes)).toEqual([]);
+ const db = postgres(routes.mainUrl, { max: 1, onnotice: () => {} });
+ expect(await db.unsafe("SELECT count(*)::int AS n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public'")).toEqual([{ n: 0 }]);
+ await db.end();
+
+ const engine = new PostgresEngine();
+ await engine.connect({ database_url: routes.mainUrl, poolSize: 2 });
+ try {
+ await engine.initSchema();
+ const seeded = await probeTarget(routes);
+ expect(seeded).toMatchObject({ empty: true, gbrainSchema: true, nonEmptyTables: [] });
+ expect(seeded.embeddingColumns.map(c => `${c.relation}.${c.column}`)).toEqual(expect.arrayContaining(['content_chunks.embedding', 'facts.embedding']));
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('notes', 'Notes')");
+ await engine.executeRaw("UPDATE persistence_brain SET enabled = true");
+ const used = await probeTarget(routes);
+ expect(used.empty).toBe(false);
+ expect(used.nonEmptyTables).toEqual(['persistence_brain', 'sources']);
+ } finally { await engine.disconnect(); }
+ }, 120_000);
+
+ test('a wrong password is an auth failure with nothing secret in the refusal', async () => {
+ const name = await freshDatabase();
+ const routes = resolveTargetRoutes({ url: urlFor(name, new URL(databaseUrl!).username, SECRET), env: {} });
+ const probe = await probeTarget(routes, { timeoutSeconds: 5 });
+ expect(probe).toMatchObject({ reachable: true, auth: false });
+ const json = thrown(() => assertTargetReachable(probe, routes));
+ expect(json.code).toBe('graduation_target_auth_failed');
+ expect(JSON.stringify({ json, probe })).not.toContain(SECRET);
+ }, 60_000);
+
+ test('a non-superuser owner cannot use replica mode but owns its tables; a non-owner has no bypass', async () => {
+ const owner = `gbrain_grad_owner_${randomUUID().slice(0, 8)}`;
+ const other = `gbrain_grad_other_${randomUUID().slice(0, 8)}`;
+ await admin!.unsafe(`CREATE ROLE ${owner} LOGIN PASSWORD 'pw'`); roles.push(owner);
+ await admin!.unsafe(`CREATE ROLE ${other} LOGIN PASSWORD 'pw'`); roles.push(other);
+ const name = await freshDatabase(owner);
+ const db = postgres(urlFor(name), { max: 1, onnotice: () => {} });
+ await db.unsafe(`ALTER SCHEMA public OWNER TO ${owner}`);
+ await db.unsafe(`CREATE TABLE owned (id int PRIMARY KEY)`);
+ await db.unsafe(`ALTER TABLE owned OWNER TO ${owner}`);
+ await db.unsafe(`GRANT CONNECT ON DATABASE ${name} TO ${other}`);
+ await db.end();
+ const ownerProbe = await probeTarget(resolveTargetRoutes({ url: urlFor(name, owner, 'pw'), env: {} }));
+ expect(ownerProbe).toMatchObject({ replicaRole: false, ownsTables: true, triggerBypass: 'disable_trigger' });
+ const otherProbe = await probeTarget(resolveTargetRoutes({ url: urlFor(name, other, 'pw'), env: {} }));
+ expect(otherProbe).toMatchObject({ replicaRole: false, ownsTables: false, triggerBypass: null });
+ expect(targetProbeBlockers(otherProbe, { main: 'm' }).map(b => b.id)).toContain('trigger_bypass');
+ }, 60_000);
+
+ test('the nonce cross-check passes for one database and refuses a DDL route to another', async () => {
+ const a = await freshDatabase();
+ const b = await freshDatabase();
+ const pair = await connectTargetEngines(resolveTargetRoutes({ url: urlFor(a), env: { GBRAIN_DIRECT_DATABASE_URL: urlFor(a) } }));
+ try {
+ await crossCheckRoutes(pair.main, pair.ddl, 'run-same');
+ } finally { await pair.close(); }
+ const wrong = await connectTargetEngines(resolveTargetRoutes({ url: urlFor(a), env: { GBRAIN_DIRECT_DATABASE_URL: urlFor(b) } }));
+ try {
+ let error: unknown;
+ try { await crossCheckRoutes(wrong.main, wrong.ddl, 'run-wrong'); } catch (e) { error = e; }
+ const json = (error as { toJSON(): Record<string, any> }).toJSON();
+ expect(json.code).toBe('graduation_target_ddl_unreachable');
+ expect(json.why).toContain('run-wrong');
+ } finally { await wrong.close(); }
+ expect(process.env.GBRAIN_DIRECT_DATABASE_URL).toBeUndefined();
+ }, 60_000);
+});