Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): lane sharing and tick-bounded switch reads for the single-write fast path
garrytan9cbee9d76e8b
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 67cf99f652..e2bb0516a8 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -28,7 +28,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.-- `src/core/persistence/switches.ts` + `preadmit-cache.ts` + `config-snapshot.ts` — the single-write fast path for foreground page writes on Postgres. `switches.ts` reads every write-path kill switch (`persistence.single_write_group` / `GBRAIN_SINGLE_WRITE_GROUP`, `persistence.preadmit_cache` / `GBRAIN_PREADMIT_CACHE`, `sync.waive_batch` / `GBRAIN_SYNC_WAIVE_BATCH`; on by default, `0`/`false` off, env over config) in one `SELECT key,value FROM config WHERE key = ANY(...)` per engine, kept 5 s; read-through views name their engine (`VIEWED_ENGINE`) to share it. With `single_write_group` on: the consumer publishes an eligible single page write (put_page, capture, edit/delete/restore/revert without an internal `intent.kind` or group key) as a group of one through `publishGroup` (`publishSingleWrite`; its intent carries no group marker, its effects queue without `deferBatchReconcile`, and a group that does not commit falls back to `publishMutation`, reclaiming a claim its file restoration released); PGLite and refused shapes keep `publishMutation`. The waiter's own wake (`wake(true)`) claims without the periodic scans (recovery records still block the claim through `CLAIMABLE_WRITE_SQL`); preparation reads the config table once (`config-snapshot.ts`) and sends its independent reads together; the coordinated (`coordinated: true`) put_page apply reuses the publisher's locked read as the import base, pipelines its follow-up statements and reads the page once after its last write for the read-back check, seal, core notice and receipt. Publication, the own admission and the recovery transactions run on the consumer's reserved lane (`onLane`: the idle-probe connection, taken while two other pool connections stay free and kept across writes), so their prepared statements stay warm; the waiter is told of the commit before the recovery record is cleared. `preadmit-cache.ts` (with `preadmit_cache` on, Postgres) answers the brain id, source row, worktree binding and local-writer reads of `submitPageMutation` from a per-engine cache (30 s, keyed by brain id; absences never cached); admission rechecks each under lock and the brain id against its protocol statement, and a refusal the cache could explain (`source_changed`, `permission_denied`, a changed brain) drops the cache and runs the whole preparation once more uncached. Pinned by `test/e2e/single-write-fast-path-postgres.test.ts` (switches, cache rechecks, replay, restoration after a failure past the file rename, the recovery-blocked direct claim) and `test/single-write-group-parity.test.ts` + `test/e2e/single-write-group-parity-postgres.test.ts` (row-for-row parity with the switches off); measured by `scripts/bench/foreground-put-page.ts`.+- `src/core/persistence/switches.ts` + `preadmit-cache.ts` + `config-snapshot.ts` — the single-write fast path for foreground page writes on Postgres. `switches.ts` reads every write-path kill switch (`persistence.single_write_group` / `GBRAIN_SINGLE_WRITE_GROUP`, `persistence.preadmit_cache` / `GBRAIN_PREADMIT_CACHE`, `sync.waive_batch` / `GBRAIN_SYNC_WAIVE_BATCH`; on by default, `0`/`false` off, env over config) in one `SELECT key,value FROM config WHERE key = ANY(...)` per engine, kept 5 s (the consumer tick reads it under its phase deadline); read-through views register their engine (`registerEngineView`) to share it. With `single_write_group` on: the consumer publishes an eligible single page write (put_page, capture, edit/delete/restore/revert without an internal `intent.kind` or group key) as a group of one through `publishGroup` (`publishSingleWrite`; its intent carries no group marker, its effects queue without `deferBatchReconcile`, and a group that does not commit falls back to `publishMutation`, reclaiming a claim its file restoration released); PGLite and refused shapes keep `publishMutation`. The waiter's own wake (`wake(true)`) claims without the periodic scans (recovery records still block the claim through `CLAIMABLE_WRITE_SQL`); preparation reads the config table once (`config-snapshot.ts`) and sends its independent reads together; the coordinated (`coordinated: true`) put_page apply reuses the publisher's locked read as the import base, pipelines its follow-up statements and reads the page once after its last write for the read-back check, seal, core notice and receipt. Publication, the own admission and the recovery transactions run on the consumer's reserved lane (`onLane`: the idle-probe connection, taken while two other pool connections stay free and kept across writes; never lent while an idle probe runs on it, and probes skip it while lent), so their prepared statements stay warm; the waiter is told of the commit before the recovery record is cleared. `preadmit-cache.ts` (with `preadmit_cache` on, Postgres) answers the brain id, source row, worktree binding and local-writer reads of `submitPageMutation` from a per-engine cache (30 s, keyed by brain id; absences never cached); admission rechecks each under lock and the brain id against its protocol statement, and a refusal the cache could explain (`source_changed`, `permission_denied`, a changed brain) drops the cache and runs the whole preparation once more uncached. Pinned by `test/e2e/single-write-fast-path-postgres.test.ts` (switches, cache rechecks, replay, restoration after a failure past the file rename, the recovery-blocked direct claim) and `test/single-write-group-parity.test.ts` + `test/e2e/single-write-group-parity-postgres.test.ts` (row-for-row parity with the switches off); measured by `scripts/bench/foreground-put-page.ts`.- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite the first full tick releases claims last written before this process started (`releaseAbandonedClaims` in `effect-journal.ts`: running effects and unpublished requests without a recovery record), since the datastore admits one process and those owners have exited; Postgres keeps lease expiry (requests 30 s, effects 2 minutes). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Both the single route and the grouped/lane route (`executeClaimedGroup` in `group-publish.ts`) prepare under a claim lease (`claim-lease.ts`: a renewal every `renewalIntervalMs`, default 10 s, each bounded by `phaseMs`); the claim is lost the first time a renewal says it is gone, throws or overruns, and `whileHeld` stops waiting on the preparation at that moment (the single route also aborts it). The claims still ours are released unpublished with `claim_lost` (token-fenced, so a consumer that took one over keeps it); the abandoned preparation is never published and keeps its root or lane slot until it settles, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains abandoned preparations and in-flight renewals before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/persistence-consumer-scheduling.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`.diff --git a/src/core/persistence/config-snapshot.ts b/src/core/persistence/config-snapshot.tsindex 089438b57f..5cd4ae1989 100644--- a/src/core/persistence/config-snapshot.ts+++ b/src/core/persistence/config-snapshot.ts@@ -8,7 +8,7 @@* unchanged (`getAllConfig` answers from the same read). Publication reads its config again inside its transaction.*/import type { BrainEngine } from '../engine.ts';-import { VIEWED_ENGINE } from './switches.ts';+import { registerEngineView } from './switches.ts';const KEY_READ = 'SELECT value FROM config WHERE key=$1';const flat = (sql: string) => sql.replace(/\s+/g, ' ').trim();@@ -17,8 +17,7 @@ export async function preparationConfigView(engine: BrainEngine): Promise<BrainEconst rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key,value FROM config');const values = new Map(rows.map(row => [row.key, row.value]));const value = (key: string) => values.has(key) ? values.get(key)! : null;- return new Proxy(engine, { get(target, key) {- if (key === VIEWED_ENGINE) return target;+ return registerEngineView(new Proxy(engine, { get(target, key) {if (key === 'getConfig') return async (name: string) => value(name);if (key === 'getAllConfig') return async () => Object.fromEntries(values);if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) =>@@ -27,5 +26,5 @@ export async function preparationConfigView(engine: BrainEngine): Promise<BrainE: target.executeRaw(sql, params, opts);const member = Reflect.get(target, key, target);return typeof member === 'function' ? member.bind(target) : member;- } });+ } }), engine);}diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 1da5ab2cac..8c88df4a50 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -24,7 +24,7 @@ import { maybeRefreshPlannerStats } from '../planner-stats.ts';import { refreshFenceClear } from './worktree-refresh-schema.ts';import { faultPoint } from './fault-points.ts';import { releaseAbandonedClaims } from './effect-journal.ts';-import { writeSwitchOn } from './switches.ts';+import { readWriteSwitches, writeSwitchOn } from './switches.ts';type PhaseObservation = { name: string; started_at: string; deadline_exceeded: boolean; attempt: number; first_conn_ms?: number };/** #5373: set by a task that abandons a still-running preparation after losing its claim; its root is freed only once `until` settles. */@@ -77,8 +77,10 @@ export class PersistenceConsumer {private topologyRetryAfter = new Map<string, number>();private idleLane: { conn: ReservedConnection; release: () => Promise<void> } | undefined;private idleLaneRetryAt = 0;- /** Phase 4.4: a single write is publishing on the idle lane's connection. */+ /** Phase 4.4: a single write is publishing or admitting on the idle lane's connection. */private laneInUse = false;+ /** An idle probe is running on the lane; it is not lent until the probe settles. */+ private probeOnLane = false;private active = new Set<Promise<void>>();/** #5373: preparations and renewals that outlived their claim; stop() drains them before the engine closes. */private outlived = new Set<Promise<void>>();@@ -176,7 +178,7 @@ export class PersistenceConsumer {const excluded = [...this.activeRoots, ...[...this.rootRetryAfter].filter(([, at]) => at > now).map(([root]) => root)];for (const [id, at] of this.topologyRetryAfter) if (at <= now) this.topologyRetryAfter.delete(id);const retryingTopologies = [...this.topologyRetryAfter.keys()];- const [row] = await this.phase('idle_probe', async signal => this.probeQuery<{ work: boolean }>(await this.acquireIdleLane(signal), `SELECT (+ const [row] = await this.phase('idle_probe', async signal => this.probeQuery<{ work: boolean }>(this.laneInUse ? undefined : await this.acquireIdleLane(signal), `SELECT (EXISTS (SELECT 1 FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id=r.worktree_idWHERE ${CLAIMABLE_WRITE_SQL}AND ($3::boolean OR r.blocked_reason IS DISTINCT FROM 'writer_pool_capacity'))@@ -273,7 +275,7 @@ export class PersistenceConsumer {async onLane<T>(run: (transaction: <R>(fn: (tx: BrainEngine) => Promise<R>) => Promise<R>) => Promise<T>): Promise<T | typeof LANE_BUSY> {if (this.engine.kind !== 'postgres' || this.stopping || this.laneInUse || !await writeSwitchOn(this.engine, 'single_write_group').catch(() => true)) return LANE_BUSY;const conn = await this.acquireIdleLane(undefined, true) as (ReservedConnection & Partial<ReservedTransactions>) | undefined;- if (!conn?.transaction || this.laneInUse) return LANE_BUSY;+ if (!conn?.transaction || this.laneInUse || this.probeOnLane || this.idleLane?.conn !== conn) return LANE_BUSY;this.laneInUse = true;try {return await run(fn => conn.transaction!(fn));@@ -287,7 +289,10 @@ export class PersistenceConsumer {}private async probeQuery<T>(lane: ReservedConnection | undefined, sql: string, params: unknown[], signal?: AbortSignal): Promise<T[]> {if (!lane) return this.engine.executeRaw<T>(sql, params, { signal });+ if (this.laneInUse) return this.engine.executeRaw<T>(sql, params, { signal });+ this.probeOnLane = true;const query = lane.executeRaw<T>(sql, params);+ void query.then(() => { this.probeOnLane = false; }, () => { this.probeOnLane = false; });if (!signal) return query;const aborted = Promise.withResolvers<never>();const onAbort = () => aborted.reject(signal.reason ?? new DOMException('aborted', 'AbortError'));@@ -295,8 +300,8 @@ export class PersistenceConsumer {try { return await Promise.race([query, aborted.promise]); }catch (error) {// The reserved query cannot be cancelled: stop using the lane now, return it to the pool once the query settles.- const current = this.idleLane;- if (current?.conn === lane) this.idleLane = undefined;+ const current = this.idleLane?.conn === lane ? this.idleLane : undefined;+ if (current) this.idleLane = undefined;this.idleLaneRetryAt = Date.now() + 60_000;void query.then(() => current?.release(), () => current?.release());throw error;@@ -346,10 +351,13 @@ export class PersistenceConsumer {}}// Lane runs size themselves to the pool's long-hold budget; a single write keeps its warm lane.- if (laneRoots().length || this.engine.kind !== 'postgres' || !await writeSwitchOn(this.engine, 'single_write_group').catch(() => true)) await this.releaseIdleLane();+ // The switches are read under the tick's phase deadline, so a saturated pool cannot hold the tick.+ const fast = await this.phase('switches', signal => readWriteSwitches(this.engine, { signal }))+ .then(switches => switches.single_write_group, async error => { await this.releaseIdleLane(); throw error; });+ if (laneRoots().length || this.engine.kind !== 'postgres' || !fast) await this.releaseIdleLane();this.idleDelayMs = this.pollMs;this.nextDelayMs = this.pollMs;- const direct = afterProgress && this.ownAdmission && await writeSwitchOn(this.engine, 'single_write_group').catch(() => true);+ const direct = afterProgress && this.ownAdmission && fast;this.ownAdmission = false;const scan = !direct && (!afterProgress || Date.now() - this.lastScan >= this.pollMs);if (scan) {diff --git a/src/core/persistence/preadmit-cache.ts b/src/core/persistence/preadmit-cache.tsindex 264e3de9a6..1d78418240 100644--- a/src/core/persistence/preadmit-cache.ts+++ b/src/core/persistence/preadmit-cache.ts@@ -19,7 +19,7 @@*/import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';-import { VIEWED_ENGINE, writeSwitchOn } from './switches.ts';+import { registerEngineView, writeSwitchOn } from './switches.ts';export const PREADMIT_TTL_MS = 30_000;const BRAIN_SQL = 'SELECT brain_id FROM persistence_brain WHERE singleton=1';@@ -79,15 +79,14 @@ export async function preadmitReads(engine: BrainEngine, now: () => number = Dat};// Every cached read is filed under the brain it was taken for, which admission checks.if (!held.brainId || now() - held.brainId.at >= PREADMIT_TTL_MS) await read(BRAIN_SQL, undefined, undefined);- return new Proxy(engine, { get(target, key) {- if (key === VIEWED_ENGINE) return target;+ return registerEngineView(new Proxy(engine, { get(target, key) {if (key === 'executeRaw') return (sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) => {const text = flat(sql);return text === BRAIN_SQL || text === SOURCE_SQL || text === BINDING_SQL || WRITER_SQL.has(text) ? read(text, params, opts) : target.executeRaw(sql, params, opts);};const value = Reflect.get(target, key, target);return typeof value === 'function' ? value.bind(target) : value;- } });+ } }), engine);}/** Thrown by admission when the brain behind the connection is not the one the cached reads came from; never leaves the retry. */diff --git a/src/core/persistence/switches.ts b/src/core/persistence/switches.tsindex 315169e113..9c485821fc 100644--- a/src/core/persistence/switches.ts+++ b/src/core/persistence/switches.ts@@ -37,15 +37,22 @@ function resolve(configured: Map<string, string>): WriteSwitches {return out;}-/** A read-through view of an engine (preparation config, pre-admission cache) names its engine here, so it shares that engine's snapshot. */-export const VIEWED_ENGINE = Symbol('gbrain.viewedEngine');+/** Read-through views of an engine (preparation config, pre-admission cache) and the engine they read through. */+const views = new WeakMap<object, object>();+export function registerEngineView<T extends object>(view: T, engine: object): T { views.set(view, engine); return view; }+/** The engine a view reads through (itself when it is not a view), so a view shares its engine's snapshots and memos. */+export function viewedEngine<T extends object>(engine: T): T { return (views.get(engine) as T | undefined) ?? engine; }-/** The switch snapshot of `engine`'s brain, at most SWITCH_TTL_MS old. A failed read is not kept. */-export function readWriteSwitches(viewed: SqlEngine, now: () => number = Date.now): Promise<WriteSwitches> {- const engine = (viewed as { [VIEWED_ENGINE]?: SqlEngine })[VIEWED_ENGINE] ?? viewed;+/**+ * The switch snapshot of `engine`'s brain, at most SWITCH_TTL_MS old. A failed read is not kept.+ * `signal` cancels a read this call starts (the consumer's tick reads under its phase deadline).+ */+export function readWriteSwitches(viewed: SqlEngine, opts: { now?: () => number; signal?: AbortSignal } = {}): Promise<WriteSwitches> {+ const now = opts.now ?? Date.now;+ const engine = viewedEngine(viewed);const held = snapshots.get(engine);if (held && held.generation === generation && now() - held.at < SWITCH_TTL_MS) return held.read;- const read = engine.executeRaw<{ key: string; value: string }>('SELECT key,value FROM config WHERE key = ANY($1::text[])', [WRITE_SWITCH_KEYS])+ const read = engine.executeRaw<{ key: string; value: string }>('SELECT key,value FROM config WHERE key = ANY($1::text[])', [WRITE_SWITCH_KEYS], { signal: opts.signal }).then(rows => resolve(new Map(rows.map(row => [row.key, row.value]))));snapshots.set(engine, { at: now(), generation, read });read.catch(() => { if (snapshots.get(engine)?.read === read) snapshots.delete(engine); });diff --git a/src/core/shared-skills/knowledge-guard.ts b/src/core/shared-skills/knowledge-guard.tsindex 67c1b1c702..6ffacfefde 100644--- a/src/core/shared-skills/knowledge-guard.ts+++ b/src/core/shared-skills/knowledge-guard.ts@@ -1,5 +1,5 @@import { isAbsolute, relative, resolve, sep } from 'node:path';-import { VIEWED_ENGINE } from '../persistence/switches.ts';+import { viewedEngine } from '../persistence/switches.ts';import { fileURLToPath } from 'node:url';import { OperationError } from '../ops/contract.ts';import { isRelativeFileUri, resolveSourceLocalFilePath } from '../markdown.ts';@@ -32,7 +32,7 @@ const packsInTransaction = new WeakMap<object, Promise<PackRoot[]>>();/** Engines (the connection owner, not a transaction view of it) whose schema has shared_skill_packs; migrations never drop it. */const packTablePresent = new WeakSet<object>();function connectionOwner(engine: object): object {- let owner = (engine as { [VIEWED_ENGINE]?: object })[VIEWED_ENGINE] ?? engine;+ let owner = viewedEngine(engine);while (Object.hasOwn(owner, '_pageTransaction') && (owner as { _pageTransaction?: boolean })._pageTransaction === true) owner = Object.getPrototypeOf(owner);return owner;}