Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(e2e): coalescing-5530 runs in a third of the time; a waiter that missed its consumer handoff reads at once
garrytanb3f096f9cbd3
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 3e524a2769..c60f709db2 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -29,9 +29,22 @@ const services = new WeakMap<BrainEngine, Service>();type ProgressRead = { row: WriteRequestProgress | null } | { error: unknown } | { cancelled: true };const receiptReads = new WeakMap<BrainEngine, Map<string, { read: Promise<ProgressRead>; abort: AbortController }>>();const settledWaiters = new WeakMap<BrainEngine, Map<string, Set<(row: WriteRequest) => void>>>();+/**+ * Requests this process's consumer settled most recently. A waiter that registers after its write already+ * settled (a caller that admits a window, then waits on each in turn) missed the handoff, so it reads at once+ * instead of sleeping through the first poll.+ */+const recentlySettled = new WeakMap<BrainEngine, Set<string>>();+const RECENTLY_SETTLED_IDS = 1024;/** #6007: when this process last settled requests, for pending retry_after_ms estimates. */const settlements = new WeakMap<BrainEngine, number[]>();const SETTLEMENT_SAMPLES = 21;+function rememberSettled(engine: BrainEngine, id: string): void {+ let ids = recentlySettled.get(engine);+ if (!ids) { ids = new Set(); recentlySettled.set(engine, ids); }+ ids.add(id);+ if (ids.size > RECENTLY_SETTLED_IDS) ids.delete(ids.values().next().value!);+}function recordSettlement(engine: BrainEngine): void {let times = settlements.get(engine);if (!times) { times = []; settlements.set(engine, times); }@@ -106,7 +119,7 @@ export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfreturn prior.consumer;}const full = () => new PersistenceConsumer(engine, config, preparePersistedMutation,- { onSettled: row => { recordSettlement(engine); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });+ { onSettled: row => { recordSettlement(engine); rememberSettled(engine, row.id); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });const kind = claimOwnerKind();const service: Service = kind !== 'serve' && RESIDENT_CONSUMER_KINDS.includes(kind) && engine.kind === 'postgres'? { consumer: new WaiterOnlyConsumer(engine, config, full, { kind, hostId: localHostId(), pool: () => enginePoolStats(engine) }), stopping: false }@@ -184,7 +197,7 @@ export function assertPersistenceAccepting(engine: BrainEngine): void {/** DX-A3: pending heads that need intervention, not more waiting. */export const BLOCKED_WRITE_REASONS = ['recovery_required', 'owner_unavailable', 'unexpected_file_bytes', 'unexpected_staging_bytes'] as const;const FATAL_READ_REASONS: readonly PgAccessReason[] = ['auth_failed', 'permission_denied', 'tenant_not_found', 'db_missing', 'schema_missing', 'storage_corrupt'];-/** CEO-A7: the first poll waits this long (at most half the wait) for an in-process handoff; later polls back off from 50 to 250 ms. */+/** CEO-A7: the first poll waits this long (at most half the wait) for an in-process handoff, or not at all when this process already settled the request; later polls back off from 50 to 250 ms. */export const WRITE_POLL_START_MS = 200;export type WriteWait =| { kind: 'terminal' | 'pending'; row: WriteRequest }@@ -216,7 +229,7 @@ export async function awaitWrite(engine: BrainEngine, row: WriteRequest, config:consumer.wake(true);const waitMs = opts.waitMs ?? 5000;const deadline = performance.now() + waitMs;- const firstPoll = Math.min(WRITE_POLL_START_MS, waitMs / 2);+ const firstPoll = recentlySettled.get(engine)?.has(id) ? 0 : Math.min(WRITE_POLL_START_MS, waitMs / 2);let delay = firstPoll, failure: { error: unknown; attempts: number } | undefined;try {while (!service.stopping && !opts.signal?.aborted) {diff --git a/test/helpers/persistence-postgres.ts b/test/helpers/persistence-postgres.tsindex cc32e41933..b1da8095a1 100644--- a/test/helpers/persistence-postgres.ts+++ b/test/helpers/persistence-postgres.ts@@ -15,3 +15,27 @@ export async function isolatedPersistencePostgres(databaseUrl:string, connectiontry {await engine.connect({database_url:url.toString(),poolSize:connectionStyle==='module'?undefined:poolSize});await engine.initSchema();return{engine,databaseUrl:url.toString(),close};}catch(error){await close();throw error;}}++/**+ * One migrated template per test file: each clone (CREATE DATABASE ... TEMPLATE) is its own fresh brain,+ * so permanent receipt IDs never cross tests, without re-running every migration per test.+ */+export async function persistencePostgresTemplate(databaseUrl:string, poolSize=4):Promise<{clone:()=>Promise<{engine:PostgresEngine;close:()=>Promise<void>}>;dispose:()=>Promise<void>}> {+ const template=await isolatedPersistencePostgres(databaseUrl);+ await template.engine.disconnect();+ const name=new URL(template.databaseUrl).pathname.slice(1);+ const admin=postgres(databaseUrl,{max:1,prepare:false});+ let clones=0;+ return {+ clone:async()=>{+ const database=`${name}_${clones++}`;+ await admin.unsafe(`CREATE DATABASE ${database} TEMPLATE ${name}`);+ const url=new URL(databaseUrl);url.pathname=`/${database}`;+ const engine=new PostgresEngine();+ const close=async()=>{await engine.disconnect();await admin.unsafe(`DROP DATABASE ${database} WITH (FORCE)`);};+ try {await engine.connect({database_url:url.toString(),poolSize});return{engine,close};}+ catch(error){await close();throw error;}+ },+ dispose:async()=>{await admin.end();await template.close();},+ };+}diff --git a/test/persistence-consumer-scheduling.test.ts b/test/persistence-consumer-scheduling.test.tsindex ae6dd01103..a5bc78159f 100644--- a/test/persistence-consumer-scheduling.test.ts+++ b/test/persistence-consumer-scheduling.test.ts@@ -14,7 +14,7 @@ import { acquireWorktree } from '../src/core/persistence/ownership.ts';import { admission, assertCommittedSnapshot, assertConservation, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';import { withEnv } from './helpers/with-env.ts';import { waitFor } from './helpers/wait-for.ts';-import { awaitWrite, disposePersistenceConsumer, registerMutationPreparer, startPersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';+import { awaitWrite, disposePersistenceConsumer, registerMutationPreparer, startPersistenceConsumer, waitForWrite, WRITE_POLL_START_MS } from '../src/core/persistence/service.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-consumer-scheduling-'));const config: HarnessConfig = {@@ -885,6 +885,28 @@ test('a write this process publishes resolves from the consumer handoff with zer} finally { await disposePersistenceConsumer(proxy); }}), 15_000);+test('a waiter that registers after this process settled its write reads at once instead of sleeping through the first poll', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ registerMutationPreparer('test_wait_settled_first', async (_e, row) => prepared(row, sources));+ let firstRead: number | undefined;+ const { proxy } = countingProxy(engine, sql => { if (sql === WRITE_PROGRESS_SQL) firstRead ??= performance.now(); });+ const consumer = startPersistenceConsumer(proxy, { engine: 'pglite' });+ try {+ // Settled before anyone waits, as when a caller admits a window of writes and then waits on each in turn.+ const row = await admitWrite(engine, admission(config, sources[0], 'wait-settled-first', 'settled body', 0, { operation: 'test_wait_settled_first' }));+ consumer.wake(true);+ await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'committed', { timeoutMs: 10_000, label: 'consumer settles the write' });+ // Only the waiter runs from here: the wait's own consumer wake must not occupy the event loop.+ (consumer as unknown as { doTick(): Promise<void> }).doTick = async () => {};+ firstRead = undefined;+ const started = performance.now();+ const waited = await awaitWrite(proxy, row, { engine: 'pglite' }, { waitMs: 10_000 });+ expect(waited.kind).toBe('terminal');+ expect(waited.row.state).toBe('committed');+ expect(firstRead! - started).toBeLessThan(WRITE_POLL_START_MS);+ } finally { await disposePersistenceConsumer(proxy); }+}), 15_000);+test('a write another consumer publishes resolves through progress polling with the full terminal row', async () => withEnv(env, async () => {const sources = await fixtures(engine, config);const row = await admitWrite(engine, admission(config, sources[0], 'wait-cross-process', 'cross body'));diff --git a/test/persistence-git-coalescing-5530.slow.test.ts b/test/persistence-git-coalescing-5530.slow.test.tsindex f1ada9e25f..6d8af7eedb 100644--- a/test/persistence-git-coalescing-5530.slow.test.ts+++ b/test/persistence-git-coalescing-5530.slow.test.ts@@ -16,8 +16,8 @@** PGLite here; Postgres through test/e2e/persistence-git-coalescing-5530-postgres.test.ts.*/-import { describe, expect, test } from 'bun:test';-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { afterAll, describe, expect, test } from 'bun:test';+import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { randomUUID } from 'node:crypto';@@ -33,6 +33,7 @@ import { runPersistenceEffects } from '../src/core/persistence/effects.ts';import { localHostId } from '../src/core/persistence/identity.ts';import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { persistencePostgresTemplate } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';@@ -46,8 +47,13 @@ function git(root: string, ...args: string[]): string {interface Repo { root: string; remote: string; pushes: () => number; rejectPushes: (on: boolean) => void; commits: () => number }-function makeRepo(home: string, name: string): Repo {- const root = join(home, name), remote = join(home, `${name}.git`), log = join(home, `${name}.pushes`), reject = join(home, `${name}.reject`);+// Each repository shape is built once per file and copied per test: a fresh repository costs ten+// git processes, and under CPU contention process startup dominated every test that made one.+let repoTemplates: string | undefined;+function repoTemplate(name: string): string {+ repoTemplates ??= realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-coalesce-5530-repos-')));+ const root = join(repoTemplates, name), remote = join(repoTemplates, `${name}.git`);+ if (existsSync(remote)) return repoTemplates;mkdirSync(root); mkdirSync(remote);git(root, 'init', '-q', '-b', 'main');git(root, 'config', 'user.name', 'Example Writer');@@ -56,6 +62,15 @@ function makeRepo(home: string, name: string): Repo {git(root, 'add', 'README.md'); git(root, 'commit', '-q', '-m', 'Initial');git(remote, 'init', '-q', '--bare');git(root, 'remote', 'add', 'origin', remote); git(root, 'push', '-q', '-u', 'origin', 'main');+ return repoTemplates;+}++function makeRepo(home: string, name: string): Repo {+ const root = join(home, name), remote = join(home, `${name}.git`), log = join(home, `${name}.pushes`), reject = join(home, `${name}.reject`);+ const template = repoTemplate(name);+ cpSync(join(template, name), root, { recursive: true });+ cpSync(join(template, `${name}.git`), remote, { recursive: true });+ git(root, 'remote', 'set-url', 'origin', remote);const preReceive = join(remote, 'hooks', 'pre-receive');writeFileSync(preReceive, `#!/bin/sh\necho push >> '${log}'\n[ -f '${reject}' ] && exit 1\nexit 0\n`);chmodSync(preReceive, 0o755);@@ -76,11 +91,20 @@ function harden(repo: Repo): void {const pageContent = (i: number, note = '') => `---\ntype: note\ntitle: Page ${i}\n---\n\nCoalescing page ${i}.${note}\n`;+// PostgreSQL brains are clones of one migrated template database rather than a full migration run per test.+let pgTemplate: ReturnType<typeof persistencePostgresTemplate> | undefined;+afterAll(async () => {+ await (await pgTemplate)?.dispose();+ if (repoTemplates) rmSync(repoTemplates, { recursive: true, force: true });+});+async function withBrain(kind: 'pglite' | 'postgres', run: (b: { engine: BrainEngine; home: string; ctx: (source: string) => OperationContext }) => Promise<void>) {const home = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-coalesce-5530-')));try {await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {- const { engine, close } = await isolatedSharedSkillsEngine(kind === 'postgres' ? process.env.GBRAIN_TEST_COALESCE_PG! : undefined);+ const { engine, close } = kind === 'postgres'+ ? await (pgTemplate ??= persistencePostgresTemplate(process.env.GBRAIN_TEST_COALESCE_PG!)).then(template => template.clone())+ : await isolatedSharedSkillsEngine();try {const ctx = (source: string) => ({ engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: source,remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } }) as OperationContext;@@ -126,12 +150,11 @@ for (const kind of testBackends()) describe(`#5530 Git effect coalescing (${kindconst repo = makeRepo(home, 'content');await bindSource(engine, 'default', repo);await activateSharedSkillPersistence(engine, { confirmQuiesced: true });- await seed(ctx('default'), PAGES - 1);- await disposePersistenceConsumer(engine);- // A seed write's Git effect can still be queued here, backed off after a- // writer-busy attempt while the consumer was publishing; apply it now so- // only the grandfather's and the interleaved write's effects are pending- // below.+ // The seed's own Git effects are setup, not under test: hold them while+ // seeding (the consumer would otherwise probe the worktree once per page)+ // and apply them all here, before hardening, so only the grandfather's and+ // the interleaved write's effects are pending below.+ await pauseGitEffects(engine, () => seed(ctx('default'), PAGES - 1));for (let i = 0; (await gitStates(engine)).queued && i < 50; i++) { await release(engine); await pass(engine); }expect((await gitStates(engine)).queued).toBeUndefined();harden(repo);