Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): keep the graduation-table presence cache to writer admission; two PostgreSQL-arm test races

garrytan32735e9a988c
diff --git a/src/core/persistence/graduation-custody.ts b/src/core/persistence/graduation-custody.ts
index 58cdec07eb..18c2ea227f 100644
--- a/src/core/persistence/graduation-custody.ts
+++ b/src/core/persistence/graduation-custody.ts
@@ -368,7 +368,7 @@ function cutoverSourceRefusal(runId: string, sourceDataDir: string | null): Oper
* (the verify-step replay probe sets it).
*/
export async function assertGraduationAdmission(tx: BrainEngine): Promise<void> {
- if (!await graduationTablePresent(tx)) return;
+ if (!await graduationTablePresent(tx, { cached: true })) return;
const [row] = await tx.executeRaw<{ role: string; run_id: string; state: string; source_data_dir: string | null; run: string | null }>(
`SELECT role, run_id::text AS run_id, state, source_data_dir, NULLIF(current_setting('${GRADUATION_RUN_SETTING}', true), '') AS run
FROM persistence_graduation WHERE singleton = 1`);
diff --git a/src/core/persistence/graduation-schema.ts b/src/core/persistence/graduation-schema.ts
index b4460d75b7..3e193d1a23 100644
--- a/src/core/persistence/graduation-schema.ts
+++ b/src/core/persistence/graduation-schema.ts
@@ -74,15 +74,19 @@ function parseJson<T>(value: unknown): T | null {
return value as T;
}
-/** Engines (their root, never a transaction clone) whose database is known to have the table; an absence is never kept. */
+/**
+ * Engines (their root, never a transaction clone) whose database is known to have the table; an absence is never
+ * kept. Only writer admission reads it (`cached`): a database that admits writes has the persistence schema, while
+ * a graduation target engine can be pointed at a database that does not have the table yet.
+ */
const tablePresent = new WeakSet<object>();
function rootEngine(engine: object): object {
let root = engine;
while (Object.hasOwn(root, '_pageTransaction')) root = Object.getPrototypeOf(root);
return root;
}
-export async function graduationTablePresent(engine: BrainEngine): Promise<boolean> {
- if (tablePresent.has(rootEngine(engine))) return true;
+export async function graduationTablePresent(engine: BrainEngine, opts: { cached?: boolean } = {}): Promise<boolean> {
+ if (opts.cached && tablePresent.has(rootEngine(engine))) return true;
const [row] = await engine.executeRaw<{ present: boolean }>(`SELECT to_regclass('persistence_graduation') IS NOT NULL AS present`);
if (row?.present === true) tablePresent.add(rootEngine(engine));
return row?.present === true;
diff --git a/test/fixtures/foreground-put-page-worker.ts b/test/fixtures/foreground-put-page-worker.ts
index 7341e41d2e..7c12cfcef4 100644
--- a/test/fixtures/foreground-put-page-worker.ts
+++ b/test/fixtures/foreground-put-page-worker.ts
@@ -11,24 +11,30 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { observeAdmissionTransactions } from '../../scripts/persistence/read-admission.ts';
-const engine = new PostgresEngine();
-await engine.connect({ database_url: process.env.WORKER_DATABASE_URL!, poolSize: 4 });
+// `admitted`: when the write's admission transaction committed (wall clock), so the test can tell a claim that
+// could already see the write from one that chose its row before the write was visible.
+let admittedAt: number | undefined;
+const postgres = new PostgresEngine();
+const engine = observeAdmissionTransactions(postgres, () => { admittedAt ??= Date.now(); });
+await postgres.connect({ database_url: process.env.WORKER_DATABASE_URL!, poolSize: 4 });
const sourceId = process.env.WORKER_SOURCE!;
const interval = Number(process.env.WORKER_INTERVAL_MS ?? '0');
-const results: Array<{ slug: string; state: string; error?: string; submitted: number; returned: number }> = [];
+const results: Array<{ slug: string; state: string; error?: string; submitted: number; returned: number; admitted?: number }> = [];
const logger = { info() {}, warn() {}, error() {} };
const go = process.env.WORKER_GO;
if (go) while (!existsSync(go) || !readFileSync(go, 'utf8')) await Bun.sleep(5);
const slugs = (go ? readFileSync(go, 'utf8') : process.env.WORKER_SLUGS!).split(',');
for (const slug of slugs) {
const submitted = Date.now();
+ admittedAt = undefined;
try {
const out = await submitPageMutation({ engine, config: { engine: 'postgres', database_url: process.env.WORKER_DATABASE_URL! }, remote: false, dryRun: false, sourceId, logger } as never,
{ operation: 'put_page', params: { slug, content: `---\ntitle: ${slug}\n---\nA foreground note written during the catch-up.\n` }, waitMs: 60_000 });
- results.push({ slug, state: String((out as { state?: string }).state ?? ''), submitted, returned: Date.now() });
+ results.push({ slug, state: String((out as { state?: string }).state ?? ''), submitted, returned: Date.now(), admitted: admittedAt });
} catch (error) {
- results.push({ slug, state: 'error', error: (error as Error).message, submitted, returned: Date.now() });
+ results.push({ slug, state: 'error', error: (error as Error).message, submitted, returned: Date.now(), admitted: admittedAt });
}
if (interval) await Bun.sleep(interval);
}
diff --git a/test/managed-sync-foreground-priority.test.ts b/test/managed-sync-foreground-priority.test.ts
index e9e628ecc4..4c630eb897 100644
--- a/test/managed-sync-foreground-priority.test.ts
+++ b/test/managed-sync-foreground-priority.test.ts
@@ -67,7 +67,7 @@ function writer(source: string, slugs: string[], intervalMs = 0, go?: string) {
return async () => {
const [stderr, code] = await Promise.all([new Response(child.stderr).text(), child.exited]);
if (code !== 0) throw new Error(`writer exited ${code}: ${stderr.slice(-2000)}`);
- return JSON.parse(readFileSync(out, 'utf8')) as Array<{ slug: string; state: string; error?: string; submitted: number; returned: number }>;
+ return JSON.parse(readFileSync(out, 'utf8')) as Array<{ slug: string; state: string; error?: string; submitted: number; returned: number; admitted?: number }>;
};
}
@@ -137,9 +137,11 @@ for (const lanes of [2, 1]) {
// With lanes, groups admitted ahead were queued when the write arrived; it still went first.
if (lanes > 1) expect(run.before.length).toBeGreaterThan(0);
const put = run.final.find(row => row.slug === run.target)!;
- // No sync group started (its head chosen) after the write was admitted and before it committed.
+ // No sync group started (its head chosen) after the write's admission committed and before the write committed.
+ // `created` is the admission transaction's start: a claim choosing its row before the commit cannot see the write.
+ expect(run.written.admitted).toBeGreaterThanOrEqual(put.created - 5);
const heads = run.final.filter(row => row.kind?.startsWith('managed_sync_') && (row.grp ?? row.request_id) === row.request_id);
- const early = heads.filter(row => { const claimed = run.claims.get(row.id) ?? Infinity; return claimed >= put.created && claimed < put.completed!; }).map(row => row.slug);
+ const early = heads.filter(row => { const claimed = run.claims.get(row.id) ?? Infinity; return claimed >= run.written.admitted! && claimed < put.completed!; }).map(row => row.slug);
expect(early).toEqual([]);
expect(run.final.filter(row => row.kind?.startsWith('managed_sync_import')).every(row => row.state === 'committed')).toBe(true);
}), 300_000);
diff --git a/test/managed-sync-lanes.test.ts b/test/managed-sync-lanes.test.ts
index bbc29f0550..87c73a2885 100644
--- a/test/managed-sync-lanes.test.ts
+++ b/test/managed-sync-lanes.test.ts
@@ -234,14 +234,21 @@ test('admit-ahead fits the writer\'s outstanding-request limit instead of stoppi
const [row] = await engine!.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running')", [f.id]);
admitted.push(row!.n);
});
- const result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 8 });
- installFaultHook(undefined);
+ // Every admission transaction the limit refused (an admission over it used to stop admit-ahead until the window drained).
+ const refused: string[] = [];
+ const transaction = engine.transaction;
+ engine.transaction = async function (this: BrainEngine, fn: (tx: BrainEngine) => Promise<unknown>) {
+ try { return await transaction.call(this, fn); }
+ catch (error) { if ((error as { code?: string }).code === 'queue_capacity') refused.push((error as Error).message); throw error; }
+ } as BrainEngine['transaction'];
+ let result;
+ try { result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 8 }); }
+ finally { engine.transaction = transaction; installFaultHook(undefined); }
expect(result.drain).toMatchObject({ outcome: 'synced' });
expect((await imports(engine, f.id)).every(row => row.state === 'committed')).toBe(true);
- // Groups kept being admitted ahead through the whole run: between the first admission and the last commits,
- // the sync never ran out of admitted requests (an admission over the limit used to stop admit-ahead until the window drained).
- const first = admitted.findIndex(n => n > 0), last = admitted.length - 1 - [...admitted].reverse().findIndex(n => n > 0);
- expect(admitted.slice(first, last + 1).filter(n => n === 0)).toEqual([]);
+ expect(refused).toEqual([]);
+ // Admit-ahead still kept groups admitted while it stayed under the limit.
+ expect(Math.max(...admitted)).toBeGreaterThan(8);
expect(Math.max(...admitted)).toBeLessThanOrEqual(40);
} finally {
installFaultHook(undefined);