Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(sync): a waiver run's screens share one bounded-read session; session reads are prepared (GBRA-75 wave 9)

time-attackc404ab304c90
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index 303432de93..fc498cb79d 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -21,7 +21,7 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/persistence/claim-phase.ts` — #6176 / #6278: the phase and step a running write request's claim is in. `startClaimPhase`/`enterClaimPhase` keep a per-claim `ClaimPhaseClock` in the consumer (single and group routes); `claimPhaseStamp` is the jsonb every claim, renewal and group dispatch mark stores in `persistence_requests.claim_phase` (v217): phase `preparing` or `publishing`, claim start, phase start, the execution token (so a later claim never reads an earlier claim's ages), the `step` in flight and when it began, `waiting_on` and the owning process (`owner`: command kind, pid, gbrain build). Preparers (`sync-prepare.ts`, `page-prepare.ts`, `prepared-maintenance.ts`, link resolution) call `enterClaimStep(clock, step, signal, waitingOn)` at each await boundary: it names the step, records what the await waits on (`git`, `fs`, `db`, `pool`, else `unknown`: set only where observed, never inferred) and throws the preparation's abort reason, so cancellation reaches a preparer between its queries even though the queries take no signal. `claimStateOf` reads a row back from the current claim's stamp only: `preparing`/`publishing` (live renewal), `publication_transaction` (claim lapsed while running, read on the database clock: a transaction holds the row or the owner is gone; requeued once it ends), `file_publication` (`publication_started`; recovery finishes it) or `unrecorded`, with claim and phase ages, `step`, `step_age_ms`, `waiting_on`, `owner`, `resumes_on_its_own` and a `why`. `claimStall` is the `preparation_overdue` verdict (`claim.stall`) for a preparing claim past its budget. `EXPIRED_PREPARING_CHARGE_SQL` is the one rule an expired-claim reclaim charges a preparation attempt by: only a claim stamped `preparing` under the token being reclaimed. `persistence.max_claim_ms` (default 600000, 60000 to 86400000; `validateMaxClaimConfigValue` is `config set`'s `invalid_params` refusal) is doctor `persistence_write_stall`'s threshold. Consumer and group-publish store the stamp on every renewal, so writer status (`diagnostics.ts`, `claim` on each running blocker, never the token) and doctor name a stuck phase and step without an extra statement per write. Tests: `test/persistence-write-stall.test.ts`, `test/persistence-claim-step.test.ts`.
- `src/core/persistence/preparation-budget.ts` + `src/commands/config/preparation-keys.ts` — #6278: how long a claimed write may prepare and how many cut-offs it survives. `preparationKind` sorts a request into `foreground` (`remember`, and `put_page`/`edit_page` with no internal intent: the consumer's 30 s `preparationMs`), `sync` (`managed_sync_*` kinds: `persistence.sync_preparation_ms`, default 120000) or `maintenance` (every other kind: `persistence.maintenance_preparation_ms`, default 120000). `persistence.preparation_ceiling_ms` (default 600000, 60000 to 3600000, floored at the larger budget plus 30 s) is the hard ceiling for a preparation that ignores cancellation and `persistence.max_preparation_attempts` (default 2, 1 to 10) the cut-offs before a request finishes `preparation_stalled`; a missing or out-of-range value keeps its default (`resolvePreparationPolicy`). The four keys ride the write-switch snapshot (`switches.ts`, one statement, 5 s TTL) together with the `preparation_deadlines` kill switch, so a claim never reads config on its own. `startPreparation` runs a preparer under its budget and the budget wins the race even when the preparer ignores its signal (the signal aborts with `{ code: 'preparation_deadline' }`; a result that lands after the budget on the clock still reads as a deadline; the late result is the caller's to drop); `racePreparation` is its outcome-only form for the sync's out-of-consumer preparations (`sync-waivers.ts`). `validatePreparationConfigValue` is `config set`'s structured refusal (each key's range, and the ceiling rule across the sibling keys; usage error exit 2, nothing written), wired in by `refuseInvalidPreparationValue`. `persistence.max_claim_ms` keeps its doctor meaning. Tests: `test/persistence-preparation-budget.test.ts`.
-- `src/core/persistence/bounded-reads.ts` — #6278 (plan item 1.4): a preparation read that can wait on a relation lock ends at the budget on the server. Phase 0 (`docs/eval/managed-sync-stall-repro.md`) showed that through a transaction-mode pooler gbrain's `statement_timeout` startup parameter is dropped, so a preparation read outside the publication transaction had no server-side bound; an `ACCESS EXCLUSIVE` lock on `pages` held elsewhere pinned the member's origin check and its connection until the lock lifted, and with the budget alone the released member's statement kept running as a zombie that blocked its root until the ceiling. `boundedReads(engine, clock)` is the engine view every preparer reads through (`prepareManagedSyncMutation` and its helpers, `preparePageMutation`, `prepareFactFenceAdoption`, the sync's out-of-consumer preparations): each unmemoized raw statement runs with `executeRaw`'s `timeoutMs` set to the clock's remaining budget (`ClaimPhaseClock.deadlineAt`, set by `startClaimPhase(now, signal, budgetMs)`) and the clock's signal, which ends only the wait for a free connection. On Postgres `timeoutMs` runs the statement on a reserved connection as `BEGIN; SET LOCAL statement_timeout; <statement>; COMMIT` in one pipelined round trip, so the bound holds through the pooler and `SET LOCAL` ends with it; inside a transaction and on PGLite the option is ignored. A statement the server ends (57014, or a 55P03 raised by a shorter session `lock_timeout`) surfaces as the member's own `preparation_deadline` (`PreparationDeadlineError`, or the signal's reason once it aborted), which `preparationAbortReason` classifies as the deadline: the consumer and the group route handle it as the deadline even inside the budget (charged release, `preparation_stalled` at the limit, the group cut like the timer), never as a `storage_error` receipt or an uncharged release. The memo rule holds: `preparationReads` answers a bounded read once with the member's bound and signal dropped. Engine helpers that bypass `executeRaw` (`readPageSnapshot`, the import pipeline) stay under the consumer's race and the ceiling. Tests: `test/persistence-bounded-reads.test.ts`, `test/e2e/persistence-preparation-lock-wait-postgres.test.ts` (a real lock held in another session), the server-ended cases in `test/persistence-consumer-scheduling.test.ts` and `test/e2e/persistence-group-deadline-postgres.test.ts`. GBRA-75 wave 9: `withBoundedReadSession` gives a waiver screen (`unchangedSyncImport`) one reserved ordinary-pool connection (a long-hold permit; none left, or PGLite, runs the screen as before) on which its bounded reads share one transaction: `BEGIN; SET LOCAL statement_timeout` once, `COMMIT` when the screen settles. The bound stays per statement on the server: it is set again in the read's pipeline once the bound in force outlasts the read's own by more than `BOUNDED_SESSION_SLACK_MS` (25 ms). A failed read rolls back and the reads it aborted (25P02) run again in a new transaction; a read after the screen settled takes the per-read path. Test: `test/persistence-bounded-read-session.test.ts` (real lock wait and no remaining statement on Postgres).
+- `src/core/persistence/bounded-reads.ts` — #6278 (plan item 1.4): a preparation read that can wait on a relation lock ends at the budget on the server. Phase 0 (`docs/eval/managed-sync-stall-repro.md`) showed that through a transaction-mode pooler gbrain's `statement_timeout` startup parameter is dropped, so a preparation read outside the publication transaction had no server-side bound; an `ACCESS EXCLUSIVE` lock on `pages` held elsewhere pinned the member's origin check and its connection until the lock lifted, and with the budget alone the released member's statement kept running as a zombie that blocked its root until the ceiling. `boundedReads(engine, clock)` is the engine view every preparer reads through (`prepareManagedSyncMutation` and its helpers, `preparePageMutation`, `prepareFactFenceAdoption`, the sync's out-of-consumer preparations): each unmemoized raw statement runs with `executeRaw`'s `timeoutMs` set to the clock's remaining budget (`ClaimPhaseClock.deadlineAt`, set by `startClaimPhase(now, signal, budgetMs)`) and the clock's signal, which ends only the wait for a free connection. On Postgres `timeoutMs` runs the statement on a reserved connection as `BEGIN; SET LOCAL statement_timeout; <statement>; COMMIT` in one pipelined round trip, so the bound holds through the pooler and `SET LOCAL` ends with it; inside a transaction and on PGLite the option is ignored. A statement the server ends (57014, or a 55P03 raised by a shorter session `lock_timeout`) surfaces as the member's own `preparation_deadline` (`PreparationDeadlineError`, or the signal's reason once it aborted), which `preparationAbortReason` classifies as the deadline: the consumer and the group route handle it as the deadline even inside the budget (charged release, `preparation_stalled` at the limit, the group cut like the timer), never as a `storage_error` receipt or an uncharged release. The memo rule holds: `preparationReads` answers a bounded read once with the member's bound and signal dropped. Engine helpers that bypass `executeRaw` (`readPageSnapshot`, the import pipeline) stay under the consumer's race and the ceiling. Tests: `test/persistence-bounded-reads.test.ts`, `test/e2e/persistence-preparation-lock-wait-postgres.test.ts` (a real lock held in another session), the server-ended cases in `test/persistence-consumer-scheduling.test.ts` and `test/e2e/persistence-group-deadline-postgres.test.ts`. GBRA-75 wave 9: `withBoundedReadSession` gives a waiver screen (`unchangedSyncImport`) one reserved ordinary-pool connection (a long-hold permit; none left, or PGLite, runs the screen as before) on which its bounded reads share one transaction: `BEGIN; SET LOCAL statement_timeout` once, `COMMIT` when the screen settles. The bound stays per statement on the server: it is set again in the read's pipeline once the bound in force differs from the read's own by more than `BOUNDED_SESSION_SLACK_MS` (25 ms). A waiver run (`waiveRun` in `sync-run.ts`) opens one session for all its screens, and a screen inside it joins it. Session reads are named prepared statements (`ReservedConnection.executeRaw` `prepare`, ANDed with the connection option as `runUnsafe` does). A failed read rolls back and the reads it aborted (25P02) run again in a new transaction; a read after the screen settled takes the per-read path. Test: `test/persistence-bounded-read-session.test.ts` (real lock wait and no remaining statement on Postgres).
- `src/core/persistence/owner-refusal.ts` — #6278: the `owner_unavailable` reasons matrix. `checkOwner(binding, incarnation, hostId)` names the first failing condition in a fixed order (`binding_missing`, `incarnation_changed`, `host_mismatch`, `transfer_in_progress` for a `draining` worktree, `clone_in_progress` for `recovering`, `local_path_missing`, `coordination_path_missing`) or returns the usable `ActiveOwnerBinding`; `ownerRefusal` gives each reason its message, `why`, actor, fix (always the read-only `gbrain sources writer status --source <id> --json`, with the same verify; `actor: provider` so the two in-progress reasons render `next: wait` with a 30 s delay, `host_admin` for the rest) and `retryable` (`host_mismatch` false at the site, carried by `OperationError.retryable`); `ownerUnavailableError` is the thrown form. `host_mismatch` prints both host ids' first 8 characters and, when `remote` is false, the `host.json` path this process read; nothing here claims or transfers ownership. Used by `maintenancePreflight`, `loadFenceSource` and `managedRepairRoot`; the registry's `owner_unavailable.reasons` and the `FENCE_REASONS` owner entries carry the same vocabulary. Tests: `test/owner-refusal.test.ts` (matrix, every preflight condition on a claimed worktree, the HTTP envelope without a local path), `test/fence-repair-reasons.test.ts`.
- `src/core/persistence/repair-busy.ts` — #6278: the busy set a repair must not write while a managed sync runs. `loadRepairBusySet(engine, sourceId, incarnation)` returns the paths and slugs named by queued, running and recovering requests and terminal rows with an open recovery (both rename endpoints included) plus, for every unfinished `managed-sync` cursor of the incarnation, the entries of its frozen `managed-sync-manifest` from the cursor's index on (a path with a `sync-hold` record is left out: the sync retries a held file only when its bytes change); it never throws and fails closed (`unknown` set, so `repairBusy` answers true for everything) when a query fails or a cursor's manifest is missing. `repairBusyMessage` is the hold text, `repairBusyError` the `sync_in_progress` refusal (`reason` `candidate_in_flight` or `busy_set_unreadable`) `submitManagedFileRepair` raises at admission. Tests: `test/repair-busy.test.ts`, `test/repair-fences.test.ts`, `test/repair-fences-during-catchup.test.ts` (Postgres: `test/e2e/repair-fences-during-catchup-postgres.test.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. 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. 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 (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 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/persistence-consumer-scheduling.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`).
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 52287e4c06..539452de60 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -227,7 +227,7 @@ export interface ReservedConnection {
executeRaw<T = Record<string, unknown>>(
sql: string,
params?: unknown[],
- opts?: { signal?: AbortSignal },
+ opts?: { signal?: AbortSignal; prepare?: boolean },
): Promise<T[]>;
}
diff --git a/src/core/persistence/bounded-reads.ts b/src/core/persistence/bounded-reads.ts
index c45e98846b..18d1c097d1 100644
--- a/src/core/persistence/bounded-reads.ts
+++ b/src/core/persistence/bounded-reads.ts
@@ -83,22 +83,23 @@ export function boundedReads(engine: BrainEngine, clock: ClaimPhaseClock | undef
} }), viewedEngine(engine));
}
-/** How far past its own bound a session statement may run before the session sets `statement_timeout` again. */
+/** How far a session statement's bound may differ from its own before the session sets `statement_timeout` again. */
export const BOUNDED_SESSION_SLACK_MS = 25;
/**
* GBRA-75 wave 9: runs `fn` with a view of `engine` whose bounded raw reads (`executeRaw` with `timeoutMs`, which
* `boundedReads` issues) share one transaction on one reserved ordinary-pool connection: `BEGIN` and
* `SET LOCAL statement_timeout` once, then each read, then `COMMIT` when `fn` settles, instead of a
* `BEGIN; SET LOCAL; read; COMMIT` per read. The bound stays per statement and server-side: before a read whose own
- * bound is more than BOUNDED_SESSION_SLACK_MS shorter than the one in force, the session sets it again in the same
- * pipeline, so a statement waiting on a relation lock still ends on the server at the budget (within the slack).
+ * bound differs from the one in force by more than BOUNDED_SESSION_SLACK_MS, the session sets it again in the same
+ * pipeline, so a statement waiting on a relation lock still ends on the server at its budget (within the slack).
* A read that fails ends the transaction (a rollback); reads the failure aborted (25P02) run again in a new one,
* so each read sees the outcome it would have alone. A read issued after `fn` settled, by a preparation the
* caller abandoned, takes the per-read path. Unbounded statements and everything else go to `engine`. On PGLite,
- * or when the pool has no long-hold capacity left, `fn` gets `engine` itself.
+ * or when the pool has no long-hold capacity left, `fn` gets `engine` itself; inside a session (a waiver run's,
+ * sync-run.ts `waiveRun`), `fn` joins it.
*/
export async function withBoundedReadSession<T>(engine: BrainEngine, fn: (engine: BrainEngine) => Promise<T>): Promise<T> {
- if (engine.kind !== 'postgres') return fn(engine);
+ if (engine.kind !== 'postgres' || sessionViews.has(engine)) return fn(engine);
let started = false;
try {
return await engine.withReservedConnection(async conn => {
@@ -112,6 +113,8 @@ export async function withBoundedReadSession<T>(engine: BrainEngine, fn: (engine
}
}
+/** Views a session hands out: a screen run inside a waiver run's session joins it instead of opening its own. */
+const sessionViews = new WeakSet<object>();
class BoundedReadSession {
readonly view: BrainEngine;
private open = false;
@@ -125,6 +128,7 @@ class BoundedReadSession {
const value = Reflect.get(target, key, target);
return typeof value === 'function' ? value.bind(target) : value;
} }), viewedEngine(engine));
+ sessionViews.add(this.view);
}
private async run<T>(sql: string, params: unknown[] | undefined, timeoutMs: number, retries: number): Promise<T[]> {
@@ -137,11 +141,11 @@ class BoundedReadSession {
steps.push(this.conn.executeRaw('BEGIN'));
steps.push(this.conn.executeRaw(`SET LOCAL statement_timeout = ${ms}`));
this.boundMs = ms;
- } else if (this.boundMs > ms + BOUNDED_SESSION_SLACK_MS || this.boundMs < ms) {
+ } else if (Math.abs(this.boundMs - ms) > BOUNDED_SESSION_SLACK_MS) {
steps.push(this.conn.executeRaw(`SET LOCAL statement_timeout = ${ms}`));
this.boundMs = ms;
}
- const read = this.conn.executeRaw<T>(sql, params);
+ const read = this.conn.executeRaw<T>(sql, params, { prepare: true });
const settled = await Promise.allSettled([...steps, read]);
const failed = settled.find((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected');
if (!failed) return (settled[settled.length - 1] as PromiseFulfilledResult<T[]>).value;
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index fd618efbc4..db50ef68f5 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -52,6 +52,7 @@ import { principalAttribution } from './attribution.ts';
import { recordSyncRunTrend } from '../fence-repair/census-store.ts';
import { addFencesNormalized, addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, heldGitPaths, fencesNormalizedReport, holdsEscalated, readGitHoldRetryPaths, readGitSourceHolds, readSyncHoldPolicy, recordSyncConversion, recoveredReport, requestGitHoldRetry, writeGitHold, type FencesTally, type SyncHoldPolicy } from './sync-holds.ts';
import { withScreeningPaths } from './screening-paths.ts';
+import { withBoundedReadSession } from './bounded-reads.ts';
export interface ManagedSyncWriteDiagnostic {
source_id: string;
@@ -808,7 +809,8 @@ const WAIVER_RUN_MAX = 64;
async function waiveRun(engine: BrainEngine, cursor: Cursor, head: Pending, key: string, config: GBrainConfig, assertActive: () => void,
frozenRun: Parameters<typeof freezeEntry>[4], drainStartedAt: number, limit: number, onProgress: SyncOpts['onProgress']): Promise<Cursor | null> {
// The run's screens share one memo of root-level path facts (screening-paths.ts); waiveNoopRun re-validates each entry.
- const run = await withScreeningPaths(() => screenWaiverRun(engine, cursor, head, key, config, assertActive, frozenRun, limit));
+ // GBRA-75 wave 9: and one bounded-read session (bounded-reads.ts), so the run's screens share one transaction.
+ const run = await withScreeningPaths(() => withBoundedReadSession(engine, session => screenWaiverRun(session, cursor, head, key, config, assertActive, frozenRun, limit)));
if (!run) return null;
assertActive();
const observedAt = frozenRun.observedAt ?? new Date().toISOString();
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 2b244a0173..2d85898045 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -682,16 +682,16 @@ export class PostgresEngine implements BrainEngine {
async executeRaw<R = Record<string, unknown>>(
query: string,
params?: unknown[],
- opts?: { signal?: AbortSignal },
+ opts?: { signal?: AbortSignal; prepare?: boolean },
): Promise<R[]> {
- // ReservedConnection.executeRaw doesn't wire AbortSignal today
- // (the only use site is migrations + cycle-lock writes that don't
- // want cancellation). Signature matches the interface so callers
- // that pass opts don't typecheck-break; opts.signal is ignored.
+ // ReservedConnection.executeRaw doesn't wire AbortSignal today (migrations and cycle-lock writes
+ // don't want cancellation); opts.signal is ignored. GBRA-75 w9: `prepare` names a parameterized
+ // statement (bounded read sessions); postgres.js ANDs it with the connection option, as runUnsafe does.
+ // Without it the statement stays unnamed, as before.
void opts;
const rows = params === undefined
? await reserved.unsafe(query)
- : await reserved.unsafe(query, params as Parameters<typeof reserved.unsafe>[1]);
+ : await reserved.unsafe(query, params as Parameters<typeof reserved.unsafe>[1], { prepare: opts?.prepare === true });
return rows as unknown as R[];
},
};
diff --git a/test/persistence-bounded-read-session.test.ts b/test/persistence-bounded-read-session.test.ts
index dff5b70d7a..6f3e79bffa 100644
--- a/test/persistence-bounded-read-session.test.ts
+++ b/test/persistence-bounded-read-session.test.ts
@@ -3,7 +3,8 @@
* screen's bounded reads share. Protects: the reads run on one reserved
* connection between one `BEGIN; SET LOCAL statement_timeout` and one `COMMIT`;
* the bound stays per statement on the server (set again once the one in force
- * outlasts a read's own bound by more than the slack); a statement held by a
+ * differs from a read's own bound by more than the slack; a screen inside a
+ * waiver run's session joins it); a statement held by a
* relation lock ends on the server at its bound with no statement left running;
* a failed read rolls the transaction back and the reads it aborted (25P02) run
* again, so each read sees its own outcome; a read after the session closed and
@@ -59,7 +60,7 @@ test('a session runs its bounded reads in one transaction; unbounded statements
expect(direct[1]).toEqual({ sql: 'SELECT 5 AS late', timeoutMs: 1000 });
});
-test('the bound in force is set again once it outlasts a read\'s own bound by more than the slack', async () => {
+test('the bound in force is set again once it differs from a read\'s own bound by more than the slack', async () => {
const { engine, conn } = fakePostgres();
await withBoundedReadSession(engine, async session => {
await session.executeRaw('SELECT 1', [], { timeoutMs: 10_000 });
@@ -89,6 +90,22 @@ test('a failed read rolls the transaction back, the reads it aborted run again,
expect(conn.filter(sql => sql === 'SELECT queued')).toHaveLength(2);
});
+test('a screen inside a waiver run\'s session joins it: one transaction for both, reads named as prepared statements', async () => {
+ const { engine, conn } = fakePostgres();
+ const prepared: unknown[] = [];
+ const spy = { ...engine, withReservedConnection: <T>(fn: (c: ReservedConnection) => Promise<T>) => engine.withReservedConnection(c => fn({ executeRaw: (sql: string, params?: unknown[], opts?: { prepare?: boolean }) => {
+ if (!/^(BEGIN|COMMIT|ROLLBACK|SET LOCAL)/.test(sql)) prepared.push(opts?.prepare); return c.executeRaw(sql, params, opts); } } as ReservedConnection)) } as unknown as BrainEngine;
+ let reserved = 0;
+ const counted = new Proxy(spy, { get(target, key) { if (key === 'withReservedConnection') reserved++; return Reflect.get(target, key); } });
+ await withBoundedReadSession(counted, async run => {
+ await run.executeRaw('SELECT 1', [], { timeoutMs: 10_000 });
+ await withBoundedReadSession(run, async screen => { expect(screen).toBe(run); await screen.executeRaw('SELECT 2', [], { timeoutMs: 10_000 }); });
+ });
+ expect(reserved).toBe(1);
+ expect(conn).toEqual(['BEGIN', 'SET LOCAL statement_timeout = 10000', 'SELECT 1', 'SELECT 2', 'COMMIT']);
+ expect(prepared).toEqual([true, true]);
+});
+
test('PGLite, or a pool with no long-hold capacity, gets the engine itself; an error from inside the session passes through', async () => {
const pglite = { kind: 'pglite' } as unknown as BrainEngine;
expect(await withBoundedReadSession(pglite, async engine => engine)).toBe(pglite);
@@ -147,7 +164,7 @@ test('on Postgres: one backend and one transaction per session, each statement b
const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
const OPTS = { noPull: true, noEmbed: true, noExtract: true };
-test('a full re-sync\'s waiver screens run their bounded reads on screen sessions, not one bounded transaction per read', () => withEnv({ GBRAIN_HOME: home }, async () => {
+test('a full re-sync\'s waiver screens run their bounded reads on the waiver run\'s session, not one bounded transaction per read', () => withEnv({ GBRAIN_HOME: home }, async () => {
for (const engine of engines) {
const id = `brs-${randomUUID().replace(/-/g, '').slice(0, 16)}`, root = join(home, id);
mkdirSync(root, { recursive: true }); git(root, 'init', '-q');
@@ -168,8 +185,9 @@ test('a full re-sync\'s waiver screens run their bounded reads on screen session
} });
try {
expect(await performManagedSync(counted, { sourceId: id, ...OPTS, full: true })).toMatchObject({ status: 'synced', modified: 0, waived: { imports: 8, deletes: 0 } });
- // Only the run's checkpoint, which the consumer prepares, reads per statement; each screen took 14 such reads before.
- if (engine.kind === 'postgres') { expect(perRead).toBeLessThan(8 * 3); expect(sessions).toBeGreaterThanOrEqual(8); }
+ // Only the run's checkpoint, which the consumer prepares, reads per statement (each screen took 14 such reads before),
+ // and the screens of one waiver run share its session.
+ if (engine.kind === 'postgres') { expect(perRead).toBeLessThan(8 * 3); expect(sessions).toBeGreaterThanOrEqual(1); expect(sessions).toBeLessThan(8); }
else expect(perRead).toBe(0);
} finally { await disposePersistenceConsumer(counted); }
}