Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: five CI flakes, each root-caused with a forced probe (A-2 re-ingest screen, db-lock release after reconnect, three test races)
garrytan741bf3f62441
diff --git a/docs/architecture/key-files/engines-1.md b/docs/architecture/key-files/engines-1.mdindex 0da51cdc63..2a92fe17b3 100644--- a/docs/architecture/key-files/engines-1.md+++ b/docs/architecture/key-files/engines-1.md@@ -8,7 +8,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/connection-manager.ts` — routes ordinary and direct Postgres pools. Supabase-shaped URLs retain automatic derivation; a valid explicit `GBRAIN_DIRECT_DATABASE_URL` or constructor override also enables dual routing for generic Postgres and PgBouncer on custom ports. The kill switch and inherited parent route stay authoritative. `describeMode()` reports the same route used by `ddl()` and `bulk()`. Regression coverage: `test/connection-manager.serial.test.ts` and the real 24-case persistence runtime matrix.-- `src/core/db-lock.ts` + `lease-schema.ts` — row leases survive transaction-mode PgBouncer. Migration 152 gives every `gbrain_cycle_locks` acquisition a UUID; refresh/release, takeover/reaper and manual/age-gated breaks match (id, holder_pid, acquisition_token), never the `acquired_at` epoch text, which is diagnostics only (#6028). `withRefreshingLock` always passes an aborting work signal, rejects results after ownership loss/TTL expiry, tracks a single actual renewal through timeout cancellation, and drains late completion before release. Renewal deadlines start before the database round trip. `performSync` composes this signal with caller cancellation. `inspectLock`, `listStaleLocks`, `listLiveLocks`, `classifyHolderLiveness` and namespace-scoped `reapDeadHolderLocks` keep their status/recovery contracts. Tests: `test/db-lock-concurrency.test.ts`, `test/db-lock-token-predicate.test.ts`, `test/e2e/db-lock-acquisition-token.test.ts`, fencing/reaper/inspection suites.+- `src/core/db-lock.ts` + `lease-schema.ts` — row leases survive transaction-mode PgBouncer. Migration 152 gives every `gbrain_cycle_locks` acquisition a UUID; refresh/release, takeover/reaper and manual/age-gated breaks match (id, holder_pid, acquisition_token), never the `acquired_at` epoch text, which is diagnostics only (#6028). `withRefreshingLock` always passes an aborting work signal, rejects results after ownership loss/TTL expiry, tracks a single actual renewal through timeout cancellation, and drains late completion before release. Release uses the live pool, surviving `engine.reconnect()`. Renewal deadlines start before the database round trip. `performSync` composes this signal with caller cancellation. `inspectLock`, `listStaleLocks`, `listLiveLocks`, `classifyHolderLiveness` and namespace-scoped `reapDeadHolderLocks` keep their status/recovery contracts. Tests: `test/db-lock-concurrency.test.ts`, `test/db-lock-token-predicate.test.ts`, `test/e2e/db-lock-acquisition-token.test.ts`, fencing/reaper/inspection suites.- `src/core/db-repair-receipts.ts` — the shared seam between `gbrain db-repair` (writer) and doctor's `db_repair_recurrence` check (reader — it must run in doctor's dead-DB filesystem lane, exactly when repairs are repeating). JSONL at `~/.gbrain/db-repair-receipts.jsonl`; row shape `{ts, brain_id, reason, action, outcome: 'applied'|'refused'|'diagnose'}` — only `applied` rows count toward the recurrence threshold (3+ same-reason per brain in 7 days). Redacted before write (the classifier redacts its own copy; actions are fixed strings), fail-open (a receipts problem never blocks a repair), capped at 200 rows ON EVERY WRITE (the recurrence check reads the file on every doctor run — it must not grow unbounded on exactly the machines having chronic problems) — EXCEPT `applied` rows inside an 8-day retention window, which are exempt from the flat cap (separately bounded at 200): a diagnose flood from an agent loop must never evict the cooldown/recurrence memory. The reader is per-line tolerant (one torn row never discards every other receipt). Also owns `rewriteCooldownBlocked` (24h per (reason, action), rewrite tier only).diff --git a/src/core/db-lock.ts b/src/core/db-lock.tsindex 01aff105ad..a5fda12fbf 100644--- a/src/core/db-lock.ts+++ b/src/core/db-lock.ts@@ -205,6 +205,13 @@ export function isLockHolderLive(snap: LockSnapshot, ttlMinutes: number = DEFAUL* Empty RETURNING means the existing row is still live. An expired holder* (worker crashed without releasing) is auto-superseded by the UPDATE* branch.+ *+ * On Postgres the handle's release and exit cleanup run on the engine's pool as+ * it is when they run, never the pool the acquire used: `engine.reconnect()`+ * ends that pool while the lock is held (a write admission that lost its+ * connection rebuilds it), and a statement on an ended pool fails+ * `CONNECTION_ENDED`, which turned a finished sync into a thrown error and left+ * its lock row behind until the TTL lapsed.*/export async function tryAcquireDbLock(engine: BrainEngine,@@ -264,7 +271,7 @@ export async function tryAcquireDbLock(// is lost) and is never compared (#6028).const fence = rows[0].fence;const deregister = registerCleanup(`db-lock:${lockId}`, async () => {- await sql`+ await (maybePG.sql as any)`DELETE FROM gbrain_cycle_locksWHERE id = ${lockId} AND holder_pid = ${pid} AND acquisition_token = ${acquisitionToken}::uuid`;@@ -291,7 +298,7 @@ export async function tryAcquireDbLock(},release: async () => {deregister();- await sql`+ await (maybePG.sql as any)`DELETE FROM gbrain_cycle_locksWHERE id = ${lockId} AND holder_pid = ${pid} AND acquisition_token = ${acquisitionToken}::uuid`;diff --git a/src/core/persistence/put-page-screen.ts b/src/core/persistence/put-page-screen.tsindex fa714f83b4..7421d275fa 100644--- a/src/core/persistence/put-page-screen.ts+++ b/src/core/persistence/put-page-screen.ts@@ -15,7 +15,10 @@* kernel waiver applies; a missing file always admits. The preparer's own* `validate` must hold. Anything else is submitted as before:* - a page with a request still pending or recovering (the stored page is- * not yet what that request will publish);+ * not yet what that request will publish). A request that has ended holds+ * nothing here even while its recovery record awaits the post-commit+ * staging cleanup (a waiter learns of the commit first): its canonical+ * file and page are final;* - a segmented (large) page: its publication decides the no-op;* - a missing, deleted or changed page, or any failure of the screen.*/@@ -33,7 +36,7 @@ export async function unchangedPutPage(ctx: OperationContext, params: Record<strif (!snapshot || snapshot.page.deleted_at || isSegmentedPage(snapshot.page)) return false;try {const [pending] = await ctx.engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND intent IS NOT NULL AND NOT compacted- AND (state NOT IN ('committed','conflict','failed','cancelled') OR recovery IS NOT NULL) LIMIT 1`, [params.source_id, params.slug.toLowerCase()]);+ AND state NOT IN ('committed','conflict','failed','cancelled') LIMIT 1`, [params.source_id, params.slug.toLowerCase()]);if (pending) return false;const prepared = await preparePageAdmission(ctx, { operation: 'put_page', params });if (prepared.prior) return false;diff --git a/test/belief-ledger-coverage.test.ts b/test/belief-ledger-coverage.test.tsindex d8fc6c7808..2a88827d84 100644--- a/test/belief-ledger-coverage.test.ts+++ b/test/belief-ledger-coverage.test.ts@@ -13,6 +13,7 @@ import { __setBeliefEmitterFaultForTests, markBeliefCommits, type BeliefEventDraimport { currentStateHash, readLedgerSource, withBeliefBatch } from '../src/core/belief/ledger.ts';import { deleteSourceRow } from '../src/core/source-delete.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { enableBeliefLedger, disableBeliefLedger, latestCoverage } from '../src/core/belief/coverage.ts';import { renamePageOntoSlug } from '../src/commands/sync/rename-collision.ts';import { runBeliefs } from '../src/commands/beliefs.ts';@@ -342,6 +343,7 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {await seeded(b);const old = (await readLedgerSource(b.engine, b.sourceId))!;const oldEvents = await b.events();+ await disposePersistenceConsumer(b.engine);expect(await deleteSourceRow(b.engine, b.sourceId)).toBe(true);await b.engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [b.sourceId, b.root]);rmSync(join(b.root, 'companies'), { recursive: true, force: true });diff --git a/test/db-lock-reconnect.test.ts b/test/db-lock-reconnect.test.tsnew file mode 100644index 0000000000..71e51b3f57--- /dev/null+++ b/test/db-lock-reconnect.test.ts@@ -0,0 +1,62 @@+/**+ * A lock held across `engine.reconnect()` still releases its own row.+ *+ * A write admission that loses its connection rebuilds the engine's pool (`retryWriteAdmission` calls+ * `engine.reconnect`), and the rebuild ends the pool the lock was acquired on. The handle's release ran its DELETE on+ * that ended pool, so `withRefreshingLock` threw `CONNECTION_ENDED` after the work finished and the row stayed until+ * its TTL lapsed (test/managed-sync-connection-loss.test.ts failed this way when an admit-ahead admission landed inside+ * the simulated pooler drop).+ *+ * Runs on PGLite and, with DATABASE_URL, on Postgres.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { tryAcquireDbLock, withRefreshingLock } from '../src/core/db-lock.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const engines: Array<{ engine: BrainEngine; close: () => Promise<void> }> = [];+const connectionClosed = () => Object.assign(new Error('write CONNECTION_CLOSED 127.0.0.1:6543'), { code: 'CONNECTION_CLOSED' });++beforeAll(async () => {+ for (const backend of testBackends()) {+ if (backend === 'pglite') {+ const engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+ engines.push({ engine, close: () => engine.disconnect() });+ } else {+ engines.push(await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ }+ }+}, 120_000);++afterAll(async () => {+ for (const e of engines) await e.close();+});++const lockRow = async (engine: BrainEngine, id: string) =>+ (await engine.executeRaw('SELECT acquisition_token::text AS token FROM gbrain_cycle_locks WHERE id = $1', [id]))[0] ?? null;++test('release after a reconnect deletes the lock row on the live pool', async () => {+ for (const { engine } of engines) {+ const handle = await tryAcquireDbLock(engine, 'test-reconnect-release', 5);+ expect(handle).not.toBeNull();+ await engine.reconnect({ error: connectionClosed() });+ expect(await handle!.refresh()).toBe(true);+ await handle!.release();+ expect(await lockRow(engine, 'test-reconnect-release')).toBeNull();+ }+});++test('withRefreshingLock returns the work result when the pool is rebuilt mid-hold', async () => {+ for (const { engine } of engines) {+ const result = await withRefreshingLock(engine, 'test-reconnect-hold', async () => {+ await engine.reconnect({ error: connectionClosed() });+ return 'done';+ });+ expect(result).toBe('done');+ expect(await lockRow(engine, 'test-reconnect-hold')).toBeNull();+ }+});diff --git a/test/pathological/a2-transcripts-ingest.test.ts b/test/pathological/a2-transcripts-ingest.test.tsindex 5f1dcd456f..409b847369 100644--- a/test/pathological/a2-transcripts-ingest.test.ts+++ b/test/pathological/a2-transcripts-ingest.test.ts@@ -8,9 +8,10 @@* a rerun waits on that write instead of admitting a duplicate; a pending* write that ends without committing is re-queued; a page deleted and* retention-purged since its write is created again instead of answered- * with the old committed receipt, while an owner purge still refuses it- * purged_content; the connector watermark never passes a pending or- * failed conversation.+ * with the old committed receipt (an identical rerun then admits nothing,+ * even before that write's recovery record is cleared), while an owner+ * purge still refuses it purged_content; the connector watermark never+ * passes a pending or failed conversation.* 2. Regression: the per-part catch treating anything but /too large|invalid* byte sequence/ as a run abort, a random request id per run, or a* committed receipt replayed for a page that no longer exists.@@ -32,6 +33,7 @@ import { connectorSourceKey } from '../../src/core/connectors/config-keys.ts';import { CHATGPT_BASE_URL } from '../../src/core/connectors/providers/chatgpt.ts';import { waitForWrites } from '../../src/core/persistence/service.ts';import { purgeDeletedPagesCoordinated } from '../../src/core/persistence/purge-deleted.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';import { operations } from '../../src/core/operations.ts';import type { WriteRequest } from '../../src/core/persistence/model.ts';import { chatgptHandler, newFixtureState, startFixture, type FixtureConversation, type FixtureState } from '../fixtures/connectors/fixture-server.ts';@@ -147,6 +149,49 @@ for (const { backend, databaseUrl } of pathologicalArms()) {expect((await putPageRequests(engine)).length).toBe(2);}, { databaseUrl }), 180_000);+ // Postgres publishes a single write as a group of one and hands the waiter its commit before clearing the recovery record.+ if (backend === 'postgres') test('recovery: a rerun while the re-created write is committed but its recovery record is not yet cleared still admits nothing', async () => managedBrain(async ({ engine, ctx, root }) => {+ const path = exportFile(root, { 'c-1': 'one' });+ await ingest(engine, ctx, path);+ const { slug } = await slugOf(engine, 'c-1');+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ await operations.find(op => op.name === 'delete_page')!.handler(ctx, { slug, expected_revision: snapshot!.revision, request_id: crypto.randomUUID() });+ expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).toEqual([slug]);+ // The re-creation's request row is held from its commit, so the post-commit recovery clear waits until the rerun has screened.+ let release!: () => void;+ const released = new Promise<void>(resolve => { release = resolve; });+ let held: Promise<unknown> | undefined;+ const executeRaw = engine.executeRaw;+ try {+ installFaultHook(async (point, detail) => {+ if (point !== 'publication:after_commit' || detail.operation !== 'put_page' || held) return;+ let locked!: () => void;+ const acquired = new Promise<void>(resolve => { locked = resolve; });+ held = engine.transaction(async tx => {+ await tx.executeRaw('SELECT 1 FROM persistence_requests WHERE request_id=$1::uuid FOR UPDATE', [detail.requestId]);+ locked();+ await released;+ });+ await acquired;+ });+ await ingest(engine, ctx, path);+ expect((await putPageRequests(engine)).map(row => [row.state, row.recovery !== null])).toEqual([['committed', false], ['committed', true]]);+ engine.executeRaw = (async function (this: BrainEngine, ...args: Parameters<BrainEngine['executeRaw']>) {+ const rows = await executeRaw.apply(this, args);+ if (args[0].includes('intent IS NOT NULL AND NOT compacted')) release();+ return rows;+ }) as BrainEngine['executeRaw'];+ const rerun = await ingest(engine, ctx, path);+ expect(rerun).toMatchObject({ sessionsImported: 1, sessionsErrored: 0, pages: { imported: 0, skipped: 1 } });+ expect((await putPageRequests(engine)).length).toBe(2);+ } finally {+ engine.executeRaw = executeRaw;+ installFaultHook(undefined);+ release();+ await held;+ }+ }, { databaseUrl }), 180_000);+test('item: an identical re-ingest after the owner purged the page is refused purged_content, never replayed or re-created', async () => managedBrain(async ({ engine, ctx, root }) => {const path = exportFile(root, { 'c-1': 'one' });await ingest(engine, ctx, path);diff --git a/test/persistence-memory-mutations.test.ts b/test/persistence-memory-mutations.test.tsindex c011b4498a..bcb5aa3ce8 100644--- a/test/persistence-memory-mutations.test.ts+++ b/test/persistence-memory-mutations.test.ts@@ -68,6 +68,7 @@ describe('journaled memory publication, both engines', () => {visibility: 'world', fence: true, valid_from: new Date().toISOString(), valid_until: null };const row = await admitWrite(engine, { principal: authority.principal, operation: 'remember', sourceId,sourceIncarnation: snapshot.sourceIncarnation, slug, pageId: snapshot.page.id, callerIntent: intent, intent, authority, requestId: randomUUID() });+ let entered = false;let aborted = false;const release = Promise.withResolvers<void>();const provider = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch: async () => {@@ -76,13 +77,26 @@ describe('journaled memory publication, both engines', () => {} });configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: { OPENAI_API_KEY: 'sk-test' } });__setEmbedTransportForTests(async options => {+ entered = true;try { return await (await fetch(provider.url, { signal: options.abortSignal })).json() as never; }catch (error) { aborted = options.abortSignal!.aborted; throw error; }});- const consumer = new PersistenceConsumer(engine, context(engine).config, prepareMemoryMutation, { pollMs: 60000, preparationMs: 50 });+ // The 50 ms budget is wall-clock from the claim, so on a loaded machine it can pass before the preparer reaches the+ // provider; the provider abort is pinned on a signal aborted once the call is in flight, the budget on the consumer's own signal.+ const cancel = new AbortController();+ let preparation: Promise<unknown> | undefined;+ const consumer = new PersistenceConsumer(engine, context(engine).config,+ (e, current, config, signal) => preparation = prepareMemoryMutation(e, current, config, signal), { pollMs: 60000, preparationMs: 50 });try {+ const direct = prepareMemoryMutation(engine, row, context(engine).config, cancel.signal);+ await waitFor(() => entered);+ cancel.abort({ code: 'preparation_deadline' });+ await expect(direct).rejects.toEqual({ code: 'preparation_deadline' });+ expect(aborted).toBe(true);consumer.start();- await waitFor(() => aborted && consumer.status().active_preparations === 0);+ await waitFor(() => preparation !== undefined);+ await expect(preparation).rejects.toEqual({ code: 'preparation_deadline' });+ await waitFor(() => consumer.status().active_preparations === 0);expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');expect(await engine.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND fact=$2', [sourceId, intent.fact])).toHaveLength(0);} finally { release.resolve(); provider.stop(true); await consumer.stop(); __setEmbedTransportForTests(null); configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} }); }diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 15d79af331..5765b36516 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -44,6 +44,7 @@ test/company-brain-runtime.test.tstest/consolidate-same-instant-6023.test.tstest/conversation-facts-oversized-sidecar.test.tstest/cycle/synthesize-concepts-merge.test.ts+test/db-lock-reconnect.test.tstest/decide/conflict-proposals-managed.test.tstest/declared-lineage-visibility.test.tstest/derived-link-reconciliation.test.tsdiff --git a/test/worker-shutdown-error-matrix.test.ts b/test/worker-shutdown-error-matrix.test.tsindex c1b6703dc9..26c6f2ede4 100644--- a/test/worker-shutdown-error-matrix.test.ts+++ b/test/worker-shutdown-error-matrix.test.ts@@ -46,7 +46,12 @@ const ERRORS: Record<string, (ctx: MinionJobContext) => unknown> = {type WorkerInternals = { queue: MinionQueue; inFlight: Map<number, unknown>; gracefulShutdown(reason: string): void };-/** `holdClaimResult`: park the committed claim's result until the trigger has fired, so the trigger lands before launchJob. */+/**+ * Without `holdClaimResult` the trigger fires once the handler is running: a+ * row already `active` in the database may still be in the claim round trip,+ * where the watchdog would see a late claim instead of a job running alone.+ * `holdClaimResult`: park the committed claim's result until the trigger has fired, so the trigger lands before launchJob.+ */async function runCase(engine: BrainEngine, trigger: Trigger, kind: keyof typeof ERRORS, holdClaimResult = false) {const queue = new MinionQueue(engine);const worker = new MinionWorker(engine, { pollInterval: 10, lockDuration: 60_000, healthCheckInterval: 0, stalledInterval: 600_000 });@@ -54,7 +59,9 @@ async function runCase(engine: BrainEngine, trigger: Trigger, kind: keyof typeoflet release!: () => void;const gate = new Promise<void>(resolve => { release = resolve; });const name = `matrix-${trigger}-${kind}${holdClaimResult ? '-held' : ''}`;- worker.register(name, async (ctx) => { await gate; throw ERRORS[kind]!(ctx); });+ let handlerStarted!: () => void;+ const started = new Promise<void>(resolve => { handlerStarted = resolve; });+ worker.register(name, async (ctx) => { handlerStarted(); await gate; throw ERRORS[kind]!(ctx); });const job = await queue.add(name, {}, { max_attempts: 3 }, { allowProtectedSubmit: true });let releaseClaim = () => {};let claimCommitted: Promise<void> | null = null;@@ -75,7 +82,7 @@ async function runCase(engine: BrainEngine, trigger: Trigger, kind: keyof typeofexpect((await queue.getJob(job.id))?.status).toBe('active');expect(internals.inFlight.size).toBe(0);} else {- for (let i = 0; i < 400 && (await queue.getJob(job.id))?.status !== 'active'; i++) await Bun.sleep(10);+ await started;}if (trigger === 'requestShutdown') worker.requestShutdown();else if (trigger === 'watchdog') internals.gracefulShutdown('watchdog');