Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(persistence): source-row diagnostics on source_changed for #6427 and the managed-atoms connector case

time-attackedf3d0fc59ca
diff --git a/test/e2e/managed-extract-atoms.test.ts b/test/e2e/managed-extract-atoms.test.ts
index 667d5a004f..e8b43d2068 100644
--- a/test/e2e/managed-extract-atoms.test.ts
+++ b/test/e2e/managed-extract-atoms.test.ts
@@ -1,6 +1,7 @@
import { afterAll, beforeAll, describe, test } from 'bun:test';
import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withSourceRowDiagnostics } from '../helpers/source-row-diagnostics.ts';
import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManagedAtomBatch, atomAuthorityCases, exerciseManagedAtomAuthority, exerciseManagedAtomReconciliation, atomRetirementCases, exerciseManagedAtomRetirement } from '../helpers/managed-atoms-contract.ts';
(process.env.DATABASE_URL ? describe : describe.skip)('managed atom PostgreSQL caller parity', () => {
@@ -10,7 +11,7 @@ import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManage
fixture = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
}, 120_000);
afterAll(async () => { await fixture?.close(); resetGateway(); });
- for (const scenario of atomContractCases) test(scenario, () => exerciseManagedAtoms(fixture.engine, scenario), 60_000);
+ for (const scenario of atomContractCases) test(scenario, () => withSourceRowDiagnostics(fixture.engine, `atoms-${scenario.replaceAll('_', '-')}`, () => exerciseManagedAtoms(fixture.engine, scenario)), 60_000);
for (const scenario of atomBatchCases) test(`batch ${scenario}`, () => exerciseManagedAtomBatch(fixture.engine, scenario), 60_000);
for (const scenario of atomAuthorityCases) test(`authority ${scenario} rejects normal and dry runs before providers`, () => exerciseManagedAtomAuthority(fixture.engine, scenario), 60_000);
test('reconciles stale atom pages and files', () => exerciseManagedAtomReconciliation(fixture.engine), 60_000);
diff --git a/test/helpers/source-row-diagnostics.ts b/test/helpers/source-row-diagnostics.ts
new file mode 100644
index 0000000000..ecbbcd900d
--- /dev/null
+++ b/test/helpers/source-row-diagnostics.ts
@@ -0,0 +1,43 @@
+import postgres from '#postgres';
+import type { BrainEngine } from '../../src/core/engine.ts';
+
+/**
+ * #6427 and the managed-atoms connector flake: a source that setup just wrote is reported
+ * missing or archived. On a `source_changed` failure this appends what each reader saw (the
+ * engine's own connection, a fresh client on the same database, every sources row and the
+ * database's sessions), then rethrows the original error unchanged otherwise.
+ */
+export async function withSourceRowDiagnostics<T>(engine: BrainEngine, sourceId: string, run: () => Promise<T>): Promise<T> {
+ try {
+ return await run();
+ } catch (error) {
+ if ((error as { code?: string }).code === 'source_changed' && error instanceof Error) {
+ error.message += `\n[source-row diagnostics]\n${await sourceRowDiagnostics(engine, sourceId)}`;
+ }
+ throw error;
+ }
+}
+
+export async function sourceRowDiagnostics(engine: BrainEngine, sourceId: string): Promise<string> {
+ const lines: string[] = [];
+ const read = async (label: string, query: () => Promise<unknown>) => {
+ try { lines.push(`${label}: ${JSON.stringify(await query())}`); } catch (error) { lines.push(`${label}: (query failed: ${(error as Error).message})`); }
+ };
+ await read('engine row', () => engine.executeRaw('SELECT to_jsonb(s) AS row FROM sources s WHERE id=$1', [sourceId]));
+ await read('all sources', () => engine.executeRaw('SELECT id,archived,archived_at,incarnation::text,local_path,config FROM sources ORDER BY id'));
+ if (engine.kind !== 'postgres') return lines.join('\n');
+ await read('engine session', () => engine.executeRaw(`SELECT current_database() AS database,pg_backend_pid() AS pid,current_user AS role,session_user AS session_role,
+ current_setting('search_path') AS search_path,current_setting('row_security') AS row_security,current_setting('transaction_isolation') AS isolation,
+ txid_current_if_assigned()::text AS xid,pg_current_snapshot()::text AS snapshot`));
+ const [{ database }] = await engine.executeRaw<{ database: string }>('SELECT current_database() AS database');
+ const url = new URL(process.env.DATABASE_URL!);
+ url.pathname = `/${database}`;
+ const fresh = postgres(url.toString(), { max: 1, prepare: false });
+ try {
+ await read('fresh client row', () => fresh.unsafe('SELECT to_jsonb(s) AS row FROM sources s WHERE id=$1', [sourceId]));
+ await read('fresh client session', () => fresh.unsafe('SELECT current_database() AS database,pg_backend_pid() AS pid,current_user AS role'));
+ await read('pg_stat_activity', () => fresh.unsafe(`SELECT pid,usename,application_name,state,xact_start::text,backend_xid::text,backend_xmin::text,left(query,200) AS query
+ FROM pg_stat_activity WHERE datname=$1 ORDER BY pid`, [database]));
+ } finally { await fresh.end(); }
+ return lines.join('\n');
+}
diff --git a/test/persistence-connector-recovery.test.ts b/test/persistence-connector-recovery.test.ts
index 860db72e66..6eae4af4a5 100644
--- a/test/persistence-connector-recovery.test.ts
+++ b/test/persistence-connector-recovery.test.ts
@@ -10,6 +10,7 @@ import type { WriteRequest } from '../src/core/persistence/model.ts';
import { parseMarkdown } from '../src/core/markdown.ts';
import { beginConnectorSync } from '../src/core/persistence/connector-sync.ts';
import { withEnv } from './helpers/with-env.ts';
+import { withSourceRowDiagnostics } from './helpers/source-row-diagnostics.ts';
import { createConnectorFixture, options, json, googleConfig, githubConfig, contact, githubFetch, sourceCheckpoint } from './helpers/connector-fixture.ts';
const { engines, env, boundSource, standaloneConnector, setup, teardown } = createConnectorFixture();
@@ -97,7 +98,7 @@ test('an already authenticated connector session drains later retained recovery
const config = parseGitHubSourceConfig(githubConfig, f.dir);
await runGitHubSync(engine, f.id, config, options, githubFetch());
await disposePersistenceConsumer(engine);
- const session = (await beginConnectorSync(engine, f.id, 'github', config, options))!;
+ const session = (await withSourceRowDiagnostics(engine, f.id, () => beginConnectorSync(engine, f.id, 'github', config, options)))!;
const crash = await standaloneConnector(engine, f, githubConfig, true);
expect(crash.stdout).toContain('CONNECTOR_AFTER_PUBLICATION_BEFORE_COMMIT');
const [retained] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 AND recovery IS NOT NULL', [f.id]);
diff --git a/test/source-row-diagnostics.test.ts b/test/source-row-diagnostics.test.ts
new file mode 100644
index 0000000000..7223b1e3cc
--- /dev/null
+++ b/test/source-row-diagnostics.test.ts
@@ -0,0 +1,53 @@
+/**
+ * The source-row diagnostic (test/helpers/source-row-diagnostics.ts) that #6427 and the
+ * managed-atoms connector case attach to a `source_changed` failure.
+ * Protects: the original error is rethrown with what the engine and a fresh client saw;
+ * other errors and successes pass through untouched.
+ * Seams: none; PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { opError } from '../src/core/ops/contract.ts';
+import { withSourceRowDiagnostics } from './helpers/source-row-diagnostics.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const closers: Array<() => Promise<void>> = [];
+afterAll(async () => { for (const close of closers.splice(0)) await close(); });
+
+async function open(backend: 'pglite' | 'postgres'): Promise<BrainEngine> {
+ if (backend === 'postgres') {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ closers.push(pg.close);
+ return pg.engine;
+ }
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ closers.push(() => engine.disconnect());
+ return engine;
+}
+
+for (const backend of testBackends()) describe(`${backend}: withSourceRowDiagnostics`, () => {
+ test('a source_changed failure carries the engine and fresh-client views; other outcomes pass through', async () => {
+ const engine = await open(backend);
+ await engine.executeRaw("INSERT INTO sources(id,name,archived,archived_at) VALUES('diag-archived','diag-archived',true,now())");
+ const original = opError('source_changed', 'The atom source is unavailable.', 'Source diag-archived is missing or archived.');
+ const caught = await withSourceRowDiagnostics(engine, 'diag-archived', async () => { throw original; }).then(() => null, (e: Error) => e);
+ expect(caught).toBe(original);
+ expect(caught!.message).toStartWith('The atom source is unavailable.');
+ expect(caught!.message).toContain('[source-row diagnostics]');
+ expect(caught!.message).toMatch(/engine row: \[\{"row":\{[^\n]*"id":"diag-archived"[^\n]*"archived":true/);
+ expect(caught!.message).toContain('all sources: ');
+ if (backend === 'postgres') {
+ for (const label of ['engine session: ', 'fresh client row: ', 'fresh client session: ', 'pg_stat_activity: ']) expect(caught!.message).toContain(label);
+ expect(caught!.message).toMatch(/fresh client row: \[\{"row":\{[^\n]*"archived":true/);
+ }
+ expect(caught!.message).not.toContain('query failed');
+ const other = new Error('unrelated');
+ expect(await withSourceRowDiagnostics(engine, 'diag-archived', async () => { throw other; }).then(() => null, (e: Error) => e)).toBe(other);
+ expect(other.message).toBe('unrelated');
+ expect(await withSourceRowDiagnostics(engine, 'diag-archived', async () => 7)).toBe(7);
+ }, 120_000);
+});