Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): PGLite maintenance and drain passes yield to due timers between steps (master red: drain latency)

garrytan2da889b6667a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cf769a518c..bb21d011d1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,30 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased] - 2026-10-17
+
+**A PGLite brain that is draining a large effects backlog answers requests sooner, and master CI is green again.** When the write owner starts on a backlog of queued embedding effects, its first tick ran the receipt compaction pass, the reservation sweep and the queue `VACUUM` back to back next to the drain, and each drain pass held the event loop for its whole reservation true-up. PGLite statements run synchronously, so a request (or a timer) waited behind all of it: about 0.3 s on a fast machine and 2.2 s on a slow CI runner, which failed `test/persistence-drain-latency.serial.test.ts` on master. Now each of those steps returns to the event loop before the next one, and a request waits behind one step at most.
+
+### What you'd see
+
+| Situation | Before | Now |
+|---|---|---|
+| longest wait for a tool call while 8,000 no-op embedding effects drain (local PGLite) | 290 to 380 ms | 86 to 120 ms |
+| the same on a host about as slow as the CI runner that failed (statements slowed 4.5x) | 1.9 to 2.1 s (over the 2 s bound in 2 of 3 runs) | 1.0 to 1.2 s |
+| time to drain that backlog (local) | about 2.8 s | about 3.5 s |
+
+### What to do
+
+Nothing. Nothing is rewritten on upgrade and there is no migration. Postgres brains are unaffected apart from the smaller settle batch.
+
+### Itemized changes
+
+- `src/core/persistence/journal.ts`: new `yieldToEventLoop`, which resumes from the timer queue so a timer that came due during the last statement chain runs before the next chain. The consumer's effects drain uses it between passes (it used `setImmediate`, which ran the next pass ahead of due timers). `vacuumPersistenceQueues` vacuums each grown queue table in its own statement with a yield before each.
+- `src/core/persistence/compaction-pass.ts` and `src/core/persistence/consumer.ts`: the compaction pass yields after compacting and after the reservation sweep step, and the consumer's maintenance chains yield between the compaction pass, the segment sweep, the queue vacuum and the planner statistics refresh.
+- `src/core/persistence/embedding-noop-settle.ts`: `NOOP_SETTLE_BATCH` is 50 (was 200), because one pass and its reservation true-up hold the event loop on PGLite.
+- `DRAIN_ANSWER_BOUND_MS` and every assertion of the drain latency test are unchanged.
+- New `test/persistence-maintenance-yield.test.ts`: the queue `VACUUM` runs in a later event-loop turn than the size check, the compaction pass, the sweep and the pass record each run in their own turn, and a yield resumes after a timer that came due before it. All three fail on the previous code.
+
## [0.60.280.0] - 2026-10-17
**A managed brain can now make a commit searchable in seconds, and every managed source reports how long that takes.** Until now a commit reached search only when the next scheduled sync ran, which on a managed brain could be most of an hour. Turn on `sync.on_commit` and `gbrain serve` notices the commit within about 3 seconds, waits 3 more for the commit burst to settle, and runs one managed sync for that source. The setting is off by default, so nothing changes until you turn it on.
diff --git a/docs/architecture/key-files/core-persistence-capacity.md b/docs/architecture/key-files/core-persistence-capacity.md
index 448542b3ed..091fd7d1cd 100644
--- a/docs/architecture/key-files/core-persistence-capacity.md
+++ b/docs/architecture/key-files/core-persistence-capacity.md
@@ -8,7 +8,7 @@ Cumulative write caps (permanent request ids, receipt bytes) and the paths that
- `src/core/persistence/owner-verification.ts` — #6741 C: the claim's owner verification (`verifyOwnerRoot`: paths recorded, physical root, marker and reservation intact; a device-only change is `restampable`), shared by writer onboarding and background admissions; `assertBackgroundOwner` refuses a background admission `owner_unavailable` once per source per run (cache: admission-origin.ts `backgroundOwnerCheck`). Tests: `test/background-owner-verification.test.ts`.
- `src/core/persistence/capacity-forecast.ts` — `readCapacityForecast`: per principal, one statement walks `persistence_requests_principal` newest first until `created_at` leaves the 7-day window and buckets by day; gross and net (compacted) receipt rates, `days_to_exhaustion`, `basis` (`:legacy_under_reserved` while receipts admitted before the intent-sized reservation remain), `recommended_limit`. `light` skips the reclaim read and table size. Thresholds `persistence.capacity.warn_days` (30) and `fail_days` (7).
- `src/core/persistence/capacity-snapshot.ts` — `cachedCapacitySnapshot`: one light forecast per engine per 60 s, shared by every caller; `capacityNotices` builds `write_capacity_low` (kind `info`, muteable; hourly per process per scope on write and sync receipts, `scopes` limits a remote caller to the brain and its own principal) and `write_capacity_backpressure` (once per pause start). Read by `mcp/dispatch.ts`, `cli/main.ts`, `commands/sync/{run,operator}.ts`, `cycle.ts` and the admin `/metrics` gauges in `serve-http-metrics.ts`. #6803: the cache keys on the real engine (`engineCacheKey`), the shared fetch is bounded at `CAPACITY_FETCH_BOUND_MS` (10 s) and a timed-out fetch is never cached; `capacitySnapshotWithin` (sync status, write and sync receipts: `CAPACITY_READ_WAIT_MS`, 1.5 s) returns `unknown` for that call alone, and `capacityNotices` on an unknown snapshot returns no notice and leaves throttle and pause state as it was. Test: `test/capacity-bounded-read-6803.test.ts`.
-- `src/core/persistence/compaction-pass.ts` — `runCompactionPass`, the consumer's idle and volume maintenance: `compactWriteReceiptsDetailed`, one sweep step, and the `persistence.maintenance.last_compaction` record (`at`, `host_id`, `compacted`, `freed_bytes`, `skipped_by_reason`). `journal.ts` `compactReceipt` compacts one receipt in its own transaction (counters first, `lock_timeout` 2 s, `statement_timeout` 15 s) and skips open managed-sync runs (`OPEN_SYNC_CURSOR_EXCLUSION`) and the newest sync receipt per worktree (`newestSyncReceipt`).
+- `src/core/persistence/compaction-pass.ts` — `runCompactionPass`, the consumer's idle and volume maintenance: `compactWriteReceiptsDetailed`, one sweep step, and the `persistence.maintenance.last_compaction` record (`at`, `host_id`, `compacted`, `freed_bytes`, `skipped_by_reason`). Each step resumes from the timer queue (`journal.ts` `yieldToEventLoop`), as do the consumer's maintenance chain, the per-table queue `VACUUM` and the effects drain passes (`NOOP_SETTLE_BATCH` 50), so on PGLite a request waits behind one step at most. `journal.ts` `compactReceipt` compacts one receipt in its own transaction (counters first, `lock_timeout` 2 s, `statement_timeout` 15 s) and skips open managed-sync runs (`OPEN_SYNC_CURSOR_EXCLUSION`) and the newest sync receipt per worktree (`newestSyncReceipt`).
- `src/core/repair/receipt-compaction.ts` — `gbrain repair receipt-compaction`: explicit-only, preview-bound, destructive consent, `publication: 'projection'`; `--older-than` (the `pages purge-deleted` grammar) floored at the configured retention unless `--force`, committed only unless `--include-failures`; the approved set binds an absolute cutoff and the newest sequence. Test: `test/repair-receipt-compaction.test.ts`.
- `src/core/persistence/refusal-breaker.ts` — `assertRefusalBreakerClosed`: `submitMaintenance` refuses before admission after `persistence.maintenance.refusal_breaker_threshold` (3; 0 off) same-code terminal refusals in 24 h for the same request `digest` (source, slug, intent with its revision and planner); `listSuppressedWrites` feeds doctor `maintenance_write_drift`. The ghost case (`canonical_file_missing`, tagged by `page-prepare.ts`, kept in `error_detail.origin`, returned by `liveFileDrift`) refuses before admission in `prepared-maintenance.ts`. Test: `test/maintenance-ghost-breaker-6696.test.ts`.
- Sync: `sync-run.ts` `preflightSyncCapacity` refuses `write_quota_insufficient` before a run's first admission; `sync-drain.ts` stops a later cap refusal `resumable` / `capacity_paused` (`drain.capacity_pause`). Test: `test/sync-capacity-preflight.test.ts`.
diff --git a/src/core/persistence/compaction-pass.ts b/src/core/persistence/compaction-pass.ts
index 883590a768..6f9a4faef5 100644
--- a/src/core/persistence/compaction-pass.ts
+++ b/src/core/persistence/compaction-pass.ts
@@ -11,7 +11,7 @@
* phase=compaction` line on stderr when the owner is `serve`.
*/
import type { BrainEngine } from '../engine.ts';
-import { compactWriteReceiptsDetailed, type ReceiptCompactionResult } from './journal.ts';
+import { compactWriteReceiptsDetailed, yieldToEventLoop, type ReceiptCompactionResult } from './journal.ts';
import { sweepCompactedReservations } from './receipt-true-up.ts';
export const LAST_COMPACTION_KEY = 'persistence.maintenance.last_compaction';
@@ -24,7 +24,9 @@ const recordedAt = new WeakMap<object, number>();
export async function runCompactionPass(engine: BrainEngine, opts: { hostId: string; notice?: boolean; now?: number }): Promise<CompactionRecord> {
const result = await compactWriteReceiptsDetailed(engine);
+ await yieldToEventLoop();
const swept = await sweepCompactedReservations(engine);
+ await yieldToEventLoop();
const now = opts.now ?? Date.now();
const record: CompactionRecord = { at: new Date(now).toISOString(), host_id: opts.hostId, compacted: result.compacted,
freed_bytes: result.freed_bytes + swept.freed_bytes, skipped_by_reason: result.skipped_by_reason };
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 2fd854911e..3bc05957b6 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -1,6 +1,6 @@
import type { BrainEngine, ReservedConnection } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
-import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, syncGroup, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues, independentGroup, sweepSegmentStorage } from './journal.ts';
+import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, syncGroup, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues, independentGroup, sweepSegmentStorage, yieldToEventLoop } from './journal.ts';
import { finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, transientDatabaseFailure, type PreparedMutation } from './coordinator.ts';
import { localHostId } from './identity.ts';
import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';
@@ -59,7 +59,6 @@ const KEEP_DB_POLICY_INTERVAL_MS = 10 * 60_000;
const CONNECTION_LOSS_RELEASE_MS = 30_000;
/** #6650: how often a consumer looks for claims held by an owner it can prove dead. */
export const DEAD_OWNER_SCAN_MS = 5_000;
-const yieldToEventLoop = () => new Promise<void>(resolve => setImmediate(resolve));
/** When this process started; on PGLite no claim written earlier can belong to a live owner. */
const PROCESS_STARTED_AT = new Date(performance.timeOrigin);
/** #5801: the phase a connection checkout belongs to, carried through its async chain. */
@@ -523,7 +522,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,
this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));
// F4b: idle maintenance also refreshes stale PGLite planner statistics (a no-op on Postgres).
- this.maintenanceWorker = runCompactionPass(this.engine, { hostId: this.hostId, notice: this.opts.drainNotice }).then(() => maybeRefreshPlannerStats(this.engine, 'idle'))
+ this.maintenanceWorker = runCompactionPass(this.engine, { hostId: this.hostId, notice: this.opts.drainNotice }).then(yieldToEventLoop).then(() => maybeRefreshPlannerStats(this.engine, 'idle'))
.catch(error => this.report(error)).finally(() => { this.maintenanceWorker = undefined; });
}
if (this.opts.keepDbPolicy && !this.opts.requestsOnly && !this.keepDbWorker && Date.now() >= this.nextKeepDb) {
@@ -564,8 +563,9 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
if (!this.maintenanceWorker && (Date.now() >= this.nextMaintenance || this.publishedSinceMaintenance >= this.maintenanceVolume)) {
this.nextMaintenance = Date.now() + 60_000;
this.publishedSinceMaintenance = 0;
- this.maintenanceWorker = runCompactionPass(this.engine, { hostId: this.hostId, notice: this.opts.drainNotice }).then(() => sweepSegmentStorage(this.engine).catch(error => this.report(error)))
- .then(() => vacuumPersistenceQueues(this.engine))
+ this.maintenanceWorker = runCompactionPass(this.engine, { hostId: this.hostId, notice: this.opts.drainNotice })
+ .then(yieldToEventLoop).then(() => sweepSegmentStorage(this.engine).catch(error => this.report(error)))
+ .then(yieldToEventLoop).then(() => vacuumPersistenceQueues(this.engine))
.then(rows => { this.maintenanceVolume = 50 + Math.ceil(rows * 0.2); }).catch(error => this.report(error))
.finally(() => { this.maintenanceWorker = undefined; });
}
diff --git a/src/core/persistence/embedding-noop-settle.ts b/src/core/persistence/embedding-noop-settle.ts
index c9387a8b8b..578fdb06cd 100644
--- a/src/core/persistence/embedding-noop-settle.ts
+++ b/src/core/persistence/embedding-noop-settle.ts
@@ -33,8 +33,11 @@ import { faultPoint } from './fault-points.ts';
import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { refreshFenceClear } from './worktree-refresh-schema.ts';
-/** At most this many effects settle in one statement. */
-export const NOOP_SETTLE_BATCH = 200;
+/**
+ * At most this many effects settle in one statement. A pass and its reservation true-up hold the event loop on PGLite,
+ * so the batch bounds how long a request waits behind the drain.
+ */
+export const NOOP_SETTLE_BATCH = 50;
/** Guard failures that leave an effect for the runner, which records them as it does today. */
const LEFT_FOR_RUNNER = new Set(['owner_unavailable', 'source_changed', 'recovery_required']);
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 22a8459330..bc334910ad 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -971,6 +971,14 @@ export async function markRecovering(engine: SqlEngine, row: WriteRequest, reaso
[row.id, row.execution_token, reason, failure?.code ?? null, failure?.message ?? null, failure?.detail ? JSON.stringify(failure.detail) : null]);
}
const PERSISTENCE_QUEUE_TABLES = ['persistence_requests', 'persistence_effects', 'persistence_counters', 'page_projection_jobs', 'page_write_guards'];
+/**
+ * Lets timers and I/O run between PGLite statement chains. Every PGLite statement runs synchronously and resolves as a
+ * microtask, so a chain of them never returns to the event loop on its own and holds every request until it ends. It
+ * resumes from the timer queue: a check-phase resume (setImmediate) runs the next chain before timers that came due
+ * during the last one, so two chains back to back held a waiting request through both.
+ */
+export const yieldToEventLoop = () => new Promise<void>(resolve => setTimeout(resolve, 0));
+
/**
* PGLite has no autovacuum. The resident owner reclaims queue churn and keeps
* planner statistics current, so receipt lookups keep using the request-id
@@ -987,7 +995,10 @@ export async function vacuumPersistenceQueues(engine: BrainEngine): Promise<numb
`SELECT c.relname FROM pg_class c WHERE c.relname = ANY($1::text[]) AND c.relkind = 'r' AND c.relnamespace = 'public'::regnamespace
AND pg_relation_size(c.oid) / current_setting('block_size')::int > c.relpages * 1.1 + 8`, [PERSISTENCE_QUEUE_TABLES]);
const tables = PERSISTENCE_QUEUE_TABLES.filter(table => grown.some(row => row.relname === table));
- if (tables.length) await engine.executeRaw(`VACUUM (ANALYZE) ${tables.join(', ')}`);
+ for (const table of tables) {
+ await yieldToEventLoop();
+ await engine.executeRaw(`VACUUM (ANALYZE) ${table}`);
+ }
const [requests] = await engine.executeRaw<{ rows: number }>("SELECT GREATEST(reltuples,0)::float8 AS rows FROM pg_class WHERE oid='persistence_requests'::regclass");
return Number(requests?.rows ?? 0);
}
diff --git a/test/persistence-maintenance-yield.test.ts b/test/persistence-maintenance-yield.test.ts
new file mode 100644
index 0000000000..997391c50d
--- /dev/null
+++ b/test/persistence-maintenance-yield.test.ts
@@ -0,0 +1,71 @@
+/**
+ * Forced probe: PGLite queue maintenance returns to the event loop between its steps.
+ *
+ * Protects: on PGLite every statement runs synchronously and resolves as a microtask, so a chain of statements never
+ * lets a timer or stdin read run until the chain ends. The resident owner's first tick runs the compaction pass, the
+ * reservation sweep and the queue VACUUM back to back next to the effects drain; on a slow CI runner that one chain held
+ * the event loop for 2.2 s (test/persistence-drain-latency.serial.test.ts, bound 2 s). Each step now yields first, and a
+ * yield resumes from the timer queue, so a timer that came due runs before the next chain instead of after it.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { vacuumPersistenceQueues } from '../src/core/persistence/journal.ts';
+import { LAST_COMPACTION_KEY, runCompactionPass } from '../src/core/persistence/compaction-pass.ts';
+import { COMPACTED_SWEEP_KEY } from '../src/core/persistence/receipt-true-up.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+
+/** Runs `work` and returns each engine call it made with the event-loop turn (timer or check phase) it ran in. */
+async function turnsOf(work: () => Promise<unknown>): Promise<Array<{ call: string; turn: number }>> {
+ let turn = 0, stop = false;
+ const immediate = () => { turn++; if (!stop) setImmediate(immediate); };
+ const timer = () => { turn++; if (!stop) setTimeout(timer, 0); };
+ setImmediate(immediate);
+ setTimeout(timer, 0);
+ await new Promise<void>(resolve => setTimeout(resolve, 5));
+ const seen: Array<{ call: string; turn: number }> = [];
+ const target = engine as unknown as Record<string, (...args: unknown[]) => Promise<unknown>>;
+ const originals = Object.fromEntries(['executeRaw', 'getConfig', 'setConfig'].map(name => [name, target[name]!]));
+ for (const [name, original] of Object.entries(originals)) {
+ target[name] = function (this: BrainEngine, ...args: unknown[]) {
+ seen.push({ call: name === 'executeRaw' ? String(args[0]).trim().split(/\s+/).slice(0, 2).join(' ') : `${name} ${String(args[0])}`, turn });
+ return original.apply(this, args);
+ };
+ }
+ try { await work(); } finally { Object.assign(target, originals); stop = true; }
+ return seen;
+}
+
+test('the queue VACUUM runs in a later event-loop turn than the size check that chose it', async () => {
+ await engine.executeRaw("INSERT INTO persistence_counters(key) SELECT 'yield-' || g FROM generate_series(1, 3000) g");
+ const calls = await turnsOf(() => vacuumPersistenceQueues(engine));
+ const size = calls.find(c => c.call === 'SELECT c.relname')!;
+ const vacuum = calls.find(c => c.call.startsWith('VACUUM'))!;
+ expect(vacuum).toBeDefined();
+ expect(vacuum.turn).toBeGreaterThan(size.turn);
+ await engine.executeRaw("DELETE FROM persistence_counters WHERE key LIKE 'yield-%'");
+});
+
+test('the compaction pass, the reservation sweep and the pass record each run in their own event-loop turn', async () => {
+ const calls = await turnsOf(() => runCompactionPass(engine, { hostId: '00000000-0000-0000-0000-000000000001' }));
+ const compact = calls.find(c => c.call === 'SELECT *')!;
+ const sweep = calls.find(c => c.call === `getConfig ${COMPACTED_SWEEP_KEY}`)!;
+ const record = calls.find(c => c.call === `setConfig ${LAST_COMPACTION_KEY}`)!;
+ expect([compact, sweep, record].every(Boolean)).toBe(true);
+ expect(sweep.turn).toBeGreaterThan(compact.turn);
+ expect(record.turn).toBeGreaterThan(sweep.turn);
+});
+
+test('a yield resumes after timers that came due before it, not ahead of them', async () => {
+ const { yieldToEventLoop } = await import('../src/core/persistence/journal.ts');
+ let fired = false;
+ setTimeout(() => { fired = true; }, 0);
+ const until = performance.now() + 5;
+ while (performance.now() < until) { /* a synchronous statement chain */ }
+ await yieldToEventLoop();
+ expect(fired).toBe(true);
+});
+