Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
persistence: in-process completion handoff and classified write waits (#5984)
garrytan9779b516624c
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex edaf491763..dd66bb9d96 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -26,7 +26,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.-- `src/core/persistence/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. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite, 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`.+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite, 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`.- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 189475eb9b..32399a7736 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -83,9 +83,11 @@ export class PersistenceConsumer {private lastPhaseError: string | undefined;private preparationAttempts = 0;private preparing = new Map<string, { request_id: string; started_at: string; deadline_exceeded: boolean; attempt: number }>();+ private executing = new Set<string>();readonly hostId: string;constructor(readonly engine: BrainEngine, readonly config: GBrainConfig, readonly prepare: PrepareMutation,- private opts: { hostId?: string; concurrency?: number; pollMs?: number; idleMaxMs?: number; phaseMs?: number; preparationMs?: number; onError?: (error: unknown) => void } = {}) {+ private opts: { hostId?: string; concurrency?: number; pollMs?: number; idleMaxMs?: number; phaseMs?: number; preparationMs?: number; onError?: (error: unknown) => void;+ onSettled?: (row: WriteRequest) => void } = {}) {this.hostId = opts.hostId ?? localHostId();}private get checkoutObservable(): ((listener: () => void) => () => void) | undefined {@@ -308,6 +310,7 @@ export class PersistenceConsumer {this.rootRetryAfter.set(root, Date.now() + delay);try {const recovered = await this.phase('recovery', () => recoverPublication(this.engine, row.id, this.hostId));+ if (isTerminal(recovered)) this.settled(recovered);if (!recovered.recovery) this.rootRetryAfter.delete(root);else if (recovered.blocked_reason === 'unexpected_file_bytes') this.rootRetryAfter.set(root, Date.now() + Math.max(delay, 30_000));} catch (error) {@@ -354,6 +357,12 @@ export class PersistenceConsumer {{ hostId: this.hostId, limit, signal: this.abort.signal }) >= limit);}foregroundCompletions(worktreeId: string): number { return this.foregroundCounts.get(worktreeId) ?? 0; }+ /** CEO-A7: this process holds the claim, so its outcome reaches waiters through `onSettled` without a read. */+ holds(id: string): boolean { return this.executing.has(id); }+ private settled(row: WriteRequest): boolean {+ try { this.opts.onSettled?.(row); } catch (error) { this.report(error); }+ return isTerminal(row);+ }status() {return { accepting: !this.stopping, active_preparations: this.active.size, active_worktrees: this.activeRoots.size,sampled_at: new Date().toISOString(), observation_scope: 'current_process_reset_on_restart',@@ -438,6 +447,7 @@ export class PersistenceConsumer {const abort = new AbortController();const observation = { request_id: row.request_id, started_at: new Date().toISOString(), deadline_exceeded: false, attempt: ++this.preparationAttempts };this.preparing.set(row.id, observation);+ this.executing.add(row.id);const stop = () => abort.abort({ code: 'consumer_stopping' });this.abort.signal.addEventListener('abort', stop, { once: true });// edit_page (#5616) builds its content during preparation like put_page, so it shares the deadline.@@ -475,7 +485,7 @@ export class PersistenceConsumer {if (done.state === 'committed' && row.worktree_id && !String(row.intent?.kind).startsWith('managed_sync_')) {this.foregroundCounts.set(row.worktree_id, this.foregroundCompletions(row.worktree_id) + 1);}- return isTerminal(done);+ return this.settled(done);} catch (error) {if (preparationActive && bounded && performance.now() >= deadline) observation.deadline_exceeded = true;if (preparationActive && (abort.signal.aborted || observation.deadline_exceeded)) {@@ -484,12 +494,12 @@ export class PersistenceConsumer {}const current = await getWriteRequestById(this.engine, row.id);if (current && !isTerminal(current) && current.execution_token === row.execution_token && !current.recovery) {- return isTerminal(await finishUnpublishedFailure(this.engine, current, error));+ return this.settled(await finishUnpublishedFailure(this.engine, current, error));}throw error;} finally {closed = true; clearInterval(interval); if (timeout) clearTimeout(timeout);- this.abort.signal.removeEventListener('abort', stop); this.preparing.delete(row.id); await renewing;+ this.abort.signal.removeEventListener('abort', stop); this.preparing.delete(row.id); this.executing.delete(row.id); await renewing;}}/** Mandatory barrier: engine.close must be sequenced AFTER this promise. */diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex c004a5d153..276a970365 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -99,6 +99,13 @@ export async function getWriteRequestById(engine: SqlEngine, id: string, signal?const [row] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [id], { signal });return row ?? null;}+/** #5984: the columns a waiter needs while a request is unfinished; the full row is read once it is terminal. */+export type WriteRequestProgress = Pick<WriteRequest, 'state' | 'error_code' | 'error_message' | 'completed_at' | 'updated_at' | 'blocked_reason' | 'outcome'>;+export const WRITE_PROGRESS_SQL = 'SELECT state,error_code,error_message,completed_at,updated_at,blocked_reason,outcome FROM persistence_requests WHERE id=$1::uuid';+export async function getWriteRequestProgress(engine: SqlEngine, id: string, signal?: AbortSignal): Promise<WriteRequestProgress | null> {+ const [row] = await engine.executeRaw<WriteRequestProgress>(WRITE_PROGRESS_SQL, [id], { signal });+ return row ?? null;+}export function intentDigest(a: Pick<WriteAdmission, 'operation' | 'sourceId' | 'slug' | 'callerIntent'>): string {return digest({ operation: a.operation, source_id: a.sourceId, slug: a.slug, intent: a.callerIntent });}diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex cc9843cb05..8454e0ec2f 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -4,17 +4,20 @@ import { OperationError } from '../ops/contract.ts';import { PersistenceConsumer, type PrepareMutation } from './consumer.ts';import { preparePageMutation } from './page-prepare.ts';import { prepareSemanticPageMutation } from './semantic-pages.ts';-import { getWriteRequestById, receiptFor } from './journal.ts';+import { getWriteRequestById, getWriteRequestProgress, receiptFor, type WriteRequestProgress } from './journal.ts';import { isTerminal, type WriteRequest } from './model.ts';import { isWriteErrorCode, type WriteReceipt } from './types.ts';import { registerPgliteReopen } from '../pglite-lifecycle.ts';import { assertMutationProtocol } from './protocol.ts';import { pendingWriteHint } from './health.ts';import { receiptDeliveredHint } from './connector-errors.ts';+import type { PgAccessReason } from '../pg-access-classify.ts';interface Service { consumer: PersistenceConsumer; stopping: boolean; unregisterStop?: () => void; unregisterReopen?: () => void; }const services = new WeakMap<BrainEngine, Service>();-const receiptReads = new WeakMap<BrainEngine, Map<string, { read: Promise<WriteRequest | null>; abort: AbortController }>>();+type ProgressRead = { row: WriteRequestProgress | null } | { error: unknown } | { cancelled: true };+const receiptReads = new WeakMap<BrainEngine, Map<string, { read: Promise<ProgressRead>; abort: AbortController }>>();+const settledWaiters = new WeakMap<BrainEngine, Map<string, Set<(row: WriteRequest) => void>>>();const preparers = new Map<string, { prepare: PrepareMutation; target: 'page' | 'skill_bundle' }>();export function registerMutationPreparer(operation: string, prepare: PrepareMutation, target: 'page' | 'skill_bundle' = 'page'): void {preparers.set(operation, { prepare, target });@@ -55,7 +58,8 @@ export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfif (prior.stopping) throw new OperationError('unavailable', 'The persistence owner is closing.');return prior.consumer;}- const consumer = new PersistenceConsumer(engine, config, preparePersistedMutation);+ const consumer = new PersistenceConsumer(engine, config, preparePersistedMutation,+ { onSettled: row => { for (const listener of settledWaiters.get(engine)?.get(row.id) ?? []) listener(row); } });const service: Service = { consumer, stopping: false };services.set(engine, service);const lifecycle = engine as BrainEngine & { registerBeforeDisconnect?: (run: () => Promise<void>) => unknown };@@ -99,39 +103,109 @@ export function persistenceConsumerStatus(engine: BrainEngine) {export function assertPersistenceAccepting(engine: BrainEngine): void {if (services.get(engine)?.stopping) throw new OperationError('unavailable', 'The persistence owner is closing. Retry the same request_id after restart.');}-/** The waiter never owns a provider, database connection, or kernel lock. */-export async function waitForWrite(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, waitMs = 5000): Promise<WriteRequest> {- if (isTerminal(row)) return row;- // The admission transaction has committed: publish now, not after the idle backoff.- startPersistenceConsumer(engine, config).wake();+/** DX-A3: pending heads that need intervention, not more waiting. */+export const BLOCKED_WRITE_REASONS = ['recovery_required', 'owner_unavailable', 'unexpected_file_bytes', 'unexpected_staging_bytes'] as const;+const FATAL_READ_REASONS: readonly PgAccessReason[] = ['auth_failed', 'permission_denied', 'tenant_not_found', 'db_missing', 'schema_missing', 'storage_corrupt'];+/** CEO-A7: the first poll waits this long (at most half the wait) for an in-process handoff; later polls back off from 50 to 250 ms. */+export const WRITE_POLL_START_MS = 200;+export type WriteWait =+ | { kind: 'terminal' | 'pending'; row: WriteRequest }+ | { kind: 'blocked'; row: WriteRequest; request_id: string; cause: typeof BLOCKED_WRITE_REASONS[number]; command: string }+ | { kind: 'read_failed'; row: WriteRequest; request_id: string; reason: PgAccessReason; transient: boolean; sqlstate?: string;+ attempts: number; message: string; remediation: string };+/**+ * Waits for an admitted write and classifies how the wait ended. A request this+ * process publishes is handed over by its consumer without a read; otherwise a+ * narrow progress read polls, and the full row is read once when terminal. The+ * waiter's own cancelled reads are not failures; database read failures are+ * classified (`read_failed`) instead of reading as a still-pending write.+ * The waiter never owns a provider, database connection, or kernel lock.+ */+export async function awaitWrite(engine: BrainEngine, row: WriteRequest, config: GBrainConfig,+ opts: { waitMs?: number; signal?: AbortSignal } = {}): Promise<WriteWait> {+ if (isTerminal(row)) return { kind: 'terminal', row };+ const consumer = startPersistenceConsumer(engine, config);const service = services.get(engine)!;- let reads = receiptReads.get(engine);- if (!reads) { reads = new Map(); receiptReads.set(engine, reads); }+ const id = row.id;+ let handed: WriteRequest | undefined;+ let wake: (() => void) | undefined;+ let waiters = settledWaiters.get(engine);+ if (!waiters) { waiters = new Map(); settledWaiters.set(engine, waiters); }+ const listeners = waiters.get(id) ?? new Set();+ const listener = (settled: WriteRequest) => { handed = settled; wake?.(); };+ listeners.add(listener); waiters.set(id, listeners);+ // The admission transaction has committed: publish now, not after the idle backoff.+ consumer.wake();+ const waitMs = opts.waitMs ?? 5000;const deadline = performance.now() + waitMs;- while (!service.stopping && performance.now() < deadline) {- await new Promise(resolve => setTimeout(resolve, Math.min(50, Math.max(1, deadline - performance.now()))));- const remaining = deadline - performance.now();- if (service.stopping || remaining <= 0) break;- let pending = reads.get(row.id);- const ownsRead = !pending;- if (!pending) {- if (reads.size >= 4) continue;- const abort = new AbortController();- const id = row.id;- const read = getWriteRequestById(engine, row.id, engine.kind === 'postgres' ? abort.signal : undefined)- .catch(() => null).finally(() => { if (reads.get(id)?.read === read) reads.delete(id); });- pending = { read, abort };- reads.set(id, pending);+ const firstPoll = Math.min(WRITE_POLL_START_MS, waitMs / 2);+ let delay = firstPoll, failure: { error: unknown; attempts: number } | undefined;+ try {+ while (!service.stopping && !opts.signal?.aborted) {+ if (handed) { row = handed; handed = undefined; if (isTerminal(row)) return { kind: 'terminal', row }; }+ const remaining = deadline - performance.now();+ if (remaining <= 0) break;+ await new Promise<void>(resolve => {+ const done = () => { clearTimeout(timer); wake = undefined; opts.signal?.removeEventListener('abort', done); resolve(); };+ const timer = setTimeout(done, Math.min(delay, remaining));+ wake = done; opts.signal?.addEventListener('abort', done, { once: true });+ });+ if (handed || service.stopping || opts.signal?.aborted || performance.now() >= deadline) continue;+ delay = delay === firstPoll ? 50 : Math.min(250, delay * 2);+ if (consumer.holds(id)) continue;+ const read = await readProgress(engine, id, deadline - performance.now());+ if ('cancelled' in read) continue;+ if ('error' in read) {+ failure = { error: read.error, attempts: (failure?.attempts ?? 0) + 1 };+ const { classifyPgAccessError } = await import('../pg-access-classify.ts');+ if (FATAL_READ_REASONS.includes(classifyPgAccessError(read.error).reason)) break;+ continue;+ }+ failure = undefined;+ if (!read.row) continue;+ row = { ...row, ...read.row };+ if (isTerminal(row)) return { kind: 'terminal', row: await getWriteRequestById(engine, id).catch(() => null) ?? row };}- let timer: ReturnType<typeof setTimeout> | undefined;- const found = await Promise.race([- pending.read,- new Promise<null>(resolve => { timer = setTimeout(() => { if (ownsRead) pending.abort.abort(); resolve(null); }, remaining); }),- ]).finally(() => { if (timer) clearTimeout(timer); });- if (found) row = found;- if (isTerminal(row)) return row;+ } finally {+ listeners.delete(listener);+ if (!listeners.size && waiters.get(id) === listeners) waiters.delete(id);+ }+ if (handed) row = handed;+ if (isTerminal(row)) return { kind: 'terminal', row };+ if (failure) {+ const { classifyPgAccessError } = await import('../pg-access-classify.ts');+ const diagnosis = classifyPgAccessError(failure.error);+ return { kind: 'read_failed', row, request_id: row.request_id, reason: diagnosis.reason, transient: diagnosis.transient,+ ...(diagnosis.sqlstate ? { sqlstate: diagnosis.sqlstate } : {}), attempts: failure.attempts, message: diagnosis.message, remediation: diagnosis.remediation };}- return row;+ const cause = BLOCKED_WRITE_REASONS.find(reason => reason === row.blocked_reason);+ return cause ? { kind: 'blocked', row, request_id: row.request_id, cause, command: `gbrain sources writer status ${row.source_id} --json` } : { kind: 'pending', row };+}+/** At most four progress reads per engine; concurrent waiters on one request share a read. */+async function readProgress(engine: BrainEngine, id: string, remaining: number): Promise<ProgressRead> {+ let reads = receiptReads.get(engine);+ if (!reads) { reads = new Map(); receiptReads.set(engine, reads); }+ let pending = reads.get(id);+ const ownsRead = !pending;+ if (!pending) {+ if (reads.size >= 4) return { cancelled: true };+ const abort = new AbortController();+ const shared = reads;+ const read: Promise<ProgressRead> = getWriteRequestProgress(engine, id, engine.kind === 'postgres' ? abort.signal : undefined)+ .then(row => ({ row }), error => abort.signal.aborted ? { cancelled: true as const } : { error })+ .finally(() => { if (shared.get(id)?.read === read) shared.delete(id); });+ pending = { read, abort };+ reads.set(id, pending);+ }+ const owned = pending;+ let timer: ReturnType<typeof setTimeout> | undefined;+ return Promise.race([owned.read, new Promise<ProgressRead>(resolve => {+ timer = setTimeout(() => { if (ownsRead) owned.abort.abort(); resolve({ cancelled: true }); }, remaining);+ })]).finally(() => { if (timer) clearTimeout(timer); });+}+/** Compatibility form of `awaitWrite`: the latest row, terminal or still pending. */+export async function waitForWrite(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, waitMs = 5000): Promise<WriteRequest> {+ return (await awaitWrite(engine, row, config, { waitMs })).row;}export function writeResponse(row: WriteRequest): Record<string, unknown> {const receipt = receiptFor(row);diff --git a/test/e2e/persistence-phase-liveness.test.ts b/test/e2e/persistence-phase-liveness.test.tsindex deafd4972e..c7468502cf 100644--- a/test/e2e/persistence-phase-liveness.test.ts+++ b/test/e2e/persistence-phase-liveness.test.ts@@ -8,7 +8,7 @@ import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts'import { withEnv } from '../helpers/with-env.ts';import { waitFor } from '../helpers/wait-for.ts';import { admission, assertCommittedSnapshot, assertConservation, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../../scripts/persistence/harness.ts';-import { admitWrite, claimNextWrite, getWriteRequestById, prepareRecovery, renewWriteClaim } from '../../src/core/persistence/journal.ts';+import { admitWrite, claimNextWrite, getWriteRequestById, prepareRecovery, renewWriteClaim, WRITE_PROGRESS_SQL } from '../../src/core/persistence/journal.ts';import { PersistenceConsumer } from '../../src/core/persistence/consumer.ts';import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite } from '../../src/core/persistence/service.ts';import { sha256 } from '../../src/core/persistence/digest.ts';@@ -108,9 +108,9 @@ describe.skipIf(!url)('PostgreSQL persistence phase cancellation', () => {let entered = false;const proxy = new Proxy(engine, { get(target, key) {if (key === 'executeRaw') return async (...args: Parameters<typeof engine.executeRaw>) => {- if (args[0] === 'SELECT * FROM persistence_requests WHERE id=$1::uuid' && args[1]?.[0] === first.id) {+ if (args[0] === WRITE_PROGRESS_SQL && args[1]?.[0] === first.id) {entered = true;- return target.executeRaw('SELECT r.* FROM persistence_requests r CROSS JOIN pg_sleep(20) WHERE r.id=$1::uuid', args[1], args[2]);+ return target.executeRaw(WRITE_PROGRESS_SQL.replace('WHERE', 'CROSS JOIN pg_sleep(20) WHERE'), args[1], args[2]);}return target.executeRaw(...args);};diff --git a/test/persistence-consumer-scheduling.test.ts b/test/persistence-consumer-scheduling.test.tsindex 7af912f80a..96a1de7968 100644--- a/test/persistence-consumer-scheduling.test.ts+++ b/test/persistence-consumer-scheduling.test.ts@@ -5,13 +5,13 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';-import { admitWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';+import { admitWrite, getWriteRequestById, WRITE_PROGRESS_SQL } from '../src/core/persistence/journal.ts';import { cancelWriteRequest } from '../src/core/persistence/control.ts';import { acquireWorktree } from '../src/core/persistence/ownership.ts';import { admission, assertCommittedSnapshot, assertConservation, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';import { withEnv } from './helpers/with-env.ts';import { waitFor } from './helpers/wait-for.ts';-import { disposePersistenceConsumer, startPersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';+import { awaitWrite, disposePersistenceConsumer, registerMutationPreparer, startPersistenceConsumer, waitForWrite } from '../src/core/persistence/service.ts';const home = mkdtempSync(join(tmpdir(), 'gbrain-consumer-scheduling-'));const config: HarnessConfig = {@@ -40,7 +40,7 @@ test('simultaneous bounded waiters retain one unresolved receipt read until settlet reads = 0;const proxy = new Proxy(engine, { get(target, key) {if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {- if (sql === 'SELECT * FROM persistence_requests WHERE id=$1::uuid') { reads++; return release.promise; }+ if (sql === WRITE_PROGRESS_SQL) { reads++; return release.promise; }return target.executeRaw(sql, params);};const value = Reflect.get(target, key);@@ -66,7 +66,7 @@ test('shutdown drains an uncancellable receipt read without scheduling another',let reads = 0, stopped = false;const proxy = new Proxy(engine, { get(target, key) {if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {- if (sql === 'SELECT * FROM persistence_requests WHERE id=$1::uuid') { reads++; return release.promise; }+ if (sql === WRITE_PROGRESS_SQL) { reads++; return release.promise; }return target.executeRaw(sql, params);};const value = Reflect.get(target, key);@@ -92,7 +92,7 @@ test.each(['queued', 'committed'] as const)('coalesced receipt reads preserve eaconst rows = Array.from({ length: 2 }, () => ({ id: randomUUID(), request_id: randomUUID(), state: 'queued' } as import('../src/core/persistence/model.ts').WriteRequest));const proxy = new Proxy(engine, { get(target, key) {if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {- if (sql === 'SELECT * FROM persistence_requests WHERE id=$1::uuid') {+ if (sql === WRITE_PROGRESS_SQL) {await Bun.sleep(20);return [{ ...rows.find(row => row.id === params?.[0]), state: params?.[0] === rows[0].id ? firstState : 'committed' }];}@@ -116,7 +116,7 @@ test('a stalled receipt read does not hide another request that already committelet entered = false;const proxy = new Proxy(engine, { get(target, key) {if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {- if (sql === 'SELECT * FROM persistence_requests WHERE id=$1::uuid') {+ if (sql === WRITE_PROGRESS_SQL) {if (params?.[0] === rows[0].id) { entered = true; return release.promise; }return [{ ...rows[1], state: 'committed' }];}@@ -144,7 +144,7 @@ test.each([false, true])('a shorter receipt waiter cannot abort another caller\'const proxy = new Proxy(engine, { get(target, key) {if (key === 'kind') return 'postgres';if (key === 'executeRaw') return async (...args: Parameters<typeof engine.executeRaw>) => {- if (args[0] === 'SELECT * FROM persistence_requests WHERE id=$1::uuid') {+ if (args[0] === WRITE_PROGRESS_SQL) {if (args[1]?.[0] === row.id) ownerSignal = args[2]?.signal;return release.promise;}@@ -168,7 +168,7 @@ test('distinct stalled receipt reads stay capped and shutdown drains every retailet reads = 0, stopped = false;const proxy = new Proxy(engine, { get(target, key) {if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {- if (sql === 'SELECT * FROM persistence_requests WHERE id=$1::uuid') {+ if (sql === WRITE_PROGRESS_SQL) {const release = releases[reads++];expect(release).toBeDefined();return release.promise;@@ -550,3 +550,113 @@ test('a local waiter wakes an idle owner for a claim-only tick instead of waitinawait waiter;} finally { await disposePersistenceConsumer(engine); }}), 5000);++/** #5984 (CEO-A7, DX-A3): classified waits with an in-process completion handoff. */+function countingProxy(target: PGLiteEngine, onRead?: (sql: string, params?: unknown[]) => unknown) {+ const counts = { progress: 0, full: 0 };+ const proxy = new Proxy(target, { get(base, key) {+ if (key === 'executeRaw') return async (sql: string, params?: unknown[], opts?: unknown) => {+ if (sql === WRITE_PROGRESS_SQL) counts.progress++;+ // Only the waiter's own reads count; publication itself reads its receipt (clearResolvedRecovery).+ if (sql === 'SELECT * FROM persistence_requests WHERE id=$1::uuid' && new Error().stack?.includes('awaitWrite')) counts.full++;+ const replaced = onRead?.(sql, params);+ if (replaced !== undefined) return replaced;+ return base.executeRaw(sql, params as unknown[], opts as never);+ };+ const value = Reflect.get(base, key);+ return typeof value === 'function' ? value.bind(base) : value;+ } });+ return { proxy, counts };+}++test('a write this process publishes resolves from the consumer handoff with zero request reads', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ registerMutationPreparer('test_wait_handoff', async (_e, row) => { await Bun.sleep(400); return prepared(row, sources); });+ const { proxy, counts } = countingProxy(engine);+ startPersistenceConsumer(proxy, { engine: 'pglite' });+ try {+ await Bun.sleep(300);+ const row = await admitWrite(engine, admission(config, sources[0], 'wait-handoff', 'handoff body', 0, { operation: 'test_wait_handoff' }));+ const before = { ...counts };+ const started = performance.now();+ const waited = await awaitWrite(proxy, row, { engine: 'pglite' }, { waitMs: 10_000 });+ expect(performance.now() - started).toBeGreaterThan(300);+ expect(waited.kind).toBe('terminal');+ expect(waited.row).toEqual((await getWriteRequestById(engine, row.id))!);+ expect(waited.row.state).toBe('committed');+ expect(counts).toEqual(before);+ } finally { await disposePersistenceConsumer(proxy); }+}), 15_000);++test('a write another consumer publishes resolves through progress polling with the full terminal row', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const row = await admitWrite(engine, admission(config, sources[0], 'wait-cross-process', 'cross body'));+ const { proxy, counts } = countingProxy(engine);+ const local = startPersistenceConsumer(proxy, { engine: 'pglite' });+ (local as unknown as { doTick(): Promise<void> }).doTick = async () => {};+ const other = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_e, current) => prepared(current, sources), { hostId: config.hostId });+ try {+ const waiting = awaitWrite(proxy, row, { engine: 'pglite' }, { waitMs: 10_000 });+ other.start();+ const waited = await waiting;+ expect(waited.kind).toBe('terminal');+ expect(waited.row).toEqual((await getWriteRequestById(engine, row.id))!);+ expect(waited.row.intent).toEqual(row.intent);+ expect(counts.progress).toBeGreaterThan(0);+ expect(counts.full).toBe(1);+ } finally { await other.stop(); await disposePersistenceConsumer(proxy); }+}), 15_000);++test('an authentication failure during a wait is classified, not reported as still pending', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const row = await admitWrite(engine, admission(config, sources[0], 'wait-auth-failure', 'auth body'));+ const { proxy, counts } = countingProxy(engine, sql => {+ if (sql === WRITE_PROGRESS_SQL) throw Object.assign(new Error('password authentication failed for user "example"'), { code: '28P01' });+ });+ (startPersistenceConsumer(proxy, { engine: 'pglite' }) as unknown as { doTick(): Promise<void> }).doTick = async () => {};+ try {+ const started = performance.now();+ const waited = await awaitWrite(proxy, row, { engine: 'pglite' }, { waitMs: 5000 });+ expect(performance.now() - started).toBeLessThan(2000);+ expect(waited).toMatchObject({ kind: 'read_failed', request_id: row.request_id, reason: 'auth_failed', transient: false, attempts: 1 });+ expect(counts.progress).toBe(1);+ } finally {+ await disposePersistenceConsumer(proxy);+ await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);+ }+}), 10_000);++test('repeated connection resets during a wait are classified with their attempt count', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const row = await admitWrite(engine, admission(config, sources[0], 'wait-connection-reset', 'reset body'));+ const { proxy, counts } = countingProxy(engine, sql => {+ if (sql === WRITE_PROGRESS_SQL) throw Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' });+ });+ (startPersistenceConsumer(proxy, { engine: 'pglite' }) as unknown as { doTick(): Promise<void> }).doTick = async () => {};+ try {+ const waited = await awaitWrite(proxy, row, { engine: 'pglite' }, { waitMs: 1200 });+ expect(waited).toMatchObject({ kind: 'read_failed', request_id: row.request_id, reason: 'conn_dropped', transient: true });+ expect(waited.kind === 'read_failed' && waited.attempts).toBe(counts.progress);+ expect(counts.progress).toBeGreaterThan(2);+ expect(waited.row.state).toBe('queued');+ } finally {+ await disposePersistenceConsumer(proxy);+ await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);+ }+}), 10_000);++test('a recovery-blocked pending head is classified as blocked with its request ID and inspection command', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const row = await admitWrite(engine, admission(config, sources[0], 'wait-recovery-blocked', 'blocked body'));+ await engine.executeRaw("UPDATE persistence_requests SET blocked_reason='recovery_required' WHERE id=$1::uuid", [row.id]);+ (startPersistenceConsumer(engine, { engine: 'pglite' }) as unknown as { doTick(): Promise<void> }).doTick = async () => {};+ try {+ const waited = await awaitWrite(engine, row, { engine: 'pglite' }, { waitMs: 600 });+ expect(waited).toMatchObject({ kind: 'blocked', request_id: row.request_id, cause: 'recovery_required',+ command: `gbrain sources writer status ${sources[0].id} --json` });+ expect(await waitForWrite(engine, row, { engine: 'pglite' }, 100)).toMatchObject({ id: row.id, state: 'queued', blocked_reason: 'recovery_required' });+ } finally {+ await disposePersistenceConsumer(engine);+ await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);+ }+}), 10_000);