Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(persistence): one-shot CLI writes run housekeeping after the reply, memo config reads, fewer connections (GBRA-156)
garrytan6de277c4bd58
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex a1222e95c4..6ca7944c74 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -27,6 +27,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `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, + the 5 s #6650 dead-owner scan, mirroring the claim, recovery, expired-claim, effect, projection (inline rows windowed by `projection-window.ts`) 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. Every claimed write has a preparation budget (`preparation-budget.ts`): `execute` races the preparation against it (`startPreparation`), so the claim is released with `blocked_reason` `preparation_deadline` and one counted attempt at the budget even when the preparer ignores its signal, and a late result never publishes (the execution-token fence). A request already at `persistence.max_preparation_attempts` is finished `failed` with `preparation_stalled` at claim without preparing again, and the release that reaches the limit finishes it there (`coordinator.ts` `finishPreparationStalled`; a waiting `awaitWrite` caller gets the terminal receipt, foreground writes included); a preparer's rejection on the consumer's own abort (its reason, an `AbortError` or a cancelled statement, `preparationAbortReason`) is a release, never a receipt. The expired-claim sweep (Postgres, and PGLite's `releaseAbandonedClaims`) charges one attempt for a claim stamped `preparing` (a process killed mid-preparation); `claim_lost`, `consumer_stopping` and `group_member_waiting` never charge, and a commit resets the counter. A statement the database ended with 57014 (statement timeout or cancel: `coordinator.ts` `writeInterruption`) is charged too, in `finishUnpublishedFailure` and in `publishMutation`'s recovery route, and at the limit ends the request `failed` with `write_interrupted` instead of a `database_contention` release; contention with other transactions (55P03, 40001, 40P01), a dropped connection or a restarting database is never charged (`test/persistence-write-interrupted.test.ts`). The #5373 root barrier for an abandoned preparation ends at `persistence.preparation_ceiling_ms` measured from the claim: the root is freed, the counter is pinned at the limit (an overrun proves cancellation is ignored, so the next claim fails the request `preparation_stalled`) and the zombie stays in `status().outlived_ceiling`; at the per-process cap (`zombieCap`, default 1) the consumer claims nothing more and `status().restart_required` is true. `stop()` gives abandoned preparations `ABANDONED_STOP_GRACE_MS` (5 s) after aborting them instead of waiting forever. The fault point `consumer:preparing` sits inside the budget, `status()` reports `preparation_policy` and `abandoned_preparations`, and the stderr line carries `phase=preparation reason=deadline_exceeded | preparation_stalled | ceiling_exceeded`. With the `preparation_deadlines` switch off only `remember` and intent-less `put_page`/`edit_page` keep the 30 s budget, the old unbounded wait applies and no attempt is counted. 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 `claimableWriteSql` 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 (PGLite, 1,000 pages: ~9.5 ms mean, ~18 ms p99 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); a provably dead owner's claim goes in 5 s (#6650). 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 or the ceiling passes, while the consumer slot frees at once. Renewals are never awaited on the way out: `stop()` drains in-flight renewals and gives abandoned preparations their grace before engine close. Tests: `test/persistence-claim-lease.test.ts`, `test/e2e/persistence-consumer-claim-loss.test.ts`, `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-deadline.e2e.test.ts`. #6355: `onLane` lends its warm lane's transaction through a wrapper that notes a connection loss (`isConnectionLoss`); in `finally` a lost lane is released and `idleLaneRetryAt` set a minute out, whatever `run` returned or threw (admission turns the loss into `write_outcome_unknown` or succeeds on the pool, so the catch alone never saw it), because the dead reservation answers every later statement with "Connection is no longer owned" (`test/persistence-consumer-lane-loss.test.ts`). #7106: `publishSingle` passes `projectionPending` (coordinator.ts `PublicationHooks`): a committed write that created its page (no page at its slug before the publication, and no additional page key such as a rename's) and whose outcome says `projection: 'pending'` (a new segmented page over SEGMENTED_CREATE_SEAL_MAX_BYTES, quarantined or not: `segmentedOutcome` in searchable.ts, recorded by the managed import, sync and put_page preparers) settles its waiter at commit, and its `afterCommit` projection goes to `detachBuild`, which runs at most `DETACHED_PROJECTION_BUILDS` (1) at a time, queued builds in order, each tracked in `outlived` so stop() waits for queued and running builds; it holds neither the reply nor the root. An edit (a deferred retirement included) and a publication without the hook await afterCommit as before (`test/large-pages/managed-import-projection-pending.test.ts`).- **`src/core/persistence/sync-group.ts`** + **`group-publish.ts`** — #5984 bulk publication for draining managed Postgres syncs. `sync-group.ts` resolves bulk settings (`--no-bulk` > `GBRAIN_SYNC_BULK` > `sync.bulk` > on; `sync.bulk_size` 16, `sync.bulk_max_txn_ms` 15 s; PGLite off), sizes the next group from the last group's admission-to-commit time per member, freezes followers (four at a time, stopping at a rename, company plan, overtaken or waived entry, or #6712 a slug or page id shared with a member in flight or held, `dependencyKeys`) and admits a group in one transaction (`admitWriteGroupInTransaction`, which keeps one request row, ID and digest per page and replays priors). `sync-run.ts` keeps the head in `pending` and all members in the cursor's `group` (members carry `intent.group` = the head's request ID), waits for the last member and advances over the committed prefix; a terminal failure becomes the pending entry (settled by fault class; later members stay in the window, #6712), a still-pending member returns `writer_pending`. Any caller finishes an existing group; only a drain forms one. #6075: when another owner loop already admitted the group's head on the single path with the head's pre-group intent (the intent minus the `group`/`lane` keys `formGroup` adds, `groupedIntent`/`ungroupedIntent`), `groupStep` drops the group and the single path takes that request, and the never-admitted followers are frozen again; a different intent under the head's request ID still refuses `idempotency_conflict`. The single path's ENG-A7 admission guard compares the stored pending intent as well as its request ID, so a pass that read the head before a drain grouped it re-reads the cursor instead of admitting the stale intent, and an `idempotency_conflict` against a head the group admitted first re-reads the cursor too (`test/managed-sync-stale-group-head.test.ts`). The consumer claims a head's directly following queued members (`claimGroupFollowers`, never past an unfinished non-member) and `executeClaimedGroup` prepares four at a time, then `publishGroup` publishes them in one transaction: one worktree lock, ownership guard and coordinated write (each member set as the attributed actor with `setMemberAttribution`), per-member authorization, preimage read, sync validation (its source-wide part shared per transaction), apply (which reads the postimage the receipt and effects use), effects and receipt; `completeGroup` then reads every member's effect bytes, and pipelines the counter lock with one `UPDATE ... FROM unnest(...) RETURNING` that checks each member's claim and terminal reservation and releases the counters (a short `RETURNING` throws, so the single path reports each member's own code). #6712: each member keeps its own fate (sync groups keep claim 64, width four, ordered release, `syncGroup`): a failed preparation settles before the rest publish as a group; a sync member its lane group's transaction refused settles alone, the rest requeue (`settleCulprit`); other failures roll back and members publish singly. Sync validation accepts a group member through the cursor's `group`. #6007: the pages of one `put_pages` batch (`intent.page_batch.id`; the group key is `journal.ts` `publicationGroupKey`) and the files of one managed import batch (`intent.import_batch`, key `import:`, grouped on PGLite too; `independentGroup` names both) also publish as groups of at most `PAGE_BATCH_GROUP_MAX` (8) pages, prepared all at once, files included: one transaction records every member's recovery record (`prepareRecoveries`) before any file is touched, the publication transaction marks the members `publication_started`, publishes each member's file before its apply and re-arms the batch's mention links once after every member completes (`reconcileFinishedBatch`), and one transaction clears the records after commit (`clearResolvedRecoveries`). A single foreground page write publishes here too, as a group of one (core-persistence-continued.md, `switches.ts` entry). Within that transaction the source's local path, the owner's host binding and config values are read once per group (source membership and the writer registration are already memoized per transaction by `transactionMemo`). On failure every file the group published is restored by `recoverPublication`, which requeues those claims; the fallback claims them back in order (`reclaimReleasedWrite`) and publishes the members singly. Each member has its own preparation budget (#6278): `executeClaimedGroup` marks a wave durably (`markDispatched`) and starts each member's clock when the wave dispatches it, so a follower waiting behind four others is never charged; the lease renews the mutable set of members still held (`renewGroupClaims` stamps each member's own phase), so releasing one member never reads as a lost group lease. When member k's budget passes, nothing later is dispatched, the in-flight suffix is aborted, k is released `preparation_deadline` (charged; finished `preparation_stalled` when that reaches the limit) and the later members `group_member_waiting` (not charged), and the contiguous prepared prefix 0..k-1 publishes (singly when shorter than two; under lanes in the original group's key order). A `put_pages` batch group releases only k, `laneFallback` keeps the expired member's reason, and an abandoned member's preparation goes to the consumer with its clock, so the root waits for it until it settles or the ceiling. A member's signal reaches its preparer through its clock (`enterClaimStep`), never as a blanket statement signal: `preparationReads` and `groupReads` answer one read for every member (GBRA-75 wave 10: `preparationReads` answers `getConfig` from one `getAllConfig` per group; an import group's members also read their own `{ sourceId, includeDeleted: true }` snapshot from one batch and coalesce `findDuplicatePage` into one `findDuplicatePages` statement through `import-reads.ts`, and the group's preparation runs inside `withScreeningPaths`; publication's `validate`/`checkPaths` run after it, unmemoized) and skip their memo for a signalled statement, so a member that must give up on a shared read races its own signal against the shared promise (pinned by `test/persistence-preparation-memo-rule.test.ts`). A commit resets `preparation_attempts` (`completeGroup`). Tests: `test/managed-sync-bulk.test.ts`, `test/e2e/put-pages-group-postgres.test.ts`, `test/e2e/persistence-group-deadline-postgres.test.ts`.- `src/core/persistence/identity.ts` — local writer and host identity. GBRA-75 wave 7: `localHostId` / `localHostIdentity` / `existingLocalHostId` share one cache of the validated `host.json`, keyed on the path (recomputed from `persistenceHome()` on every call, so a `GBRAIN_HOME` change misses) plus `statSync(bigint)` dev, ino, mtimeNs, ctimeNs and size. ENOENT is a miss (`existingLocalHostId` never mints); any other stat error reads uncached, so `writer_identity_invalid` still throws on every call; an invalid document is never cached; a file modified under 2 s ago is read but not cached (same-size rewrites inside one timestamp tick). `scripts/persistence/harness.ts` `selectFixtureHost` (rename over the path) stays correct. Tests: `test/persistence-host-identity-cache.test.ts`.+- `src/core/persistence/housekeeping-turn.ts` — GBRA-156: a one-shot CLI consumer (`markOneShotCommand`) runs upkeep only after its write and only in the host's turn, one per `GBRAIN_ONESHOT_HOUSEKEEPING_INTERVAL_MS` (default 5 min); see the module doc. Tests: `test/write-roundtrips-gbra156.test.ts`.- `src/core/persistence/consumer-heartbeat.ts` — #6317 (B1a, B3): the probe and heartbeat behind one full consumer per host. `consumerIdentity()` is this process's `{pid, nonce, pid_ns}` (a random per-process nonce, the `/proc/self/ns/pid` inode where readable), so a reused pid after a container restart is a new row; every `owner_pid === process.pid` check compares the nonce too. `startConsumerHeartbeat(engine, row, opts)` renews this process's `persistence_consumers` row every 10 s on its own single-flight timer through `executeRawDirect` (independent of claim renewal: an idle `serve` holds no claim), carrying kind (`claimOwner().kind`), mode (`probing|full|waiter_only|promoted`), `restart_required`, the age of the oldest abandoned root barrier, the pool gauge `{checked_out, max, waiters}`, `host_json_path`, `persistence_home`, `minted_under` and the build; each renewal deletes rows not renewed for 90 s in the same CTE, and a failed write is logged once and never stops the consumer. #6650: rows carry `boot_id`, `process_start` (v243); the probe and `electOwner` skip rows `consumerRowProvablyDead` proves dead (Linux: same boot and pid ns, pid gone/reused). `probeLiveFullConsumer(engine, hostId, self)` is the database-only probe (never a socket: the persistence IPC socket exists only on PGLite): a row of a resident kind (`serve`, `sync`, `jobs`, `autopilot`, `mcp`), mode `full`, not this process, renewed within 30 s, not `restart_required` and not wedged (no root barrier older than `persistence.preparation_ceiling_ms`), on an `active` binding. `listHostConsumers(engine, hostId)` feeds `writer status --json` `host.consumers` and doctor. The consumer mode machine in `consumer.ts` (`probing` → `full` or `waiter_only` → `promoted` → back to `waiter_only` after three healthy owner ticks) consumes the probe on every tick; `startPersistenceConsumer` in `service.ts` stays synchronous and returns the waiter-only seam (`WaiterOnlyConsumer` behind `PersistenceConsumerLike`: `wake()` no-op, settlement listeners kept, `holds()` false, `status()` `waiter_only` with the owner pid) when the probe finds an owner and `persistence.single_consumer` is on. A `serve` always starts full; short-lived kinds (`put`, `import`, `dream`, `cycle`, `sources`, `cli`) keep their own consumer; PGLite is inert.- `src/core/schema-migrations/v222-persistence-consumers.ts` — #6317 (T-01): the `persistence_consumers` table, primary key `(host_id, pid, nonce)`, columns `pid_ns`, `kind`, `mode`, `started_at`, `renewed_at`, `restart_required`, `root_barrier_age_ms`, `pool` jsonb, `host_json_path`, `persistence_home`, `minted_under` jsonb, `version`; plus the partial index `persistence_requests (worktree_id, completed_at DESC) WHERE state = 'committed'` that the movement watermark reads (the baseline indexes cover pending, recovery and principal reads only). Both objects are also in `src/schema.sql` for fresh installs (PGLite and Postgres parity, goldens). The number is taken at the merge slot by `bun run release:restamp`.- `src/core/persistence/journal.ts` — the request journal SQL: admission, claims, renewals, releases and completion. #6278: the claim statements stamp a `preparing` phase of their own token at claim time and return the previous claim's stamp with the row (`previous_claim_phase`), so a stalled receipt names the last recorded step; a follower's stamp has only its token and owner (#6650) until its wave dispatches it (`markDispatched`), so a kill charges exactly the members that were preparing; `renewGroupClaims` stamps each member's own phase; `releaseUnpublishedClaim` charges one `preparation_attempts` only for `preparation_deadline` (`claim_lost`, `consumer_stopping` and `group_member_waiting` never do); `chargePreparationAttempt` charges a claim this owner still holds before it is finished `preparation_stalled`; `floorPreparationAttempts` pins the counter at the limit after a ceiling overrun; completing a request as committed resets the counter (`completeWrite`, `completeGroup`). An older owner ignores the counter and its renewals overwrite the stamp with the old shape (writer status shows each owner's version); every statement keeps `PERSISTENCE_PROTOCOL_PREDICATE`. Tests: `test/persistence-preparation-kill-accounting.test.ts`, `test/e2e/persistence-preparation-attempts-postgres.test.ts`.diff --git a/src/cli/db-plane-config.ts b/src/cli/db-plane-config.tsindex a1d5bbf875..ec22e19f3c 100644--- a/src/cli/db-plane-config.ts+++ b/src/cli/db-plane-config.ts@@ -6,7 +6,8 @@import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';import { configureGateway, reconfigureGatewayWithEngine } from '../core/ai/gateway.ts';import { loadConfigWithEngine, type GBrainConfig } from '../core/config.ts';-import { withRequestConfigSnapshot } from '../core/config-snapshot.ts';+import { keepCommandStartupConfig, requestConfigRows, withRequestConfigSnapshot } from '../core/config-snapshot.ts';+import { seedWriteSwitchSnapshot } from '../core/persistence/switches.ts';import type { BrainEngine } from '../core/engine.ts';export async function mergeDbPlaneConfig(engine: BrainEngine, config: GBrainConfig, MERGED_CONFIG_BY_ENGINE: WeakMap<BrainEngine, GBrainConfig>): Promise<void> {@@ -52,6 +53,9 @@ export async function mergeDbPlaneConfig(engine: BrainEngine, config: GBrainConf// chat. Per Codex F3 — configureGateway is sync; this is the async// re-stamp seam after engine.connect() makes config reads possible.await reconfigureGatewayWithEngine(engine);+ // GBRA-156: the same table read serves the command's source resolution and its write switches.+ const rows = await requestConfigRows(engine);+ if (rows) { keepCommandStartupConfig(engine, rows); seedWriteSwitchSnapshot(engine, rows); }});} catch {// Non-fatal. Pre-v39 brains may not have a usable config table yet.diff --git a/src/cli/main.ts b/src/cli/main.tsindex 95ac6f68d6..1c48044609 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -522,6 +522,7 @@ async function main() {* Split out of main() (refactor wave 1, W4 cli); order and exits unchanged.*/async function runSharedOperation(command: string, subArgs: string[], cliOpts: CliOptions): Promise<void> {+ (await import('../core/persistence/claim-phase.ts')).markOneShotCommand();// Shared operations (fall through to aliases, e.g. link-add -> add_link)const meta = cliOps.get(command) ?? cliAliases.get(command);if (!meta) exitCliError(usageError(`Unknown command: ${command}`, 'Run `gbrain --help` for available commands.', { code: 'unknown_command' }), command);@@ -1454,10 +1455,14 @@ export async function makeContext(engine: BrainEngine, params: Record<string, unconst explicit = op && opOwnsSource(op) ? null : (params.source as string | undefined) ?? null;const { resolveSourceWithTier, localFederatedSourceIds, SourceTargetError } = await import('../core/source-resolver.ts');try {- const resolved = await resolveSourceWithTier(engine, explicit);- sourceId = resolved.source_id;- sourceImplicit = resolved.tier !== 'flag' && resolved.tier !== 'env' && resolved.tier !== 'dotfile';- localFederated = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);+ // GBRA-156: the source resolution reads config through the table the connect-time merge already read.+ const { commandStartupConfig, withRequestConfigSnapshot } = await import('../core/config-snapshot.ts');+ await withRequestConfigSnapshot(engine, async () => {+ const resolved = await resolveSourceWithTier(engine, explicit);+ sourceId = resolved.source_id;+ sourceImplicit = resolved.tier !== 'flag' && resolved.tier !== 'env' && resolved.tier !== 'dotfile';+ localFederated = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);+ }, commandStartupConfig(engine));} catch (err) {// #1712: an EXPLICIT --source that fails to resolve (invalid id, or a// source that doesn't exist) must error loudly — the blanket swallowdiff --git a/src/core/config-snapshot.ts b/src/core/config-snapshot.tsindex 8835c79ebb..f90c547067 100644--- a/src/core/config-snapshot.ts+++ b/src/core/config-snapshot.ts@@ -101,10 +101,13 @@ function activeSnapshot(engine: object): RequestSnapshot | undefined {return store && !store.live && store.held.open && store.held.engine === engine ? store.held : undefined;}-/** Run `fn` with one config snapshot of `engine`; an enclosing snapshot of the same engine is reused. */-export async function withRequestConfigSnapshot<T>(engine: BulkConfigReader, fn: () => Promise<T>): Promise<T> {+/**+ * Run `fn` with one config snapshot of `engine`; an enclosing snapshot of the same engine is reused. `seed` (GBRA-156) is+ * a whole-table read this command already took (`commandStartupConfig`), which the snapshot answers from instead of reading again.+ */+export async function withRequestConfigSnapshot<T>(engine: BulkConfigReader, fn: () => Promise<T>, seed?: Record<string, string>): Promise<T> {if (activeSnapshot(engine)) return fn();- const held: RequestSnapshot = { engine, open: true, rows: null };+ const held: RequestSnapshot = { engine, open: true, rows: seed ? Promise.resolve(new Map(Object.entries(seed))) : null };try {return await requestSnapshot.run({ held, live: false }, fn);} finally {@@ -150,6 +153,22 @@ export async function requestConfigRows(engine: BulkConfigReader): Promise<Recorreturn rows ? Object.fromEntries(rows) : undefined;}+/**+ * GBRA-156: the whole config table as the CLI's connect-time merge read it (cli/db-plane-config.ts), kept per engine so the+ * same command's next read-only resolution (makeContext's source resolution) answers from it instead of reading again.+ * Taken once: a later resolution reads live, as before.+ */+const startupRows = new WeakMap<object, { at: number; rows: Record<string, string> }>();+export const STARTUP_CONFIG_MAX_AGE_MS = 5_000;+export function keepCommandStartupConfig(engine: object, rows: Record<string, string>, now: number = Date.now()): void {+ startupRows.set(engine, { at: now, rows });+}+export function commandStartupConfig(engine: object, now: number = Date.now()): Record<string, string> | undefined {+ const kept = startupRows.get(engine);+ startupRows.delete(engine);+ return kept && now - kept.at < STARTUP_CONFIG_MAX_AGE_MS ? kept.rows : undefined;+}+/** Keep an open snapshot of `engine` equal to a write the engine just made (value null = key removed). */export function noteRequestConfigWrite(engine: object, key: string, value: string | null): void {const held = activeSnapshot(engine);diff --git a/src/core/db.ts b/src/core/db.tsindex 82d28a321a..a8d38b5c75 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -1,5 +1,5 @@import postgres from '#postgres'-import { claimOwner } from './persistence/claim-phase.ts';+import { claimOwner, isOneShotCommand } from './persistence/claim-phase.ts';import { traceSqlOptions } from './sql-trace.ts';import { GBrainError, type EngineConfig } from './types.ts';import { SCHEMA_SQL } from './schema-embedded.generated.ts';@@ -555,6 +555,9 @@ export async function connect(config: EngineConfig, hooks: PoolHealthHooks = {})}sql = postgres(url, traceSqlOptions(opts, 'module'));+ // GBRA-156: a one-shot command's startup reads its retired-marker state beside its persistence row, which opened the+ // pool's second connection on the critical path (about three round trips behind a pooler); it opens beside the first.+ if (isOneShotCommand() && Number(opts.max) >= 3) sql`SELECT 1`.catch(() => undefined);// Test connectionawait checkPoolAndLoadSharedTypes(sql, url);connectedUrl = url;diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 3fb62400a4..e1261320c8 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -391,10 +391,12 @@ export async function updatePageContextualRetrievalState(sourceId: string,mode: string,corpusGeneration: string | null,+ memo: <T>(key: string, read: () => Promise<T>) => Promise<T> = (_key, read) => read(),): Promise<void> {if (mode === 'none') {- const { rows: config } = await exec.run<{ key: string; value: string }>(sqlFragment`- SELECT key,value FROM config WHERE key IN ('search_embedding_column','embedding_columns')`);+ // GBRA-156: the same read, under the same memo key, as the chunk write of this page transaction (chunks.ts).+ const config = await memo('config:embedding-write', async () => (await exec.run<{ key: string; value: string }>(+ sqlFragment`SELECT key, value FROM config WHERE key IN ('search_embedding_column', 'embedding_columns', 'embedding_model')`)).rows);const column = resolveWriteColumnFromConfigRows({searchEmbeddingColumn: config.find(row => row.key === 'search_embedding_column')?.value ?? null,embeddingColumnsJson: config.find(row => row.key === 'embedding_columns')?.value ?? null,diff --git a/src/core/persistence/admission-origin.ts b/src/core/persistence/admission-origin.tsindex 0f6af43241..d6e9eb351f 100644--- a/src/core/persistence/admission-origin.ts+++ b/src/core/persistence/admission-origin.ts@@ -68,7 +68,12 @@ export function isAdmissionOrigin(value: unknown): value is AdmissionOrigin {/** The pause line as a share of each cumulative cap (0 < share <= 1); the setting is a percent (80), and a share (0.8) reads the same. */export async function readBackgroundPauseShare(engine: SqlEngine): Promise<number> {const [row] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1', [BACKGROUND_PAUSE_KEY]);- const value = row ? Number(row.value) : DEFAULT_BACKGROUND_PAUSE_SHARE;+ return backgroundPauseShare(row?.value);+}++/** The pause share a stored setting (undefined when unset) stands for. */+export function backgroundPauseShare(raw: string | undefined): number {+ const value = raw === undefined ? DEFAULT_BACKGROUND_PAUSE_SHARE : Number(raw);if (!Number.isFinite(value) || value <= 0 || value > 100) return DEFAULT_BACKGROUND_PAUSE_SHARE;return value > 1 ? value / 100 : value;}diff --git a/src/core/persistence/capacity-forecast.ts b/src/core/persistence/capacity-forecast.tsindex 5b65b6487f..b4a84d7a00 100644--- a/src/core/persistence/capacity-forecast.ts+++ b/src/core/persistence/capacity-forecast.ts@@ -22,7 +22,8 @@*/import type { SqlEngine } from './model.ts';import { DEFAULT_JOURNAL_LIMITS, type JournalLimits } from './model.ts';-import { DEFAULT_RECEIPT_RETENTION_DAYS, journalLimitKey, readJournalLimits, readReceiptRetentionDays, recommendedLimit } from './limits.ts';+import { DEFAULT_RECEIPT_RETENTION_DAYS, journalLimitKey, parseJournalConfigValue, readJournalLimits, RECEIPT_RETENTION_KEY, recommendedLimit } from './limits.ts';+import { BACKGROUND_PAUSE_KEY, backgroundPauseShare } from './admission-origin.ts';import { COMPACTED_HEADROOM_BYTES } from './receipt-bytes.ts';export const CAPACITY_WARN_DAYS_KEY = 'persistence.capacity.warn_days';@@ -69,10 +70,36 @@ export interface CapacityForecast {interface Day { scope: string; day: string; ids: number; gross: number; net: number; recent_ids: number; recent_gross: number; recent_net: number }+function daysSetting(raw: string | undefined, fallback: number): number {+ const value = raw === undefined ? fallback : Number(raw);+ return Number.isFinite(value) && value >= 0 ? value : fallback;+}+async function readDays(engine: SqlEngine, key: string, fallback: number): Promise<number> {const [row] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1', [key]);- const value = row ? Number(row.value) : fallback;- return Number.isFinite(value) && value >= 0 ? value : fallback;+ return daysSetting(row?.value, fallback);+}++export interface CapacityConfig { warnDays: number; failDays: number; retentionDays: number; pauseShare: number }++/**+ * GBRA-156: the forecast's settings and the background pause line in one statement. Sent one statement each, they widened+ * the receipt's capacity read past the connections a one-shot CLI has open, so each opened a connection of its own. An+ * unreadable retention setting keeps the default, as the forecast always treated it.+ */+export async function readCapacityConfig(engine: SqlEngine): Promise<CapacityConfig> {+ const rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key,value FROM config WHERE key = ANY($1::text[])',+ [[CAPACITY_WARN_DAYS_KEY, CAPACITY_FAIL_DAYS_KEY, RECEIPT_RETENTION_KEY, BACKGROUND_PAUSE_KEY]]);+ const value = new Map(rows.map(row => [row.key, row.value]));+ const retention = value.get(RECEIPT_RETENTION_KEY);+ let retentionDays = DEFAULT_RECEIPT_RETENTION_DAYS;+ try {+ if (retention !== undefined) retentionDays = parseJournalConfigValue(RECEIPT_RETENTION_KEY, retention);+ } catch {+ retentionDays = DEFAULT_RECEIPT_RETENTION_DAYS;+ }+ return { warnDays: daysSetting(value.get(CAPACITY_WARN_DAYS_KEY), DEFAULT_CAPACITY_WARN_DAYS), failDays: daysSetting(value.get(CAPACITY_FAIL_DAYS_KEY), DEFAULT_CAPACITY_FAIL_DAYS),+ retentionDays, pauseShare: backgroundPauseShare(value.get(BACKGROUND_PAUSE_KEY)) };}/** Rows one step of the principal-index walk reads. */@@ -116,7 +143,7 @@ export async function readCapacityThresholds(engine: SqlEngine): Promise<{ warnDreturn { warnDays, failDays };}-export async function readCapacityForecast(engine: SqlEngine & { kind?: string }, opts: { limits?: JournalLimits; light?: boolean } = {}): Promise<CapacityForecast> {+export async function readCapacityForecast(engine: SqlEngine & { kind?: string }, opts: { limits?: JournalLimits; light?: boolean; config?: Promise<CapacityConfig> } = {}): Promise<CapacityForecast> {// Every read below is independent of the others (the principal walks need only the counters), so they are issued together:// one round trip for the lot instead of one each (GBRA-133).const counterRead = engine.executeRaw<{ key: string; lifetime_ids: string; terminal_bytes: string }>(@@ -142,8 +169,8 @@ export async function readCapacityForecast(engine: SqlEngine & { kind?: string }count(*) FILTER (WHERE COALESCE(octet_length(r.intent::text),0)+octet_length(r.authority::text)>r.terminal_reservation)::text AS underFROM r LEFT JOIN e ON e.request_id=r.id GROUP BY 1`);const tableBytesRead = opts.light ? Promise.resolve(null) : engine.executeRaw<{ bytes: string }>("SELECT pg_total_relation_size('persistence_requests')::text AS bytes").then(r => Number(r[0]?.bytes), () => null);- const [limits, { warnDays, failDays }, retention, counters, principalRows, topologyRows, [historyRow], reclaim, tableBytes] = await Promise.all([- opts.limits ?? readJournalLimits(engine), readCapacityThresholds(engine), readReceiptRetentionDays(engine).catch(() => DEFAULT_RECEIPT_RETENTION_DAYS),+ const [limits, { warnDays, failDays, retentionDays: retention }, counters, principalRows, topologyRows, [historyRow], reclaim, tableBytes] = await Promise.all([+ opts.limits ?? readJournalLimits(engine), opts.config ?? readCapacityConfig(engine),counterRead, principals, topology, history, reclaimRead, tableBytesRead]);const days: Day[] = [...principalRows.flat(), ...topologyRows.map(toDay)];const windowDays = Math.min(WINDOW_DAYS, Math.max(1, Number(historyRow?.age_days ?? WINDOW_DAYS)));diff --git a/src/core/persistence/capacity-snapshot.ts b/src/core/persistence/capacity-snapshot.tsindex e7a46fa3af..9bf8cb5faa 100644--- a/src/core/persistence/capacity-snapshot.ts+++ b/src/core/persistence/capacity-snapshot.ts@@ -23,8 +23,8 @@*/import type { Notice } from '../agent-output.ts';import { principalKey, type Principal, type SqlEngine } from './model.ts';-import { BACKGROUND_PRODUCERS, readBackgroundPauseShare } from './admission-origin.ts';-import { readCapacityForecast } from './capacity-forecast.ts';+import { BACKGROUND_PRODUCERS } from './admission-origin.ts';+import { readCapacityConfig, readCapacityForecast } from './capacity-forecast.ts';import { CAPACITY_VERIFY } from './capacity-verify.ts';import { deadlineBoundEngine, deadlineFailure, engineCacheKey, withStatementDeadline } from '../statement-deadline.ts';@@ -68,8 +68,11 @@ export function cachedCapacitySnapshot(engine: SqlEngine, now: number = Date.nowconst bounded = deadlineBoundEngine(engine);const startedAt = Date.now();const fetch = withStatementDeadline({ startedAt, deadlineAt: startedAt + CAPACITY_FETCH_BOUND_MS, expired: false },- () => Promise.all([readCapacityForecast(bounded, { light: true }), readBackgroundPauseShare(bounded)]));- const value: Promise<CapacitySnapshot> = fetch.then(([forecast, share]): CapacitySnapshot => {+ () => {+ const config = readCapacityConfig(bounded);+ return Promise.all([readCapacityForecast(bounded, { light: true, config }), config]);+ });+ const value: Promise<CapacitySnapshot> = fetch.then(([forecast, { pauseShare: share }]): CapacitySnapshot => {const attention = (row: typeof forecast.rows[number]): CapacityAttention => ({ scope: row.scope, resource: row.resource, used: row.used, limit: row.limit,pct: row.pct, days_to_exhaustion: row.days_to_exhaustion, config_key: row.config_key, recommended_limit: row.recommended_limit,command: `gbrain config set ${row.config_key} ${row.recommended_limit}` });diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.tsindex 860f181226..7f4f310188 100644--- a/src/core/persistence/claim-phase.ts+++ b/src/core/persistence/claim-phase.ts@@ -134,6 +134,14 @@ export function claimOwnerKind(): string {const command = process.argv.slice(2).find(arg => !arg.startsWith('-'));return command && OWNER_COMMANDS.has(command) ? command : 'cli';}+let oneShotCommand = false;+/**+ * GBRA-156: set by the CLI's shared-operation dispatch, which runs one operation and exits. The consumer such a process+ * starts (service.ts) leaves its housekeeping off the write's path and rations it per host (housekeeping-turn.ts), and its+ * pool opens a second connection beside the first (db.ts).+ */+export function markOneShotCommand(on = true): void { oneShotCommand = on; }+export function isOneShotCommand(): boolean { return oneShotCommand; }/** The owning process for the stamp: the gbrain command this process runs (`cli` when none is recognisable), its pid, nonce, pid namespace and build. */export function claimOwner(): ClaimOwner {if (ownerOverride) return ownerOverride;diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 605d2ffa27..a25a168bc4 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -20,6 +20,7 @@ import { laneClaim, laneOf, laneRoots, laneTask } from './sync-lanes.ts';import { runPersistenceEffects } from './effects.ts';import { settleNoopEmbeddingEffects, type NoopSettleCursor } from './embedding-noop-settle.ts';import { runCompactionPass } from './compaction-pass.ts';+import { claimHousekeepingTurn, housekeepingIntervalMs } from './housekeeping-turn.ts';import { currentEmbeddingSignature } from '../embedding.ts';import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { isWriteErrorCode } from './types.ts';@@ -236,6 +237,9 @@ export class PersistenceConsumer implements PersistenceConsumerLike {private detachedBuilds = 0;private detachedQueue: Array<() => void> = [];private abandonedReleased = false;+ /** GBRA-156: when this one-shot consumer last asked for the host's housekeeping turn, and whether it holds the turn now. */+ private housekeepingAskedAt = -Infinity;+ private housekeepingTurn = false;/** #6317: the engine the tick's own statements run through (the direct route when the engine has one; consumer-lane.ts). */private readonly statements: BrainEngine;private routeLogged = false;@@ -254,7 +258,14 @@ export class PersistenceConsumer implements PersistenceConsumerLike {/** #6278: abandoned preparations past the ceiling before this process stops claiming (default DEFAULT_ZOMBIE_CAP). */zombieCap?: number;/** Write the long-drain progress line on stderr (serve; never a CLI command that may print --json). */- drainNotice?: boolean } = {}) {+ drainNotice?: boolean;+ /**+ * GBRA-156: the consumer of a one-shot command (`put`, `cli`, `import`, ...). While `waiting` says a caller in this+ * process awaits a write, it runs only what that write's claim can depend on; housekeeping (recovery and topology scans,+ * compaction, queue upkeep, the projection pass) waits until no write is awaited and then runs at most once per+ * interval across this host's processes (housekeeping-turn.ts).+ */+ oneShot?: { waiting: () => boolean } } = {}) {this.hostId = opts.hostId ?? localHostId();this.statements = consumerStatementEngine(engine);}@@ -299,6 +310,29 @@ export class PersistenceConsumer implements PersistenceConsumerLike {}, ms);this.timer.unref?.();}+ /**+ * GBRA-156: recovery, expired-claim, dead-owner and topology scans. A one-shot consumer runs them while a caller in this+ * process awaits a write that may be blocked behind them (except on the direct claim of its own admission), and otherwise+ * only in the host's housekeeping turn (housekeeping-turn.ts).+ */+ private async sweepAllowed(direct: boolean): Promise<boolean> {+ if (!this.opts.oneShot) return true;+ return this.opts.oneShot.waiting() ? !direct : this.housekeepingTurnNow();+ }+ /** GBRA-156: compaction, queue upkeep and the projection pass; a one-shot consumer runs them only in the host's housekeeping turn. */+ private async upkeepAllowed(): Promise<boolean> {+ return !this.opts.oneShot || !this.opts.oneShot.waiting() && this.housekeepingTurnNow();+ }+ /** Whether this tick holds the host's housekeeping turn; asked at most once per interval per process, granted when the claim cannot be read. */+ private async housekeepingTurnNow(): Promise<boolean> {+ if (this.housekeepingTurn) return true;+ const interval = housekeepingIntervalMs();+ if (interval === 0) return true;+ if (Date.now() - this.housekeepingAskedAt < interval) return false;+ this.housekeepingAskedAt = Date.now();+ this.housekeepingTurn = await this.phase('housekeeping_turn', signal => claimHousekeepingTurn(this.statements, this.hostId, interval, signal)).catch(() => true);+ return this.housekeepingTurn;+ }private backoff(): number {this.idleDelayMs = Math.min(Math.max(this.idleDelayMs, this.pollMs) * 2, this.idleMaxMs);return this.idleDelayMs;@@ -500,6 +534,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {}private async doTick(afterProgress: boolean): Promise<void> {if (this.stopping) return;+ this.housekeepingTurn = false;const requested = this.fullTickRequested;this.fullTickRequested = false;if (!requested) {@@ -515,11 +550,11 @@ export class PersistenceConsumer implements PersistenceConsumerLike {}if (this.stopping) return;// #6650: the idle probe sees only lapsed claims; a live-leased claim of a dead owner is looked for here, on its own cadence.- if (!work) this.deadOwnersSeen = await this.phase('dead_owner_claims', signal => this.deadOwnerClaims(signal, true));+ if (!work && await this.sweepAllowed(false)) this.deadOwnersSeen = await this.phase('dead_owner_claims', signal => this.deadOwnerClaims(signal, true));if (!work && !this.deadOwnersSeen?.length) {if (this.active.size > 0) { this.nextDelayMs = this.pollMs; return; }this.nextDelayMs = this.backoff();- if (!this.maintenanceWorker && Date.now() >= this.nextMaintenance) {+ if (!this.maintenanceWorker && Date.now() >= this.nextMaintenance && await this.upkeepAllowed()) {this.nextMaintenance = Date.now() + 300_000;await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,this.engine.kind === 'pglite' ? this.config.database_path : undefined, signal));@@ -542,7 +577,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {this.nextDelayMs = this.pollMs;const direct = afterProgress && this.ownAdmission && fast;this.ownAdmission = false;- const scan = !direct && (!afterProgress || Date.now() - this.lastScan >= this.pollMs);+ const scan = !direct && (!afterProgress || Date.now() - this.lastScan >= this.pollMs) && await this.sweepAllowed(direct);+ const upkeep = await this.upkeepAllowed();if (scan) {this.lastScan = Date.now();await this.phase('refresh_roots', signal => refreshManagedFilesystemRoots(this.engine,@@ -557,7 +593,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {.finally(() => { this.effectsWorker = undefined; });// Queue upkeep also follows publication volume, like autovacuum's scale// factor, so a busy owner never plans against a much smaller queue.- if (!this.maintenanceWorker && (Date.now() >= this.nextMaintenance || this.publishedSinceMaintenance >= this.maintenanceVolume)) {+ if (upkeep && !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 })@@ -566,7 +602,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {.then(rows => { this.maintenanceVolume = 50 + Math.ceil(rows * 0.2); }).catch(error => this.report(error)).finally(() => { this.maintenanceWorker = undefined; });}- if (!this.projectionWorker) this.projectionWorker = runResidentProjectionInvocation(this.engine, this.hostId,+ if (upkeep && !this.projectionWorker) this.projectionWorker = runResidentProjectionInvocation(this.engine, this.hostId,[...this.activeRoots, ...this.rootRetryAfter.keys()], Date.now, this.engine.kind === 'postgres'? AbortSignal.any([this.abort.signal, AbortSignal.timeout(this.opts.phaseMs ?? 5000)]) : undefined).catch(error => this.report(error)).finally(() => { this.projectionWorker = undefined; });@@ -989,6 +1025,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {return this.settled(done);} finally { this.preparing.delete(row.id); this.executing.delete(row.id); }}+ // GBRA-156: the publication ceiling (a TTL-cached config read that never rejects) is read while the write prepares.+ const ceiling = readPublicationCeilingMs(this.engine);const prep = startPreparation(async signal => {signal.addEventListener('abort', () => cancel.abort(signal.reason), { once: true });await faultPoint('consumer:preparing', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation, signal });@@ -1037,7 +1075,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {preparationActive = false;enterClaimPhase(clock, 'publishing');await faultPoint('consumer:prepared', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation });- const ceilingMs = await readPublicationCeilingMs(this.engine);+ const ceilingMs = await ceiling;await holdClaimForPublication(lease, () => renewWriteClaim({ executeRaw: this.engine.executeRawDirect.bind(this.engine) }, row.id, row.execution_token!,publicationLeaseMs(ceilingMs), undefined, claimPhaseStamp(clock, row.execution_token)));const { done, settled } = await boundPublication(() => this.publishSingle(row, prepared), this.publicationBound(row, ceilingMs, clock));diff --git a/src/core/persistence/housekeeping-turn.ts b/src/core/persistence/housekeeping-turn.tsnew file mode 100644index 0000000000..1401867642--- /dev/null+++ b/src/core/persistence/housekeeping-turn.ts@@ -0,0 +1,36 @@+/**+ * GBRA-156: one housekeeping turn per host for one-shot commands.+ *+ * A one-shot command (`gbrain put`, `gbrain remember`, any shared operation the CLI runs once and exits) starts a full+ * consumer to publish its own write. The consumer's housekeeping (recovery and expired-claim scans, dead-owner and topology+ * recovery, compaction and queue upkeep, the resident projection pass) is not what that write waits on, and it held the+ * process open after the reply on every command. Many brains have no resident process, so these commands are also the only+ * thing that runs it: it is rationed, not removed. After no caller in the process awaits a write, the consumer asks for the+ * host's turn; the turn is granted at most once per `GBRAIN_ONESHOT_HOUSEKEEPING_INTERVAL_MS` (default 5 minutes) across+ * this host's processes (an atomic claim on one op_checkpoints row, op `consumer-housekeeping`, fingerprint the host id),+ * and never while a resident full consumer on the host is live, because that one already runs the same scans. The scans a+ * waiting write may be blocked behind still run at once (consumer.ts `sweepAllowed`).+ */+import type { SqlEngine } from './model.ts';+import { CONSUMER_LIVE_MS, RESIDENT_CONSUMER_KINDS } from './consumer-heartbeat.ts';++export const HOUSEKEEPING_TURN_OP = 'consumer-housekeeping';+export const HOUSEKEEPING_INTERVAL_MS_DEFAULT = 300_000;++export function housekeepingIntervalMs(env: Record<string, string | undefined> = process.env): number {+ const raw = env.GBRAIN_ONESHOT_HOUSEKEEPING_INTERVAL_MS;+ const value = raw === undefined || raw === '' ? NaN : Number(raw);+ return Number.isFinite(value) && value >= 0 ? Math.floor(value) : HOUSEKEEPING_INTERVAL_MS_DEFAULT;+}++/** Claims the host's housekeeping turn: true when no turn was taken within `intervalMs` and no resident full consumer of the host is live. */+export async function claimHousekeepingTurn(engine: SqlEngine, hostId: string, intervalMs: number, signal?: AbortSignal): Promise<boolean> {+ const [row] = await engine.executeRaw<{ claimed: boolean }>(`WITH claim AS (+ INSERT INTO op_checkpoints (op, fingerprint, completed_keys, updated_at)+ SELECT $1::text, $2::text, '[]'::jsonb, now() WHERE NOT EXISTS (SELECT 1 FROM persistence_consumers WHERE host_id=$2::text::uuid+ AND kind=ANY($4::text[]) AND mode IN ('full','promoted') AND renewed_at > now() - ($5::integer * interval '1 millisecond'))+ ON CONFLICT (op, fingerprint) DO UPDATE SET updated_at=now()+ WHERE op_checkpoints.updated_at <= now() - ($3::bigint * interval '1 millisecond') RETURNING 1)+ SELECT EXISTS (SELECT 1 FROM claim) AS claimed`, [HOUSEKEEPING_TURN_OP, hostId, intervalMs, [...RESIDENT_CONSUMER_KINDS], CONSUMER_LIVE_MS], { signal });+ return row?.claimed === true;+}diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 57b1dd2e44..d164d3aed9 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -6,7 +6,7 @@ import { LANE_BUSY, PersistenceConsumer, type PersistenceConsumerLike, type Prepimport { WaiterOnlyConsumer, type ElectedOwner } from './consumer-election.ts';import { RESIDENT_CONSUMER_KINDS, startConsumerHeartbeat, type ConsumerHeartbeat } from './consumer-heartbeat.ts';import { enginePoolStats } from '../postgres-engine/pool-stats.ts';-import { claimOwnerKind } from './claim-phase.ts';+import { claimOwnerKind, isOneShotCommand } from './claim-phase.ts';import { preparePageMutation } from './page-prepare.ts';import { prepareSemanticPageMutation } from './semantic-pages.ts';import { getWriteRequestById, getWriteRequestProgress, receiptFor, type WriteRequestProgress } from './journal.ts';@@ -123,9 +123,10 @@ export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConf}return prior.consumer;}- const full = () => new PersistenceConsumer(engine, config, preparePersistedMutation,- { drainNotice: claimOwnerKind() === 'serve', onSettled: row => { recordSettlement(engine); rememberSettled(engine, row.id); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });const kind = claimOwnerKind();+ const oneShot = isOneShotCommand() && kind !== 'serve' && !RESIDENT_CONSUMER_KINDS.includes(kind) ? { waiting: () => (settledWaiters.get(engine)?.size ?? 0) > 0 } : undefined;+ const full = () => new PersistenceConsumer(engine, config, preparePersistedMutation,+ { drainNotice: kind === 'serve', oneShot, onSettled: row => { recordSettlement(engine); rememberSettled(engine, row.id); for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });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 }: (() => { const consumer = full(); return { consumer, stopping: false, heartbeat: startConsumerHeartbeat(engine, consumer.hostId,diff --git a/src/core/persistence/switches.ts b/src/core/persistence/switches.tsindex f4e22bf08a..7a12a0bc36 100644--- a/src/core/persistence/switches.ts+++ b/src/core/persistence/switches.ts@@ -81,6 +81,16 @@ export function readWriteSwitchSnapshot(viewed: SqlEngine, opts: { now?: () => nread.catch(() => { if (snapshots.get(engine)?.read === read) snapshots.delete(engine); });return read;}+/**+ * GBRA-156: a whole-table config read this process just took (the CLI's connect-time merge) is the switch snapshot as of+ * that read, kept for SWITCH_TTL_MS like any other; a snapshot already held is left alone.+ */+export function seedWriteSwitchSnapshot(viewed: object, rows: Record<string, string>, now: number = Date.now()): void {+ const engine = viewedEngine(viewed);+ const held = snapshots.get(engine);+ if (held && held.generation === generation && now - held.at < SWITCH_TTL_MS) return;+ snapshots.set(engine, { at: now, generation, read: Promise.resolve(resolve(new Map(Object.entries(rows)))) });+}/** The preparation budgets in effect (defaults when the read fails). */export async function readPreparationPolicy(engine: SqlEngine): Promise<PreparationPolicy> {return readWriteSwitchSnapshot(engine).then(snapshot => snapshot.preparation, () => ({ ...DEFAULT_PREPARATION_POLICY }));diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 066d197824..251167b7dc 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1317,7 +1317,7 @@ export class PGLiteEngine implements BrainEngine {mode: string,corpusGeneration: string | null,): Promise<void> {- return pagesImpl.updatePageContextualRetrievalState(this.engineSql, slug, sourceId, mode, corpusGeneration);+ return pagesImpl.updatePageContextualRetrievalState(this.engineSql, slug, sourceId, mode, corpusGeneration, (key, read) => transactionMemo(this, key, read));}async migrateFactsToCanonical(diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex b1043d5d20..14f5ae7734 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -890,7 +890,7 @@ export class PostgresEngine implements BrainEngine {mode: string,corpusGeneration: string | null,): Promise<void> {- return pagesImpl.updatePageContextualRetrievalState(this.engineSql, slug, sourceId, mode, corpusGeneration);+ return pagesImpl.updatePageContextualRetrievalState(this.engineSql, slug, sourceId, mode, corpusGeneration, (key, read) => transactionMemo(this, key, read));}async migrateFactsToCanonical(diff --git a/test/e2e/write-roundtrips-gbra156-postgres.test.ts b/test/e2e/write-roundtrips-gbra156-postgres.test.tsnew file mode 100644index 0000000000..3e1b26decf--- /dev/null+++ b/test/e2e/write-roundtrips-gbra156-postgres.test.ts@@ -0,0 +1,71 @@+/**+ * GBRA-156, Postgres arm: the statements of a page transaction and the connections a one-shot CLI command opens.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import postgres from '#postgres';+import { connect, disconnect } from '../../src/core/db.ts';+import { markOneShotCommand } from '../../src/core/persistence/claim-phase.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { hasDatabase } from './helpers.ts';+import { withEnv } from '../helpers/with-env.ts';++type Traced = { sql: string; kind: string; conn: number; t: number };+const traced = (file: string): Traced[] => readFileSync(file, 'utf8').trim().split('\n').map(line => JSON.parse(line) as Traced)+ .map(record => ({ ...record, sql: record.sql.replace(/\s+/g, ' ').trim() }));++const d = hasDatabase() ? describe : describe.skip;+d('GBRA-156 one-shot write (Postgres)', () => {+ let scratch: string;+ beforeAll(() => { scratch = mkdtempSync(join(tmpdir(), 'gbrain-gbra156-')); });+ afterAll(() => { markOneShotCommand(false); rmSync(scratch, { recursive: true, force: true }); });++ for (const oneShot of [true, false]) test(`the module pool opens ${oneShot ? 'a second connection beside the first for a one-shot command' : 'one connection for any other process'}`, async () => {+ const application = `gbra156-${randomUUID().slice(0, 8)}`;+ const url = new URL(process.env.DATABASE_URL!);+ url.searchParams.set('application_name', application);+ const admin = postgres(process.env.DATABASE_URL!, { max: 1 });+ markOneShotCommand(oneShot);+ try {+ await connect({ engine: 'postgres', database_url: url.toString() } as never);+ let open = 0;+ for (let i = 0; i < 40; i++) {+ [{ open }] = await admin<{ open: number }[]>`SELECT count(*)::int AS open FROM pg_stat_activity WHERE application_name=${application}`;+ if (open >= 2) break;+ await Bun.sleep(25);+ }+ expect(open).toBe(oneShot ? 2 : 1);+ } finally {+ markOneShotCommand(false);+ await disconnect();+ await admin.end();+ }+ }, 60_000);++ test('a page transaction that stamps the keyless contextual state and writes chunks reads the embedding write target once', async () => {+ const trace = join(scratch, 'page-transaction.jsonl');+ let window: [number, number] = [0, 0];+ await withEnv({ GBRAIN_SQL_TRACE: trace, GBRAIN_SQL_TRACE_LABEL: 'gbra156-page-tx', GBRAIN_HOME: join(scratch, 'home') }, async () => {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ try {+ await pg.engine.putPage('notes/gbra156', { type: 'note', title: 'GBRA-156', compiled_truth: 'Body text.' }, { sourceId: 'default' });+ await Bun.sleep(50);+ const started = performance.timeOrigin + performance.now();+ await pg.engine.transaction(async tx => {+ await tx.updatePageContextualRetrievalState('notes/gbra156', 'default', 'none', null);+ await tx.upsertChunks('notes/gbra156', [{ chunk_index: 0, chunk_text: 'Body text.', chunk_source: 'compiled_truth' }], { sourceId: 'default' });+ });+ window = [started, performance.timeOrigin + performance.now()];+ } finally {+ await pg.close();+ }+ });+ await Bun.sleep(1300);+ const reads = traced(trace).filter(record => record.t >= window[0] && record.t <= window[1]+ && /^SELECT key, ?value FROM config WHERE key IN \('search_embedding_column'/.test(record.sql));+ expect(reads.map(record => record.sql)).toHaveLength(1);+ }, 120_000);+});diff --git a/test/write-roundtrips-gbra156.test.ts b/test/write-roundtrips-gbra156.test.tsnew file mode 100644index 0000000000..a4033c1ff5--- /dev/null+++ b/test/write-roundtrips-gbra156.test.ts@@ -0,0 +1,171 @@+/**+ * GBRA-156: the reads a one-shot CLI write sends behind a transaction pooler. Each case counts the statements a step sends+ * (and the waves they form) and keeps the result the step returned before. Both backends.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { readCapacityForecast } from '../src/core/persistence/capacity-forecast.ts';+import { cachedCapacitySnapshot } from '../src/core/persistence/capacity-snapshot.ts';+import { randomUUID } from 'node:crypto';+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';+import { claimHousekeepingTurn, HOUSEKEEPING_TURN_OP } from '../src/core/persistence/housekeeping-turn.ts';+import { markOneShotCommand } from '../src/core/persistence/claim-phase.ts';+import { disposePersistenceConsumer, startPersistenceConsumer } from '../src/core/persistence/service.ts';+import { readWriteSwitchSnapshot, resetWriteSwitches } from '../src/core/persistence/switches.ts';+import { commandStartupConfig, keepCommandStartupConfig, requestConfigValue, withRequestConfigSnapshot } from '../src/core/config-snapshot.ts';+import { mergeDbPlaneConfig } from '../src/cli/db-plane-config.ts';+import { withEnv } from './helpers/with-env.ts';+import { freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';+import { testBackends } from './helpers/test-backends.ts';++async function recordStatements<T>(engine: BrainEngine, fn: () => Promise<T>): Promise<{ result: T; waves: number; statements: string[] }> {+ let inFlight = 0;+ let waves = 0;+ const statements: string[] = [];+ const target = engine as unknown as Record<string, (...args: unknown[]) => Promise<unknown>>;+ const original = target.executeRaw!;+ target.executeRaw = function (this: unknown, ...args: unknown[]) {+ if (inFlight === 0) waves++;+ inFlight++;+ statements.push(String(args[0]).replace(/\s+/g, ' ').trim());+ return original.apply(this, args).finally(() => { inFlight--; });+ };+ try {+ return { result: await fn(), waves, statements };+ } finally {+ delete target.executeRaw;+ }+}++const configReads = (statements: string[]) => statements.filter(s => /FROM config\b/.test(s));++type Gate = { upkeepAllowed(): Promise<boolean>; sweepAllowed(direct: boolean): Promise<boolean>; housekeepingTurn: boolean };+const oneShotConsumer = (engine: BrainEngine, hostId: string, waiting: () => boolean) => new PersistenceConsumer(engine, { engine: engine.kind } as never,+ async () => { throw new Error('unused'); }, { hostId, oneShot: { waiting } }) as unknown as Gate;+const turns = async (engine: BrainEngine, hostId: string) => (await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [HOUSEKEEPING_TURN_OP, hostId]))[0]!.n;++describe('GBRA-156 command startup config', () => {+ test('a seeded request snapshot answers from the seed without a table read', async () => {+ let bulk = 0;+ const engine = { getConfig: async () => 'live', getAllConfig: async () => { bulk++; return { k: 'live' }; } };+ const value = await withRequestConfigSnapshot(engine, () => requestConfigValue(engine, 'k'), { k: 'seeded' });+ expect(value).toBe('seeded');+ expect(bulk).toBe(0);+ });++ test('the startup read is handed over once, and not when it is older than its window', () => {+ const engine = {};+ keepCommandStartupConfig(engine, { k: 'v' }, 1_000);+ expect(commandStartupConfig(engine, 2_000)).toEqual({ k: 'v' });+ expect(commandStartupConfig(engine, 2_000)).toBeUndefined();+ keepCommandStartupConfig(engine, { k: 'v' }, 1_000);+ expect(commandStartupConfig(engine, 7_000)).toBeUndefined();+ });+});++for (const kind of testBackends()) {+ describe('GBRA-156 write round trips (' + kind + ')', () => {+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;+ beforeAll(async () => { factory = await freshBrainFactory(kind, process.env.DATABASE_URL); }, 120_000);+ afterAll(async () => { await factory?.dispose(); });++ test('the receipt capacity snapshot reads its config keys in one statement beside the journal limits', async () => {+ const engine = await factory.fresh();+ const requests = await requestFixture(engine);+ await requests.admit('gbra156-capacity');+ await engine.executeRaw(`INSERT INTO config(key,value) VALUES ('persistence.capacity.warn_days','11'),('persistence.capacity.fail_days','3'),+ ('persistence.receipt_retention_days','9'),('persistence.capacity.background_pause_pct','60')+ ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value`);+ const { result, statements } = await recordStatements(engine, () => cachedCapacitySnapshot(engine, Date.now() + 1e9));+ expect(configReads(statements)).toHaveLength(2);+ expect(result.status).toBe('ok');+ expect(result.pause_pct).toBe(60);+ const forecast = await readCapacityForecast(engine, { light: true });+ expect(forecast.thresholds).toMatchObject({ warn_days: 11, fail_days: 3 });+ expect(forecast.retention_days).toBe(9);+ }, 120_000);++ test('the connect-time config merge seeds the write switches and hands its read to the command', async () => {+ const engine = await factory.fresh();+ resetWriteSwitches();+ await mergeDbPlaneConfig(engine, { engine: engine.kind } as never, new WeakMap());+ const { statements } = await recordStatements(engine, () => readWriteSwitchSnapshot(engine));+ expect(statements).toEqual([]);+ expect(commandStartupConfig(engine)).toBeDefined();+ }, 120_000);++ test('the host housekeeping turn is granted once per interval per host', async () => {+ const engine = await factory.fresh();+ const host = randomUUID();+ expect(await claimHousekeepingTurn(engine, host, 60_000)).toBe(true);+ expect(await claimHousekeepingTurn(engine, host, 60_000)).toBe(false);+ expect(await claimHousekeepingTurn(engine, randomUUID(), 60_000)).toBe(true);+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now()-interval '2 minutes' WHERE op=$1 AND fingerprint=$2", [HOUSEKEEPING_TURN_OP, host]);+ expect(await claimHousekeepingTurn(engine, host, 60_000)).toBe(true);+ }, 120_000);++ test('no housekeeping turn while a resident full consumer of the host is live', async () => {+ const engine = await factory.fresh();+ const host = randomUUID();+ await engine.executeRaw(`INSERT INTO persistence_consumers (host_id,pid,nonce,kind,mode,host_json_path,persistence_home,version)+ VALUES ($1::uuid,4242,'n','serve','full','/h.json','/home','0')`, [host]);+ expect(await claimHousekeepingTurn(engine, host, 60_000)).toBe(false);+ await engine.executeRaw("UPDATE persistence_consumers SET renewed_at=now()-interval '10 minutes' WHERE host_id=$1::uuid", [host]);+ expect(await claimHousekeepingTurn(engine, host, 60_000)).toBe(true);+ }, 120_000);++ test('a one-shot consumer keeps upkeep off while a write is awaited, and the direct claim of its own write sweeps nothing', async () => {+ const engine = await factory.fresh();+ const host = randomUUID();+ const consumer = oneShotConsumer(engine, host, () => true);+ expect(await consumer.upkeepAllowed()).toBe(false);+ expect(await consumer.sweepAllowed(true)).toBe(false);+ expect(await consumer.sweepAllowed(false)).toBe(true);+ expect(await turns(engine, host)).toBe(0);+ }, 120_000);++ test('after the write, one one-shot consumer per host and interval takes the housekeeping turn', async () => {+ const engine = await factory.fresh();+ const host = randomUUID();+ const first = oneShotConsumer(engine, host, () => false);+ expect(await first.upkeepAllowed()).toBe(true);+ expect(await first.sweepAllowed(false)).toBe(true);+ expect(await turns(engine, host)).toBe(1);+ const second = oneShotConsumer(engine, host, () => false);+ expect(await second.upkeepAllowed()).toBe(false);+ expect(await second.sweepAllowed(false)).toBe(false);+ first.housekeepingTurn = false;+ expect(await first.upkeepAllowed()).toBe(false);+ await withEnv({ GBRAIN_ONESHOT_HOUSEKEEPING_INTERVAL_MS: '0' }, async () => {+ expect(await oneShotConsumer(engine, host, () => false).upkeepAllowed()).toBe(true);+ });+ const resident = new PersistenceConsumer(engine, { engine: engine.kind } as never, async () => { throw new Error('unused'); }, { hostId: host }) as unknown as Gate;+ expect(await resident.upkeepAllowed()).toBe(true);+ expect(await resident.sweepAllowed(true)).toBe(true);+ }, 120_000);++ test('only a one-shot command starts its consumer with the housekeeping ration', async () => {+ for (const oneShot of [true, false]) {+ const engine = await factory.fresh();+ markOneShotCommand(oneShot);+ try {+ const consumer = startPersistenceConsumer(engine, { engine: engine.kind } as never) as unknown as { opts: { oneShot?: unknown } };+ expect(consumer.opts.oneShot !== undefined).toBe(oneShot);+ } finally {+ markOneShotCommand(false);+ await disposePersistenceConsumer(engine);+ }+ }+ }, 120_000);++ test('an unreadable retention setting still falls back to the default, and bad thresholds to theirs', async () => {+ const engine = await factory.fresh();+ await engine.executeRaw(`INSERT INTO config(key,value) VALUES ('persistence.capacity.warn_days','-1'),('persistence.receipt_retention_days','soon')+ ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value`);+ const forecast = await readCapacityForecast(engine, { light: true });+ expect(forecast.thresholds.warn_days).toBe(30);+ expect(forecast.retention_days).toBe(30);+ }, 120_000);+ });+}