Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test: two order and timing races CI exposed on the master merge
garrytanae4ed1cc2e2b
diff --git a/test/e2e/sync-lock-overlap-postgres.test.ts b/test/e2e/sync-lock-overlap-postgres.test.tsindex a8deb18fc3..082bd90443 100644--- a/test/e2e/sync-lock-overlap-postgres.test.ts+++ b/test/e2e/sync-lock-overlap-postgres.test.ts@@ -5,6 +5,7 @@ import { join, resolve } from 'node:path';import postgres from '#postgres'import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';import { makeGitFixture } from '../helpers/git-fixture.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';const databaseUrl = process.env.DATABASE_URL;const cli = resolve(import.meta.dir, '../../src/cli.ts');@@ -19,12 +20,17 @@ describe.skipIf(!databaseUrl)('sync lock overlap on Postgres', () => {mkdirSync(repo);const source = `lock-test-${crypto.randomUUID().slice(0, 8)}`;const lockKey = `gbrain-sync:${source}`;- const sql = postgres(databaseUrl!, { max: 2, onnotice: () => {} });+ // A database of its own with the schema already applied: the CLI's init+ // then finds an existing brain and leaves managed persistence off, whatever+ // earlier files in the shard did to the shared database.+ const isolated = await isolatedPersistencePostgres(databaseUrl!);+ const brainUrl = isolated.databaseUrl;+ const sql = postgres(brainUrl, { max: 2, onnotice: () => {} });const children: ReturnType<typeof Bun.spawn>[] = [];let barrier: Awaited<ReturnType<typeof sql.reserve>> | undefined;const env = {PATH: process.env.PATH!, HOME: home, GBRAIN_HOME: home,- DATABASE_URL: databaseUrl!, GBRAIN_DATABASE_URL: databaseUrl!,+ DATABASE_URL: brainUrl, GBRAIN_DATABASE_URL: brainUrl,GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_NO_GITIGNORE: '1',};const spawn = (args: string[]) => {@@ -56,7 +62,7 @@ describe.skipIf(!databaseUrl)('sync lock overlap on Postgres', () => {writeFileSync(join(repo, `${name}.md`), `---\ntitle: Lock fixture ${name}\ntype: note\n---\n\nGeneric lock fixture ${name}.\n`);}fixture.commitAll('seed lock fixtures');- await run(['init', '--non-interactive', '--no-embedding', '--url', databaseUrl!]);+ await run(['init', '--non-interactive', '--no-embedding', '--url', brainUrl]);await run(['sources', 'add', source, '--path', repo, '--no-federated']);barrier = await sql.reserve();@@ -117,15 +123,8 @@ describe.skipIf(!databaseUrl)('sync lock overlap on Postgres', () => {await barrier`ROLLBACK`;barrier.release();}- await sql`DELETE FROM gbrain_cycle_locks WHERE holder_host = ${hostname()} AND holder_pid = ANY(${children.map(c => c.pid)}::int[])`;- // On a fresh database the CLI's init activates managed persistence, so- // raw fixture cleanup must declare itself to the writer guard.- await sql.begin(async tx => {- await tx`SELECT set_config('gbrain.topology_change', 'on', true), set_config('gbrain.write_sources', ${JSON.stringify([source])}, true)`;- await tx`DELETE FROM facts WHERE source_id = ${source}`;- await tx`DELETE FROM sources WHERE id = ${source}`;- });await sql.end();+ await isolated.close();rmSync(home, { recursive: true, force: true });}}, 180_000);diff --git a/test/fixtures/foreground-put-page-worker.ts b/test/fixtures/foreground-put-page-worker.tsindex 3dfc77d0a2..2b1fe5ef08 100644--- a/test/fixtures/foreground-put-page-worker.ts+++ b/test/fixtures/foreground-put-page-worker.ts@@ -7,7 +7,8 @@* test can start the process ahead and write at a chosen moment). GBRAIN_HOME is the drain's, so both processes* are the same local writer on the same owner host. WORKER_PREPARING_HOLD_MS (optional): when this process claims its* own write, its preparation waits that long first (results record `held: [start, end]`), so the write stays claimed- * by this process, unpublished, while the drain's lanes hold the worktree.+ * by this process, unpublished, while the drain's lanes hold the worktree. WORKER_READY (optional): a file this process+ * creates once connected, so a test can wait for it before starting the drain.*/import { existsSync, readFileSync, writeFileSync } from 'node:fs';import { PostgresEngine } from '../../src/core/postgres-engine.ts';@@ -34,6 +35,7 @@ if (holdMs > 0) installFaultHook(async (point, detail) => {held = [start, Date.now()];});const logger = { info() {}, warn() {}, error() {} };+if (process.env.WORKER_READY) writeFileSync(process.env.WORKER_READY, String(process.pid));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(',');diff --git a/test/managed-sync-foreground-priority.test.ts b/test/managed-sync-foreground-priority.test.tsindex 228c5d0046..70daa0c977 100644--- a/test/managed-sync-foreground-priority.test.ts+++ b/test/managed-sync-foreground-priority.test.ts@@ -6,7 +6,7 @@*/import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { execFileSync } from 'node:child_process';@@ -61,11 +61,11 @@ function recordClaims(e: BrainEngine): { claims: Map<string, number>; restore: (} as BrainEngine['executeRaw'];return { claims, restore: () => { e.executeRaw = execute; } };}-function writer(source: string, slugs: string[], intervalMs = 0, go?: string, preparingHoldMs = 0) {+function writer(source: string, slugs: string[], intervalMs = 0, go?: string, preparingHoldMs = 0, ready?: string) {const out = join(home, `worker-${randomUUID()}.json`);const child = Bun.spawn([process.execPath, join(import.meta.dir, 'fixtures', 'foreground-put-page-worker.ts')], { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',env: { ...process.env, GBRAIN_HOME: home, WORKER_DATABASE_URL: databaseUrl, WORKER_SOURCE: source, WORKER_SLUGS: slugs.join(',') || '-', WORKER_INTERVAL_MS: String(intervalMs), WORKER_OUT: out, ...(go ? { WORKER_GO: go } : {}),- ...(preparingHoldMs ? { WORKER_PREPARING_HOLD_MS: String(preparingHoldMs) } : {}) } });+ ...(preparingHoldMs ? { WORKER_PREPARING_HOLD_MS: String(preparingHoldMs) } : {}), ...(ready ? { WORKER_READY: ready } : {}) } });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)}`);@@ -233,9 +233,15 @@ test('a stream of writes from another process still lets the drain publish a groif (!engine) return;resetWriteSwitches();const e = engine, source = await fixture(e, 64);+ // The writer process boots and connects before the drain starts, so its first write follows the drain's first+ // group commit at once: the drain publishes the 16 groups in well under a second, less than a cold process start.+ const go = join(home, `go-${randomUUID()}`), ready = join(home, `ready-${randomUUID()}`);+ const finish = writer(source, [], 0, go, 0, ready);+ await until(async () => existsSync(ready));const drain = performSync(e, { sourceId: source, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 2 });await until(async () => (await rows(e, source)).some(row => row.state === 'committed' && row.kind === 'managed_sync_import'));- const written = await writer(source, Array.from({ length: 12 }, (_, i) => `notes/stream-${i}`))();+ writeFileSync(go, Array.from({ length: 12 }, (_, i) => `notes/stream-${i}`).join(','));+ const written = await finish();const result = await drain;expect(written.map(write => write.state)).toEqual(written.map(() => 'committed'));expect(result.status).toBe('first_sync');