Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(persistence): bounded preparation on the single route: per-kind budget, race, attempt counter, ceiling, bounded stop (#6278)
garrytana7d29c8cb680
diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.tsindex 593bcb492c..58cb75e146 100644--- a/src/core/persistence/claim-phase.ts+++ b/src/core/persistence/claim-phase.ts@@ -88,6 +88,16 @@ export function claimPhaseStamp(clock: ClaimPhaseClock, token: string | null, owstep: clock.step, step_since: new Date(clock.stepSince).toISOString(), waiting_on: clock.waitingOn, owner });}+/**+ * #6278: the SQL that charges a reclaimed expired claim to its request's+ * `preparation_attempts`: only a claim whose owner stamped it `preparing`+ * under the token being reclaimed (a kill mid-preparation), never one that+ * was publishing, undispatched (no stamp of its token) or stamped by an+ * earlier claim.+ */+export const EXPIRED_PREPARING_CHARGE_SQL = (r: string) =>+ `CASE WHEN ${r}.claim_phase->>'phase'='preparing' AND ${r}.claim_phase->>'token'=${r}.execution_token::text THEN 1 ELSE 0 END`;+/** `persistence.max_claim_ms`: how long a write may hold its claim before doctor reports it as stalled. */export const MAX_CLAIM_CONFIG_KEY = 'persistence.max_claim_ms';export const MAX_CLAIM_DEFAULT_MS = 600_000;diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex c52af2eb5c..344222e3b8 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -1,12 +1,13 @@import type { BrainEngine, ReservedConnection } from '../engine.ts';import type { GBrainConfig } from '../config.ts';-import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, compactWriteReceipts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';-import { finishUnpublishedFailure, recoverPublication, type PreparedMutation } from './coordinator.ts';+import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, compactWriteReceipts, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';+import { finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, type PreparedMutation } from './coordinator.ts';import { localHostId } from './identity.ts';import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';import { preparationConfigView } from './config-snapshot.ts';import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';-import { claimPhaseStamp, enterClaimPhase, startClaimPhase } from './claim-phase.ts';+import { claimPhaseStamp, claimStateOf, EXPIRED_PREPARING_CHARGE_SQL, enterClaimPhase, startClaimPhase, type ClaimPhaseClock, type WaitingOn } from './claim-phase.ts';+import { DEFAULT_PREPARATION_POLICY, preparationBudgetMs, preparationKind, startPreparation, type PreparationPolicy } from './preparation-budget.ts';import { isTerminal, type WriteRequest } from './model.ts';import { ownerExceptionLogText } from './publication-failure.ts';import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';@@ -26,11 +27,19 @@ import { maybeRefreshPlannerStats } from '../planner-stats.ts';import { refreshFenceClear } from './worktree-refresh-schema.ts';import { faultPoint } from './fault-points.ts';import { releaseAbandonedClaims } from './effect-journal.ts';-import { readWriteSwitches, writeSwitchOn } from './switches.ts';+import { readWriteSwitchSnapshot, writeSwitchOn } from './switches.ts';type PhaseObservation = { name: string; started_at: string; deadline_exceeded: boolean; attempt: number; first_conn_ms?: number };/** #5373: set by a task that abandons a still-running preparation after losing its claim; its root is freed only once `until` settles. */type RootHold = { until?: Promise<void> };+/** #6278: the budgets and switch in effect for this tick's claims; a test may pin them through `opts.preparationBudgets`. */+export type EffectivePreparationPolicy = PreparationPolicy & { deadlines: boolean };+/** #6278: an abandoned preparation that outlived the hard ceiling; it pins whatever its await holds until it settles. */+export interface AbandonedPreparation { request_id: string; operation: string; step: string | null; waiting_on: WaitingOn; claimed_at: string; abandoned_at: string; outlived_ceiling_at: string }+/** #6278: how long stop() waits on abandoned preparations after their abort before closing the engine. */+export const ABANDONED_STOP_GRACE_MS = 5_000;+/** #6278: abandoned preparations past the ceiling this process tolerates before it stops claiming and reports `restart_required`. */+export const DEFAULT_ZOMBIE_CAP = 1;/** When this process started; on PGLite no claim written earlier can belong to a live owner. */const PROCESS_STARTED_AT = new Date(performance.timeOrigin);/** #5801: the phase a connection checkout belongs to, carried through its async chain. */@@ -49,6 +58,13 @@ function errorDetail(error: unknown): string | undefined {return redactConnectionInfo(message).replace(/\s+/g, ' ').replaceAll('"', "'").trim().slice(0, 200);}+/** #6278: the token of the stamp the previous claim left, so `claimStateOf` reads its last step. */+function previousToken(stamp: unknown): string | null {+ const raw = typeof stamp === 'string' ? (() => { try { return JSON.parse(stamp) as unknown; } catch { return null; } })() : stamp;+ const token = raw && typeof raw === 'object' ? (raw as { token?: unknown }).token : undefined;+ return typeof token === 'string' ? token : null;+}+/*** #5401: one resident projection invocation takes up to this many pages and* starts no new page once the budget has passed since it began. When a write is@@ -72,7 +88,8 @@ const PARKED_WORKER: Promise<void> = Promise.resolve();/** `onLane`'s answer when the lane cannot be lent: the caller runs on the pool instead. */export const LANE_BUSY = Symbol('gbrain.laneBusy');-export type PrepareMutation = (engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal) => Promise<PreparedMutation>;+/** `clock` (#6278): the claim's phase clock, for `enterClaimStep` at the preparer's await boundaries. */+export type PrepareMutation = (engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal, clock?: ClaimPhaseClock) => Promise<PreparedMutation>;export class PersistenceConsumer {private stopping = false;private timer: ReturnType<typeof setTimeout> | undefined;@@ -92,6 +109,11 @@ export class PersistenceConsumer {private active = new Set<Promise<void>>();/** #5373: preparations and renewals that outlived their claim; stop() drains them before the engine closes. */private outlived = new Set<Promise<void>>();+ /** #6278: preparations whose claim the budget (or a lost claim, with the switch on) released; stop() gives them ABANDONED_STOP_GRACE_MS. */+ private abandoned = new Set<Promise<void>>();+ /** #6278: abandoned preparations past the ceiling, by request row id. */+ private zombies = new Map<string, AbandonedPreparation>();+ private policy: EffectivePreparationPolicy = { ...DEFAULT_PREPARATION_POLICY, deadlines: true };private activeRoots = new Set<string>();/** #5984 lanes: running lane tasks per worktree. */private laneTasks = new Map<string, number>();@@ -137,7 +159,11 @@ export class PersistenceConsumer {claimLeaseMs?: number; onError?: (error: unknown) => void;onSettled?: (row: WriteRequest) => void;/** Engine graduation drain: claim, recover and publish requests only; effect, projection, topology and maintenance workers never start. */- requestsOnly?: boolean } = {}) {+ requestsOnly?: boolean;+ /** #6278 test seam: pins budgets, ceiling, attempt limit or the switch over the brain's config. */+ preparationBudgets?: Partial<EffectivePreparationPolicy>;+ /** #6278: abandoned preparations past the ceiling before this process stops claiming (default DEFAULT_ZOMBIE_CAP). */+ zombieCap?: number } = {}) {this.hostId = opts.hostId ?? localHostId();}private get checkoutObservable(): ((listener: () => void) => () => void) | undefined {@@ -368,8 +394,11 @@ export class PersistenceConsumer {}// Lane runs size themselves to the pool's long-hold budget; a single write keeps its warm lane.// The switches are read under the tick's phase deadline, so a saturated pool cannot hold the tick.- const fast = await this.phase('switches', signal => readWriteSwitches(this.engine, { signal }))- .then(switches => switches.single_write_group, async error => { await this.releaseIdleLane(); throw error; });+ const fast = await this.phase('switches', signal => readWriteSwitchSnapshot(this.engine, { signal }))+ .then(snapshot => {+ this.policy = { ...snapshot.preparation, deadlines: snapshot.switches.preparation_deadlines, ...this.opts.preparationBudgets };+ return snapshot.switches.single_write_group;+ }, async error => { await this.releaseIdleLane(); throw error; });if (laneRoots().length || this.engine.kind !== 'postgres' || !fast) await this.releaseIdleLane();this.idleDelayMs = this.pollMs;this.nextDelayMs = this.pollMs;@@ -404,7 +433,7 @@ export class PersistenceConsumer {// Recover only our owner roots. Kernel exclusion, not elapsed heartbeat,// proves that a previous process can no longer be publishing this root.if (scan && this.engine.kind === 'pglite' && !this.abandonedReleased) {- await this.phase('abandoned_claims', () => releaseAbandonedClaims(this.engine, PROCESS_STARTED_AT));+ await this.phase('abandoned_claims', () => releaseAbandonedClaims(this.engine, PROCESS_STARTED_AT, this.policy.deadlines));this.abandonedReleased = true;}const now = Date.now();@@ -433,19 +462,23 @@ export class PersistenceConsumer {this.report(error);}}+ // #6278: a claim that expired while its owner was preparing (the kill case) counts one preparation attempt.await this.phase('expired_claims', signal => this.engine.executeRaw(`WITH expired AS (SELECT r.id FROM persistence_requests r WHERE r.state='running' AND r.recovery IS NULLAND r.publication_started=false AND r.claim_expires_at<now() AND ${PERSISTENCE_PROTOCOL_PREDICATE}AND (r.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=r.worktree_id AND w.owner_host_id=$1::uuid))ORDER BY r.sequence LIMIT 100 FOR UPDATE OF r SKIP LOCKED)- UPDATE persistence_requests r SET state='queued',execution_token=NULL,claim_expires_at=NULL- FROM expired WHERE r.id=expired.id`, [this.hostId], { signal }));+ UPDATE persistence_requests r SET state='queued',execution_token=NULL,claim_expires_at=NULL,+ preparation_attempts=r.preparation_attempts+CASE WHEN $2::boolean THEN ${EXPIRED_PREPARING_CHARGE_SQL('r')} ELSE 0 END+ FROM expired WHERE r.id=expired.id`, [this.hostId, this.policy.deadlines], { signal }));}if (publicationConcurrency(this.engine) === 0) {await this.phase('capacity', signal => this.engine.executeRaw(`UPDATE persistence_requests SET blocked_reason='writer_pool_capacity'WHERE state='queued' AND blocked_reason IS DISTINCT FROM 'writer_pool_capacity' AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, undefined, { signal }));return;}+ // #6278: at the zombie cap this process claims nothing more; status() says restart_required and the drain ends.+ if (this.restartRequired()) return;const concurrency = this.opts.concurrency ?? 2;const attemptedRoots = new Set([...this.activeRoots, ...this.laneTasks.keys(), ...this.rootRetryAfter.keys()]);while (!this.stopping && this.active.size - this.laneTaskCount() < concurrency) {@@ -520,12 +553,20 @@ export class PersistenceConsumer {try { this.opts.onSettled?.(row); } catch (error) { this.report(error); }return isTerminal(row);}+ /** #6278: abandoned preparations past the ceiling have reached this process's cap; it claims nothing more until it restarts. */+ restartRequired(): boolean { return this.zombies.size >= (this.opts.zombieCap ?? DEFAULT_ZOMBIE_CAP); }status() {+ const { deadlines, syncMs, maintenanceMs, ceilingMs, maxAttempts } = this.policy;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',preparation_attempts: this.preparationAttempts,phase: this.phaseObservation ? { ...this.phaseObservation, ...this.phaseTiming(this.phaseObservation, this.phaseStartedAt) } : null,preparations: [...this.preparing.values()].map(value => ({ ...value })),+ // #6278: deadlines in effect, preparations whose claim was released while they still ran, and the zombies past the ceiling.+ preparation_policy: { deadlines, sync_preparation_ms: syncMs, maintenance_preparation_ms: maintenanceMs, preparation_ceiling_ms: ceilingMs, max_preparation_attempts: maxAttempts },+ abandoned_preparations: this.abandoned.size,+ outlived_ceiling: [...this.zombies.values()].map(value => ({ ...value })),+ restart_required: this.restartRequired(),...(this.lastError ? { last_error: { ...this.lastError } } : {}) };}/**@@ -606,48 +647,102 @@ export class PersistenceConsumer {private leaseTiming(): ClaimLeaseTiming {return { everyMs: this.opts.renewalIntervalMs ?? DEFAULT_CLAIM_LEASE_TIMING.everyMs, deadlineMs: this.opts.phaseMs ?? DEFAULT_CLAIM_LEASE_TIMING.deadlineMs };}+ /**+ * #6278: tracks a preparation whose claim is gone while it still runs. With+ * the deadlines switch on it goes to `abandoned` (stop() gives it a short+ * grace); off, to `outlived` as before (stop() waits for it). The returned+ * promise never rejects.+ */+ private keepAbandoned(work: Promise<unknown>): Promise<void> {+ if (!this.policy.deadlines) return this.keepUntilSettled(work);+ const settled = work.then(() => undefined, () => undefined);+ this.abandoned.add(settled);+ void settled.then(() => { this.abandoned.delete(settled); });+ return settled;+ }+ /**+ * #6278: the #5373 root barrier for an abandoned preparation, bounded by the+ * hard ceiling measured from the claim. At the ceiling the root is freed, the+ * request's counter is set to the limit (an overrun proves the await ignored+ * cancellation, so its next claim fails it `preparation_stalled`) and the+ * zombie stays tracked here and in status() until it settles.+ */+ private abandonedRootBlock(row: WriteRequest, clock: ClaimPhaseClock, settled: Promise<void>): Promise<void> {+ if (!this.policy.deadlines) return settled;+ let done = false;+ void settled.then(() => { done = true; });+ const remaining = Math.max(0, this.policy.ceilingMs - (Date.now() - clock.claimedAt));+ let timer: ReturnType<typeof setTimeout> | undefined;+ const ceiling = new Promise<void>(resolve => { timer = setTimeout(resolve, remaining); timer.unref?.(); });+ return Promise.race([settled, ceiling]).then(async () => {+ if (timer) clearTimeout(timer);+ if (done) return;+ const at = new Date().toISOString();+ this.zombies.set(row.id, { request_id: row.request_id, operation: row.operation, step: clock.step, waiting_on: clock.waitingOn,+ claimed_at: new Date(clock.claimedAt).toISOString(), abandoned_at: at, outlived_ceiling_at: at });+ void settled.then(() => { this.zombies.delete(row.id); });+ this.log('preparation', 'ceiling_exceeded', `request ${row.request_id} step=${clock.step ?? 'none'} waiting_on=${clock.waitingOn}${this.restartRequired() ? ' restart_required' : ''}`);+ await floorPreparationAttempts(this.engine, row.id, this.policy.maxAttempts).catch(error => this.report(error));+ });+ }private async execute(row: WriteRequest, root: RootHold): Promise<boolean> {let preparationActive = true;- 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.- const bounded = row.operation === 'remember' || (row.operation === 'put_page' || row.operation === 'edit_page') && !row.intent?.kind;- const budget = this.opts.preparationMs ?? 30_000;- const deadline = performance.now() + budget;- const timeout = bounded ? setTimeout(() => {- observation.deadline_exceeded = true;- abort.abort({ code: 'preparation_deadline' });- this.log('preparation', 'deadline_exceeded');- }, budget) : undefined;+ const policy = this.policy;+ // #6278: every kind has a budget with the switch on; off, only remember and intent-less put_page/edit_page (#5616) keep the 30 s one.+ const foregroundMs = this.opts.preparationMs ?? 30_000;+ const budget = policy.deadlines ? preparationBudgetMs(row, policy, foregroundMs) : preparationKind(row) === 'foreground' ? foregroundMs : undefined;const clock = startClaimPhase();+ // #6278: a request already at the attempt limit (a kill loop charged it at each reclaim) is finished without preparing again.+ if (policy.deadlines && (row.preparation_attempts ?? 0) >= policy.maxAttempts) {+ try {+ const previous = claimStateOf({ state: 'running', claim_phase: row.previous_claim_phase, execution_token: previousToken(row.previous_claim_phase) });+ const done = await finishPreparationStalled(this.engine, row, { step: previous?.step ?? null, waiting_on: previous?.waiting_on ?? 'unknown', limit: policy.maxAttempts }, false);+ this.log('preparation', 'preparation_stalled', failureLogText(done));+ return this.settled(done);+ } finally { this.preparing.delete(row.id); this.executing.delete(row.id); }+ }+ const prep = startPreparation(async signal => {+ await faultPoint('consumer:preparing', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation, signal });+ // Phase 4.3: a single page write prepares against one config read instead of one per key.+ return this.prepare(this.engine.kind === 'postgres' && singleWrite(row)+ && await writeSwitchOn(this.engine, 'single_write_group').catch(() => true) ? await preparationConfigView(this.engine) : this.engine,+ row, this.config, budget === undefined ? undefined : signal, clock);+ }, budget, { onDeadline: () => { observation.deadline_exceeded = true; this.log('preparation', 'deadline_exceeded'); } });+ const stop = () => prep.abort({ code: 'consumer_stopping' });+ this.abort.signal.addEventListener('abort', stop, { once: true });const lease = startClaimLease(signal => renewWriteClaim({ executeRaw: this.engine.executeRawDirect.bind(this.engine) }, row.id, row.execution_token!, this.opts.claimLeaseMs ?? 30_000,this.engine.kind === 'postgres' ? signal : undefined, claimPhaseStamp(clock, row.execution_token)),- this.leaseTiming(), () => abort.abort({ code: 'claim_lost' }));+ this.leaseTiming(), () => prep.abort({ code: 'claim_lost' }));const releaseReason = () => !lease.held ? 'claim_lost' : observation.deadline_exceeded ? 'preparation_deadline' : 'consumer_stopping';+ const stallInfo = () => ({ step: clock.step, waiting_on: clock.waitingOn, limit: policy.maxAttempts });try {- // Phase 4.3: a single page write prepares against one config read instead of one per key.- const preparation = (async () => this.prepare(this.engine.kind === 'postgres' && singleWrite(row)- && await writeSwitchOn(this.engine, 'single_write_group').catch(() => true) ? await preparationConfigView(this.engine) : this.engine,- row, this.config, bounded ? abort.signal : undefined))();- const prepared = await lease.whileHeld(preparation);- if (prepared === CLAIM_LOST) {- root.until = this.keepUntilSettled(preparation);+ // With the switch on the budget wins the race even against a preparer that ignores its signal; off, the preparer's own settlement decides.+ const raced = await lease.whileHeld(policy.deadlines ? prep.outcome : prep.work.then(result => ({ result })));+ if (raced === CLAIM_LOST) {+ root.until = this.abandonedRootBlock(row, clock, this.keepAbandoned(prep.work));await endLostLease(lease);await releaseUnpublishedClaim(this.engine, row, 'claim_lost');return false;}- if (timeout) clearTimeout(timeout);- if (bounded && performance.now() >= deadline && !abort.signal.aborted) {- observation.deadline_exceeded = true;- abort.abort({ code: 'preparation_deadline' });- this.log('preparation', 'deadline_exceeded');+ if ('deadline' in raced) {+ // The claim is released now, charged, whether or not the preparer settles; its late result never publishes (#6278).+ root.until = this.abandonedRootBlock(row, clock, this.keepAbandoned(prep.work));+ if (!lease.held || this.stopping) { await releaseUnpublishedClaim(this.engine, row, releaseReason()); return false; }+ if ((row.preparation_attempts ?? 0) + 1 >= policy.maxAttempts) {+ const done = await finishPreparationStalled(this.engine, row, stallInfo(), true);+ this.log('preparation', 'preparation_stalled', failureLogText(done));+ return this.settled(done);+ }+ await releaseUnpublishedClaim(this.engine, row, 'preparation_deadline', { charge: true });+ return false;}- if (!lease.held || this.stopping || abort.signal.aborted) {+ const prepared = raced.result;+ if (budget !== undefined && !prep.signal.aborted && prep.late()) prep.expire();+ if (!lease.held || this.stopping || prep.signal.aborted) {await releaseUnpublishedClaim(this.engine, row, releaseReason()); return false;}this.preparing.delete(row.id);@@ -661,8 +756,9 @@ export class PersistenceConsumer {}return settled ? isTerminal(done) : this.settled(done);} catch (error) {- if (preparationActive && bounded && performance.now() >= deadline) observation.deadline_exceeded = true;- if (preparationActive && (abort.signal.aborted || observation.deadline_exceeded)) {+ if (preparationActive && budget !== undefined && prep.late()) observation.deadline_exceeded = true;+ // #6278: the preparer's rejection on our own abort (its reason, an AbortError, a cancelled statement) is a release, never a receipt.+ if (preparationActive && (prep.signal.aborted || observation.deadline_exceeded || preparationAbortReason(error, prep.signal))) {await releaseUnpublishedClaim(this.engine, row, releaseReason());return false;}@@ -676,7 +772,6 @@ export class PersistenceConsumer {} finally {const renewal = lease.end();if (renewal) this.keepUntilSettled(renewal);- if (timeout) clearTimeout(timeout);this.abort.signal.removeEventListener('abort', stop); this.preparing.delete(row.id); this.executing.delete(row.id);}}@@ -721,6 +816,13 @@ export class PersistenceConsumer {await this.releaseIdleLane();await Promise.allSettled([...this.active]);await this.releaseIdleLane();+ // #6278: abandoned preparations (their claims are released and their signals aborted) get a short grace, not forever;+ // renewals and publications in `outlived` keep their bounded waits.+ if (this.abandoned.size) {+ let timer: ReturnType<typeof setTimeout> | undefined;+ await Promise.race([Promise.allSettled([...this.abandoned]), new Promise<void>(resolve => { timer = setTimeout(resolve, ABANDONED_STOP_GRACE_MS); })]);+ if (timer) clearTimeout(timer);+ }while (this.outlived.size) await Promise.all([...this.outlived]);await this.projectionWorker;await this.effectsWorker;diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex f74069c0e5..1656d2a40f 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -13,7 +13,9 @@ import { sha256 } from './digest.ts';import { authorizeStoredRequest } from './authority.ts';import { localHostId } from './identity.ts';import { acquireWorktree, getWorktreeBinding, guardOwnership, type WorktreeBinding } from './ownership.ts';-import { clearResolvedRecovery, completeWrite, getWriteRequestById, lockCounters, markRecovering, prepareRecovery, releaseUnpublishedClaim } from './journal.ts';+import { chargePreparationAttempt, clearResolvedRecovery, completeWrite, getWriteRequestById, lockCounters, markRecovering, prepareRecovery, releaseUnpublishedClaim } from './journal.ts';+import type { WaitingOn } from './claim-phase.ts';+import { preparationKind } from './preparation-budget.ts';import { isTerminal, principalKey, requestPrincipal, recoveryFiles, type FileRecoveryRecord, type RecoveryRecord, type WriteRequest } from './model.ts';import type { NativeLockHandle } from './native-lock.ts';import { withCoordinatedWrite } from './context.ts';@@ -138,6 +140,53 @@ export function transientDatabaseFailure(error: unknown): boolean {return ['40001','40P01','55P03','57014','53300','57P01','57P02','57P03','08000','08003','08006','08001','08004','ECONNRESET','ECONNREFUSED','ETIMEDOUT','CONNECTION_CLOSED','CONNECTION_ENDED'].includes(String((error as {code?:string})?.code));}+/**+ * #6278: the reasons a consumer aborts a preparation with. An error that is+ * that abort (the reason itself, an AbortError, or the Postgres cancel the+ * signal sent, 57014) is a release under that reason, never a terminal+ * `storage_error` or an uncounted `database_contention`; classify it before+ * `finishUnpublishedFailure`. Null when the error is the preparer's own.+ */+export type PreparationAbortReason = 'preparation_deadline' | 'consumer_stopping' | 'claim_lost';+const ABORT_REASONS: ReadonlySet<string> = new Set<PreparationAbortReason>(['preparation_deadline', 'consumer_stopping', 'claim_lost']);+export function preparationAbortReason(error: unknown, signal?: AbortSignal): PreparationAbortReason | null {+ const reason = signal?.aborted ? (signal.reason as { code?: unknown } | null)?.code : undefined;+ const own = typeof reason === 'string' && ABORT_REASONS.has(reason) ? reason as PreparationAbortReason : null;+ const e = error as { name?: unknown; code?: unknown; message?: unknown } | null;+ if (e && typeof e === 'object' && typeof e.code === 'string' && ABORT_REASONS.has(e.code)) return e.code as PreparationAbortReason;+ if (!own) return null;+ if (error === signal!.reason || e?.name === 'AbortError') return own;+ if (e?.code === '57014' && typeof e.message === 'string' && /canceling statement due to user request/.test(e.message)) return own;+ return null;+}++/** #6278: the owner-only detail of a `preparation_stalled` receipt: the last recorded step and the count that reached the limit. */+export interface PreparationStallDetail extends Pick<PublicationFailureDetail, 'stage' | 'attempt'> {+ origin: 'preparation_stall'; step: string | null; waiting_on: WaitingOn; attempts: number; limit: number;+}+export interface PreparationStallInfo { step: string | null; waiting_on: WaitingOn; attempts: number; limit: number }+export function preparationStalledFailure(row: WriteRequest, info: PreparationStallInfo): PublicationFailure {+ const kind = preparationKind(row);+ const where = info.step ? `, last at step ${info.step} (waiting on ${info.waiting_on})` : '';+ const fix = kind === 'sync'+ ? `Run gbrain sources writer status --source ${row.source_id} --json, then gbrain sources retry-held ${row.source_id}, then the same gbrain sync with the same options.`+ : `Run gbrain sources writer status --source ${row.source_id} --json, fix or report what the step was waiting on, then submit the write again with a new request_id.`;+ return { code: 'preparation_stalled',+ message: `Preparation of this write was cut off ${info.attempts} time(s) at its deadline${where}, the limit of persistence.max_preparation_attempts (${info.limit}); it is not claimed again. ${fix}`,+ detail: { origin: 'preparation_stall', step: info.step, waiting_on: info.waiting_on, attempts: info.attempts, limit: info.limit } as unknown as PublicationFailureDetail };+}+/**+ * #6278: finishes a claimed request `failed`/`preparation_stalled`: at claim+ * when its counter is already at the limit, or at the release that would+ * bring it there (`charge`, which counts that attempt first). Token-fenced+ * like every completion.+ */+export async function finishPreparationStalled(engine: BrainEngine, row: WriteRequest, info: Omit<PreparationStallInfo, 'attempts'>, charge: boolean): Promise<WriteRequest> {+ const attempts = charge ? await chargePreparationAttempt(engine, row) : row.preparation_attempts ?? info.limit;+ const failure = withAttempt(preparationStalledFailure(row, { ...info, attempts }), 'preparation');+ return engine.transaction(tx => completeWrite(tx, row, 'failed', {}, failure));+}+export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteRequest, error: unknown,stage: PublicationStage = 'publication'): Promise<WriteRequest> {const failure = withAttempt(requestError(error), stage);diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex d2808a89d4..a5a3bcc312 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -13,6 +13,7 @@ import { isFactsExtractionEnabled } from '../facts/extract.ts';import { loadConfig } from '../config.ts';import { resolveDefaultVisibility } from '../facts/visibility.ts';import { declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';+import { EXPIRED_PREPARING_CHARGE_SQL } from './claim-phase.ts';import { refreshFenceClear } from './worktree-refresh-schema.ts';import { pageBatchChildRequestIds } from './page-batch-id.ts';import { EFFECT_FAULT_POINTS, faultPoint } from './fault-points.ts';@@ -185,14 +186,21 @@ export async function claimCoalescedGitEffects(engine: BrainEngine, hostId: stri* mirror left running would otherwise also hold back writes to its pages.* Claims with a recovery record stay with the recovery path.*/-export async function releaseAbandonedClaims(engine: BrainEngine, processStartedAt: Date): Promise<number> {+/**+ * `chargePreparing` (#6278, the `preparation_deadlines` switch): a request whose+ * dead owner stamped the reclaimed claim `preparing` is charged one preparation+ * attempt, the same rule as the Postgres expired-claim sweep (consumer.ts), so a+ * kill loop reaches `persistence.max_preparation_attempts`.+ */+export async function releaseAbandonedClaims(engine: BrainEngine, processStartedAt: Date, chargePreparing = false): Promise<number> {if (engine.kind !== 'pglite') return 0;const effects = await engine.executeRaw(`UPDATE persistence_effects SET state='queued',execution_token=NULL,claim_expires_at=NULL,next_attempt_at=LEAST(next_attempt_at,now()) WHERE state='running' AND recovery IS NULL AND updated_at<$1::timestamptzAND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [processStartedAt.toISOString()]);- const requests = await engine.executeRaw(`UPDATE persistence_requests SET state='queued',execution_token=NULL,claim_expires_at=NULL+ const requests = await engine.executeRaw(`UPDATE persistence_requests r SET state='queued',execution_token=NULL,claim_expires_at=NULL,+ preparation_attempts=preparation_attempts+CASE WHEN $2::boolean THEN ${EXPIRED_PREPARING_CHARGE_SQL('r')} ELSE 0 ENDWHERE state='running' AND recovery IS NULL AND publication_started=false AND updated_at<$1::timestamptz- AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [processStartedAt.toISOString()]);+ AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [processStartedAt.toISOString(), chargePreparing]);return effects.length + requests.length;}diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex 0af4272676..074b61a0d2 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -14,8 +14,14 @@ import type { WriteRequest } from './model.ts';export type PublicationBoundary = Parameters<NonNullable<PublicationHooks['boundary']>>[0];export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${EffectKind}:mid`- | 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'consumer:prepared';-export interface FaultDetail { requestId?: string; effectId?: string | number; sourceId?: string; operation?: string | null }+ | 'effect_recovery:before_clear' | 'publication_recovery:before_clear' | 'sync:mid_checkpoint' | 'sync:before_group_admission' | 'sync:mid_waiver_run' | 'consumer:prepared'+ | 'consumer:preparing';+/**+ * `signal` (#6278, `consumer:preparing` only): the preparation's abort signal, so+ * a stalling hook can model both the reporter's cases: a preparer that honours+ * cancellation (settle on abort) and one that ignores it (hang on).+ */+export interface FaultDetail { requestId?: string; effectId?: string | number; sourceId?: string; operation?: string | null; signal?: AbortSignal }type FaultHook = (point: FaultPoint, detail: FaultDetail) => Promise<void> | void;/** The mid-effect seam of every effect kind; a new kind without one fails typecheck. */diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 146d7ee78d..a6107daeef 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -13,6 +13,7 @@ import { PreadmitBrainChanged } from './preadmit-cache.ts';import { pipelined } from '../page-state/transactions.ts';import { writeHealth, type WriteHealthFacts } from './health.ts';import { writerStamp } from './writer-versions.ts';+import { claimPhaseStamp, startClaimPhase } from './claim-phase.ts';import { publicFailureDetail } from './publication-failure.ts';import { catalogueError } from '../error-catalogue.ts';import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';@@ -322,31 +323,71 @@ export async function claimGroupFollowers(engine: BrainEngine, head: WriteRequesif (!head.worktree_id || max <= 0) return [];return engine.transactionDirect(async tx => {await declarePersistenceProtocol(tx);- const next = await tx.executeRaw<{ id: string; state: string; grp: string | null; recovering: boolean }>(`SELECT id,state,${GROUP_KEY_SQL} AS grp,recovery IS NOT NULL AS recovering+ const next = await tx.executeRaw<{ id: string; state: string; grp: string | null; recovering: boolean; claim_phase: unknown }>(`SELECT id,state,${GROUP_KEY_SQL} AS grp,recovery IS NOT NULL AS recovering,claim_phaseFROM persistence_requests WHERE worktree_id=$1::uuid AND sequence>$2 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL)ORDER BY sequence LIMIT $3 FOR UPDATE`, [head.worktree_id, head.sequence, max]);const members: string[] = [];+ const previous = new Map<string, unknown>();for (const row of next) {if (row.grp !== group || row.state !== 'queued' || row.recovering) break;members.push(row.id);+ previous.set(row.id, row.claim_phase);}if (!members.length) return [];const tokens = members.map(() => randomUUID());+ // #6278: a follower carries no stamp of its claim until its wave dispatches it (`markDispatched`), so an undispatched follower is never charged.return tx.executeRaw<WriteRequest>(`UPDATE persistence_requests r SET state='running',execution_token=t.token,- claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now(),blocked_reason=NULL+ claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now(),blocked_reason=NULL,claim_phase=NULLFROM unnest($1::uuid[],$2::uuid[]) AS t(id,token) WHERE r.id=t.id AND r.state='queued' RETURNING r.*`, [members, tokens, leaseMs])- .then(rows => rows.sort((a, b) => Number(BigInt(a.sequence) - BigInt(b.sequence))));+ .then(rows => rows.sort((a, b) => Number(BigInt(a.sequence) - BigInt(b.sequence))).map(row => ({ ...row, previous_claim_phase: previous.get(row.id) })));});}-/** Renews every claim of a group in one statement; returns the ids still held. */-export async function renewGroupClaims(engine: SqlEngine, rows: WriteRequest[], leaseMs = 30_000, signal?: AbortSignal, phase: string | null = null): Promise<Set<string>> {+/**+ * Renews every claim of a group in one statement; returns the ids still held.+ * `stamps` (#6176/#6278) are the members' `claimPhaseStamp`s in `rows` order+ * (null keeps a member's recorded stamp, for one not yet dispatched); a single+ * string is stamped on every member with its own token.+ */+export async function renewGroupClaims(engine: SqlEngine, rows: WriteRequest[], leaseMs = 30_000, signal?: AbortSignal,+ stamps: string | null | Array<string | null> = null): Promise<Set<string>> {+ const perMember = Array.isArray(stamps) ? stamps.map(stamp => stamp ?? null) : rows.map(() => stamps);const held = await engine.executeRaw<{ id: string }>(`UPDATE persistence_requests r SET claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now(),- claim_phase=COALESCE(jsonb_set($4::text::jsonb,'{token}',to_jsonb(t.token::text)),r.claim_phase)- FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token) WHERE r.id=t.id AND r.execution_token=t.token AND r.state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING r.id`,- [rows.map(row => row.id), rows.map(row => row.execution_token), leaseMs, phase], { signal });+ claim_phase=COALESCE(jsonb_set(t.stamp::jsonb,'{token}',to_jsonb(t.token::text)),r.claim_phase)+ FROM unnest($1::uuid[],$2::uuid[],$4::text[]) AS t(id,token,stamp) WHERE r.id=t.id AND r.execution_token=t.token AND r.state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING r.id`,+ [rows.map(row => row.id), rows.map(row => row.execution_token), leaseMs, perMember], { signal });return new Set(held.map(row => row.id));}+/**+ * #6278: a group's dispatch mark. Before a wave of members starts preparing,+ * each member's `preparing` stamp (its own token, start and step) is stored,+ * so a kill before the first renewal still charges exactly the members that+ * were preparing (the expired-claim reclaim, consumer.ts and effect-journal.ts)+ * and never an undispatched follower. Returns the ids whose claim still held.+ */+export async function markDispatched(engine: SqlEngine, members: Array<{ row: WriteRequest; stamp: string }>, signal?: AbortSignal): Promise<Set<string>> {+ if (!members.length) return new Set();+ const marked = await engine.executeRaw<{ id: string }>(`UPDATE persistence_requests r SET claim_phase=jsonb_set(t.stamp::jsonb,'{token}',to_jsonb(t.token::text))+ FROM unnest($1::uuid[],$2::uuid[],$3::text[]) AS t(id,token,stamp) WHERE r.id=t.id AND r.execution_token=t.token AND r.state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING r.id`,+ [members.map(m => m.row.id), members.map(m => m.row.execution_token), members.map(m => m.stamp)], { signal });+ return new Set(marked.map(row => row.id));+}+/**+ * #6278: an abandoned preparation overran the hard ceiling, which proves it+ * ignored cancellation: its request's counter is set to the limit so the next+ * claim finishes it `preparation_stalled`. Token-free (the claim was released+ * at the budget), terminal rows are left alone.+ */+export async function floorPreparationAttempts(engine: SqlEngine, id: string, limit: number): Promise<void> {+ await engine.executeRaw(`UPDATE persistence_requests SET preparation_attempts=GREATEST(preparation_attempts,$2::integer),updated_at=now()+ WHERE id=$1::uuid AND state IN ('queued','running') AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, [id, limit]);+}+/** #6278: charges one preparation attempt to a claim this owner still holds (before finishing it `preparation_stalled`). */+export async function chargePreparationAttempt(engine: SqlEngine, row: WriteRequest): Promise<number> {+ const [charged] = await engine.executeRaw<{ preparation_attempts: number }>(`UPDATE persistence_requests SET preparation_attempts=preparation_attempts+1,updated_at=now()+ WHERE id=$1::uuid AND execution_token=$2::uuid AND state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING preparation_attempts`, [row.id, row.execution_token]);+ return charged?.preparation_attempts ?? (row.preparation_attempts ?? 0) + 1;+}/*** F0: a write to a worktree under an active `gbrain sources refresh` is refused@@ -479,13 +520,15 @@ export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseM]) as [unknown, WriteRequest[]];if (!row) return null;// `passed_sync`: the claimed row went ahead of a queued sync row of its root.+ // #6278: the claim stamps its own `preparing` phase, so a kill before the first renewal is charged like any other.+ const token = randomUUID();const [claimed] = await tx.executeRaw<WriteRequest & { passed_sync: boolean }>(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,claim_expires_at=now()+($3::double precision*interval '1 millisecond'),- updated_at=now(),blocked_reason=NULL WHERE id=$1::uuid RETURNING *,EXISTS (SELECT 1 FROM persistence_requests earlier+ updated_at=now(),blocked_reason=NULL,claim_phase=$4::text::jsonb WHERE id=$1::uuid RETURNING *,EXISTS (SELECT 1 FROM persistence_requests earlierWHERE earlier.worktree_id=persistence_requests.worktree_id AND earlier.sequence<persistence_requests.sequenceAND earlier.state='queued' AND ${SYNC_KIND('earlier')}) AS passed_sync`,- [row.id, randomUUID(), leaseMs]);- return claimed ?? null;+ [row.id, token, leaseMs, claimPhaseStamp(startClaimPhase(), token)]);+ return claimed ? { ...claimed, previous_claim_phase: row.claim_phase } : null;});}/**@@ -526,10 +569,12 @@ export async function claimNextLaneHead(engine: BrainEngine, hostId: string, worAND c.state='committed' AND NOT ${SYNC_KIND('c')}))ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, worktreeId, run, seenSequence]);if (!row) return null;+ const token = randomUUID();const [claimed] = await tx.executeRaw<WriteRequest & { seen_sequence: string }>(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,claim_expires_at=now()+($3::double precision*interval '1 millisecond'),- updated_at=now(),blocked_reason=NULL WHERE id=$1::uuid RETURNING *,(SELECT max(sequence) FROM persistence_requests)::text AS seen_sequence`, [row.id, randomUUID(), leaseMs]);- return claimed;+ updated_at=now(),blocked_reason=NULL,claim_phase=$4::text::jsonb WHERE id=$1::uuid RETURNING *,(SELECT max(sequence) FROM persistence_requests)::text AS seen_sequence`,+ [row.id, token, leaseMs, claimPhaseStamp(startClaimPhase(), token)]);+ return claimed ? { ...claimed, previous_claim_phase: row.claim_phase } : claimed;});}/** `phase` (claim-phase.ts `claimPhaseStamp`, #6176) records the claim's current phase with the renewal. */@@ -539,10 +584,12 @@ export async function renewWriteClaim(engine: SqlEngine, id: string, token: striWHERE id=$1::uuid AND execution_token=$2::uuid AND state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [id, token, leaseMs, phase], { signal });return rows.length === 1;}-export async function releaseUnpublishedClaim(engine: SqlEngine, row: WriteRequest, reason: string): Promise<void> {+/** `charge` (#6278): a `preparation_deadline` release counts one preparation attempt; `claim_lost`, `consumer_stopping` and the rest never do. */+export async function releaseUnpublishedClaim(engine: SqlEngine, row: WriteRequest, reason: string, opts: { charge?: boolean } = {}): Promise<void> {await engine.executeRaw(`UPDATE persistence_requests SET state='queued',execution_token=NULL,claim_expires_at=NULL,- blocked_reason=$3,updated_at=now() WHERE id=$1::uuid AND execution_token=$2::uuid- AND state='running' AND recovery IS NULL AND publication_started=false AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, [row.id, row.execution_token, reason]);+ blocked_reason=$3,updated_at=now(),preparation_attempts=preparation_attempts+CASE WHEN $4::boolean THEN 1 ELSE 0 END+ WHERE id=$1::uuid AND execution_token=$2::uuid+ AND state='running' AND recovery IS NULL AND publication_started=false AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, [row.id, row.execution_token, reason, opts.charge === true]);}/** Called while holding the root lock; the durable record precedes any rename. */@@ -635,9 +682,10 @@ export async function clearResolvedRecoveries(engine: BrainEngine, rows: WriteRe/** #6007: claims again a request this owner pass released to the queue itself, while it still holds the worktree's native lock. */export async function reclaimReleasedWrite(engine: BrainEngine, id: string, leaseMs = 30_000): Promise<WriteRequest | null> {+ const token = randomUUID();const [claimed] = await engine.executeRawDirect<WriteRequest>(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,- claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now(),blocked_reason=NULL- WHERE id=$1::uuid AND state='queued' AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [id, randomUUID(), leaseMs]);+ claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now(),blocked_reason=NULL,claim_phase=$4::text::jsonb+ WHERE id=$1::uuid AND state='queued' AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [id, token, leaseMs, claimPhaseStamp(startClaimPhase(), token)]);return claimed ?? null;}diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 37316fb8b8..97bd712480 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -90,7 +90,11 @@ export interface WriteRequest {compacted: boolean;publication_started: boolean;/** #6278 (v221): preparations cut off by a deadline or an expired `preparing` claim; reset by a commit. Absent on rows read before the migration. */+ /** #6176 (v217): the owner's claim-phase stamp (claim-phase.ts), read back by `claimStateOf`; absent on rows read before the migration. */+ claim_phase?: unknown;preparation_attempts?: number;+ /** #6278: on a row the claim statements return: the stamp the previous claim left (its last recorded step). Never stored. */+ previous_claim_phase?: unknown;created_at: Date | string;updated_at: Date | string;completed_at: Date | string | null;diff --git a/src/core/persistence/preparation-budget.ts b/src/core/persistence/preparation-budget.tsindex c3d20c9d51..1028a15229 100644--- a/src/core/persistence/preparation-budget.ts+++ b/src/core/persistence/preparation-budget.ts@@ -125,49 +125,64 @@ export function preparationBudgetMs(row: Pick<WriteRequest, 'operation' | 'intenreturn kind === 'foreground' ? foregroundMs : kind === 'sync' ? policy.syncMs : policy.maintenanceMs;}-/** What `racePreparation` yields when the budget passes before the work settles. */+/** What a preparation's `outcome` yields when the budget passes before the work settles. */export const PREPARATION_DEADLINE: unique symbol = Symbol('preparation_deadline');+export type PreparationOutcome<T> = { result: T } | { deadline: typeof PREPARATION_DEADLINE };+export interface PreparationRun<T> {+ /** The preparer's own promise; after a deadline the caller owns it and must never publish its result. */+ work: Promise<T>;+ /** The result, or the deadline when the budget passes first (the work keeps running); a failure inside the budget rejects. */+ outcome: Promise<PreparationOutcome<T>>;+ /** The preparer's signal: aborted `{ code: 'preparation_deadline' }` at the budget, or with `abort(reason)`'s reason. */+ signal: AbortSignal;+ /** Cancels the preparer for another reason (a lost claim, a stopping consumer); the outcome then follows the work. */+ abort(reason: unknown): void;+ /** Whether the budget has passed (by timer, or by `late()` when the work settled after it). */+ readonly expired: boolean;+ /** Whether the budget passed on the clock, for a synchronous preparation that outran the timer. */+ late(): boolean;+ /** Treats the preparation as over budget now (aborts it, runs `onDeadline`). */+ expire(): void;+}/**- * Runs `work` with a signal that aborts `{ code: 'preparation_deadline' }` at- * the budget and yields PREPARATION_DEADLINE then, whether or not the work- * honours the signal; the work keeps running and the caller owns it (it must- * never publish a late result). `signal` (an outer cancellation) aborts the- * work's signal too and rejects the race with the outer reason. The budget is- * measured by `now`, so a synchronous late preparation that outruns the timer- * still reads as a deadline.+ * Starts `work` under a budget. The budget wins the `outcome` race whether or+ * not the preparer honours its signal (the deadline settles before the abort+ * reaches the work, so a preparer that rejects on abort cannot win), and a+ * result that lands after the budget on the clock still reads as a deadline.+ * `budgetMs` undefined means no deadline: the outcome follows the work.*/-export async function racePreparation<T>(work: (signal: AbortSignal) => Promise<T>, budgetMs: number,- opts: { signal?: AbortSignal; now?: () => number; onDeadline?: () => void } = {}): Promise<{ result: T } | { deadline: typeof PREPARATION_DEADLINE; work: Promise<T> }> {+export function startPreparation<T>(work: (signal: AbortSignal) => Promise<T>, budgetMs: number | undefined,+ opts: { now?: () => number; onDeadline?: () => void } = {}): PreparationRun<T> {const now = opts.now ?? (() => performance.now());const abort = new AbortController();- const deadline = Promise.withResolvers<typeof PREPARATION_DEADLINE>();+ const deadline = Promise.withResolvers<{ deadline: typeof PREPARATION_DEADLINE }>();let expired = false;- // The deadline settles before the abort reaches the work, so a preparer that rejects on abort never wins the race.const expire = () => {if (expired) return;expired = true;- deadline.resolve(PREPARATION_DEADLINE);+ deadline.resolve({ deadline: PREPARATION_DEADLINE });if (!abort.signal.aborted) abort.abort({ code: 'preparation_deadline' });opts.onDeadline?.();};- const timer = setTimeout(expire, budgetMs);- const outer = Promise.withResolvers<never>();- const onOuter = () => { abort.abort(opts.signal?.reason); outer.reject(opts.signal?.reason); };- if (opts.signal?.aborted) onOuter(); else opts.signal?.addEventListener('abort', onOuter, { once: true });- outer.promise.catch(() => undefined);+ const timer = budgetMs === undefined ? undefined : setTimeout(expire, budgetMs);const started = now();+ const late = () => budgetMs !== undefined && (expired || now() - started >= budgetMs);const run = (async () => work(abort.signal))();run.catch(() => undefined);- const late = () => expired || now() - started >= budgetMs;- try {- const won = await Promise.race([run.then(result => ({ result })), deadline.promise.then(deadline => ({ deadline, work: run })), outer.promise]);- if ('result' in won && late()) { expire(); return { deadline: PREPARATION_DEADLINE, work: run }; }- return won;- } catch (error) {- if (!opts.signal?.aborted && late()) { expire(); return { deadline: PREPARATION_DEADLINE, work: run }; }- throw error;- } finally {- clearTimeout(timer);- opts.signal?.removeEventListener('abort', onOuter);- }+ const outcome = (async (): Promise<PreparationOutcome<T>> => {+ try {+ const won = await Promise.race([run.then(result => ({ result })), deadline.promise]);+ if ('result' in won && late()) { expire(); return { deadline: PREPARATION_DEADLINE }; }+ return won;+ } catch (error) {+ if (late()) { expire(); return { deadline: PREPARATION_DEADLINE }; }+ throw error;+ } finally { if (timer) clearTimeout(timer); }+ })();+ outcome.catch(() => undefined);+ return { work: run, outcome, signal: abort.signal, abort: reason => { if (!abort.signal.aborted) abort.abort(reason); }, get expired() { return expired; }, late, expire };+}+/** The outcome alone: the sync's out-of-consumer preparations (waivers, origin equivalence) race their work against the budget this way. */+export function racePreparation<T>(work: (signal: AbortSignal) => Promise<T>, budgetMs: number, opts: { now?: () => number; onDeadline?: () => void } = {}): Promise<PreparationOutcome<T>> {+ return startPreparation(work, budgetMs, opts).outcome;}diff --git a/test/persistence-consumer-scheduling.test.ts b/test/persistence-consumer-scheduling.test.tsindex 341524d47b..66b102db27 100644--- a/test/persistence-consumer-scheduling.test.ts+++ b/test/persistence-consumer-scheduling.test.ts@@ -4,7 +4,8 @@ import { mkdtempSync, rmSync } from 'node:fs';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 { ABANDONED_STOP_GRACE_MS, PersistenceConsumer } from '../src/core/persistence/consumer.ts';+import { resetWriteSwitches } from '../src/core/persistence/switches.ts';import { admitWrite, getWriteRequestById, WRITE_PROGRESS_SQL } from '../src/core/persistence/journal.ts';import { cancelWriteRequest } from '../src/core/persistence/control.ts';import { publishMutation } from '../src/core/persistence/coordinator.ts';@@ -198,7 +199,10 @@ test('distinct stalled receipt reads stay capped and shutdown drains every retai} finally { for (const release of releases) release.resolve([]); await disposePersistenceConsumer(proxy); }}), 5000);-for (const cooperates of [true, false]) test(`preparation deadline retains tracking and fences late results (cooperative=${cooperates})`, async () => withEnv(env, async () => {+// #6278: this pair pins the pre-deadline behaviour (a preparer that ignores its signal stays `running` past the budget) and+// runs verbatim with the `preparation_deadlines` switch off; the switch-on variants follow it.+for (const cooperates of [true, false]) test(`preparation deadline retains tracking and fences late results (cooperative=${cooperates})`, async () => withEnv({ ...env, GBRAIN_PREPARATION_DEADLINES: '0' }, async () => {+ resetWriteSwitches();const sources = await fixtures(engine, config);const row = await admitWrite(engine, admission(config, sources[0], `deadline-${cooperates}`, 'deadline body'));const release = Promise.withResolvers<void>();@@ -229,10 +233,146 @@ for (const cooperates of [true, false]) test(`preparation deadline retains track} finally {release.resolve();await consumer.stop();+ resetWriteSwitches();await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);}}), 5000);+/**+ * #6278, switch on: the budget releases the claim whether or not the preparer honours its signal. The non-cooperative+ * preparer's request is back in the queue at the budget with `preparation_deadline` and one counted attempt while the+ * abandoned preparation still runs (the #5373 root barrier holds, so the root is not claimed again until it settles);+ * its late result never publishes and the counters conserve.+ */+for (const cooperates of [true, false]) test(`preparation deadline releases the claim at the budget and counts the attempt (cooperative=${cooperates}, #6278)`, async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const row = await admitWrite(engine, admission(config, sources[0], `deadline-switch-on-${cooperates}`, 'deadline body'));+ const release = Promise.withResolvers<void>();+ let attempts = 0;+ let aborted = false;+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_e, current, _c, signal?: AbortSignal) => {+ attempts++;+ signal?.addEventListener('abort', () => { aborted = true; if (cooperates) release.resolve(); }, { once: true });+ await release.promise;+ if (cooperates) signal?.throwIfAborted();+ return prepared(current, sources);+ }, { hostId: config.hostId, pollMs: 60_000, preparationMs: 50, preparationBudgets: { maxAttempts: 5, ceilingMs: 60_000 } });+ try {+ consumer.start();+ await waitFor(() => attempts === 1);+ await waitFor(async () => (await getWriteRequestById(engine, row.id))?.state === 'queued', { timeoutMs: 2_000, label: 'the budget releases the claim' });+ expect(aborted).toBe(true);+ expect(attempts).toBe(1);+ const released = await getWriteRequestById(engine, row.id);+ expect(released).toMatchObject({ state: 'queued', blocked_reason: 'preparation_deadline', preparation_attempts: 1 });+ if (!cooperates) {+ // The preparer still runs: the slot is free, the root is still blocked by it, nothing is re-claimed meanwhile.+ await Bun.sleep(150);+ expect(consumer.status()).toMatchObject({ active_preparations: 0, abandoned_preparations: 1, restart_required: false, outlived_ceiling: [] });+ expect(attempts).toBe(1);+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('queued');+ }+ release.resolve();+ await waitFor(() => consumer.status().abandoned_preparations === 0);+ expect(await engine.readPageSnapshot(row.slug, { sourceId: row.source_id })).toBeNull();+ await assertConservation(engine);+ } finally {+ release.resolve();+ await consumer.stop();+ await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id);+ }+}), 5000);++test('an abandoned preparation past the hard ceiling frees its root, pins the counter at the limit and the next claim fails preparation_stalled (#6278)', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const stuck = await admitWrite(engine, admission(config, sources[0], 'ceiling/stuck', 'stuck body'));+ const behind = await admitWrite(engine, admission(config, sources[0], 'ceiling/behind', 'behind body'));+ const never = Promise.withResolvers<ReturnType<typeof prepared>>();+ const attempts: string[] = [];+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_e, current) => {+ attempts.push(current.id);+ return current.id === stuck.id ? never.promise : prepared(current, sources);+ }, { hostId: config.hostId, pollMs: 20, preparationMs: 30, preparationBudgets: { maxAttempts: 3, ceilingMs: 200 }, onError: () => {} });+ try {+ consumer.start();+ await waitFor(async () => (await getWriteRequestById(engine, stuck.id))?.blocked_reason === 'preparation_deadline', { timeoutMs: 2_000 });+ // Until the ceiling the root waits on the zombie: the write behind it is not claimed.+ expect((await getWriteRequestById(engine, behind.id))?.state).toBe('queued');+ expect(attempts).toEqual([stuck.id]);+ await waitFor(() => consumer.status().restart_required, { timeoutMs: 2_000, label: 'the ceiling passes and the zombie is isolated' });+ expect(consumer.status().outlived_ceiling).toEqual([expect.objectContaining({ request_id: stuck.request_id, operation: 'put_page', step: null, waiting_on: 'unknown' })]);+ await waitFor(async () => (await getWriteRequestById(engine, stuck.id))?.preparation_attempts === 3, { timeoutMs: 2_000, label: 'the overrun pins the counter at the limit' });+ // At the zombie cap this process claims nothing more; a process that still claims it finishes it without preparing again.+ await Bun.sleep(100);+ expect(attempts).toEqual([stuck.id]);+ const fresh = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_e, current) => { attempts.push(current.id); return prepared(current, sources); },+ { hostId: config.hostId, pollMs: 20, preparationBudgets: { maxAttempts: 3 }, onError: () => {} });+ try {+ fresh.start();+ await waitFor(async () => (await getWriteRequestById(engine, stuck.id))?.state === 'failed', { timeoutMs: 3_000, label: 'the next claim fails it preparation_stalled' });+ const failed = (await getWriteRequestById(engine, stuck.id))!;+ expect(failed).toMatchObject({ state: 'failed', error_code: 'preparation_stalled', preparation_attempts: 3 });+ expect(failed.error_message).toContain('persistence.max_preparation_attempts (3)');+ expect(failed.error_detail).toMatchObject({ origin: 'preparation_stall', attempts: 3, limit: 3, stage: 'preparation' });+ await waitFor(async () => (await getWriteRequestById(engine, behind.id))?.state === 'committed', { timeoutMs: 3_000, label: 'the root moves on' });+ expect(attempts.filter(id => id === stuck.id)).toHaveLength(1);+ } finally { await fresh.stop(); }+ never.resolve(prepared(stuck, sources));+ await waitFor(() => consumer.status().outlived_ceiling.length === 0);+ expect(await engine.readPageSnapshot(stuck.slug, { sourceId: stuck.source_id })).toBeNull();+ await assertConservation(engine);+ } finally {+ never.resolve(prepared(stuck, sources));+ await consumer.stop();+ for (const row of [stuck, behind]) await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id).catch(() => {});+ }+}), 15_000);++test('the release that brings the counter to the limit finishes the request failed/preparation_stalled, and a waiting put_page caller receives it (#6278)', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const row = await admitWrite(engine, admission(config, sources[0], 'limit/foreground', 'poisoned body'));+ let attempts = 0;+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_e, _current, _c, signal?: AbortSignal) => {+ attempts++;+ // Honours cancellation but never finishes inside its budget: the reporter's cooperative shape.+ return new Promise<never>((_, reject) => signal?.addEventListener('abort', () => reject(signal.reason), { once: true }));+ }, { hostId: config.hostId, pollMs: 20, preparationMs: 30, preparationBudgets: { maxAttempts: 2 }, onError: () => {} });+ try {+ consumer.start();+ const waited = await awaitWrite(engine, row, { engine: 'pglite' }, { waitMs: 5_000 });+ expect(waited.kind).toBe('terminal');+ expect(waited.row).toMatchObject({ state: 'failed', error_code: 'preparation_stalled', preparation_attempts: 2 });+ expect(attempts).toBe(2);+ expect(waited.row.error_message).toContain('submit the write again with a new request_id');+ expect(await engine.readPageSnapshot(row.slug, { sourceId: row.source_id })).toBeNull();+ await assertConservation(engine);+ } finally { await disposePersistenceConsumer(engine); await consumer.stop(); }+}), 10_000);++test('a stopping consumer gives abandoned preparations a bounded grace instead of waiting forever (#6278)', async () => withEnv(env, async () => {+ const sources = await fixtures(engine, config);+ const row = await admitWrite(engine, admission(config, sources[0], 'stop/abandoned', 'abandoned body'));+ const never = Promise.withResolvers<ReturnType<typeof prepared>>();+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async () => never.promise,+ { hostId: config.hostId, pollMs: 60_000, preparationMs: 30, preparationBudgets: { maxAttempts: 5, ceilingMs: 60_000 } });+ try {+ consumer.start();+ await waitFor(async () => (await getWriteRequestById(engine, row.id))?.blocked_reason === 'preparation_deadline', { timeoutMs: 2_000 });+ expect(consumer.status().abandoned_preparations).toBe(1);+ const started = performance.now();+ await consumer.stop();+ expect(performance.now() - started).toBeLessThan(ABANDONED_STOP_GRACE_MS + 2_000);+ expect(performance.now() - started).toBeGreaterThanOrEqual(ABANDONED_STOP_GRACE_MS - 50);+ never.resolve(prepared(row, sources));+ await Bun.sleep(50);+ expect(await engine.readPageSnapshot(row.slug, { sourceId: row.source_id })).toBeNull();+ } finally {+ never.resolve(prepared(row, sources));+ await consumer.stop();+ await cancelWriteRequest(engine, { kind: 'local_cli', id: config.principalIds[0] }, row.request_id).catch(() => {});+ }+}), 15_000);+test('an edit_page preparation shares the preparation deadline (#5616)', async () => withEnv(env, async () => {const sources = await fixtures(engine, config);const row = await admitWrite(engine, admission(config, sources[0], 'edit-page-deadline', 'edited body', 0, { operation: 'edit_page' }));diff --git a/test/persistence-preparation-budget.test.ts b/test/persistence-preparation-budget.test.tsindex 86c2b4bd71..908adbf884 100644--- a/test/persistence-preparation-budget.test.ts+++ b/test/persistence-preparation-budget.test.ts@@ -12,7 +12,7 @@*/import { afterEach, describe, expect, test } from 'bun:test';import { DEFAULT_PREPARATION_POLICY, PREPARATION_BUDGET_KEYS, PREPARATION_DEADLINE, preparationBudgetMs, preparationKind, racePreparation,- resolvePreparationPolicy, validatePreparationConfigValue } from '../src/core/persistence/preparation-budget.ts';+ resolvePreparationPolicy, startPreparation, validatePreparationConfigValue } from '../src/core/persistence/preparation-budget.ts';import { readPreparationPolicy, readWriteSwitches, resetWriteSwitches, WRITE_SWITCHES } from '../src/core/persistence/switches.ts';import { withEnv } from './helpers/with-env.ts';@@ -85,7 +85,7 @@ describe('preparation_deadlines switch', () => {});});-describe('racePreparation', () => {+describe('startPreparation / racePreparation', () => {test('a preparation inside its budget yields its result and never aborts', async () => {let signal: AbortSignal | undefined;const raced = await racePreparation(async s => { signal = s; await sleep(10); return 'prepared'; }, 500);@@ -93,20 +93,22 @@ describe('racePreparation', () => {expect(signal?.aborted).toBe(false);});test('a preparer that honours its signal is cut off at the budget: the deadline wins, not its abort rejection', async () => {- const raced = await racePreparation(async signal => new Promise<string>((_, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true })), 20);- expect('deadline' in raced && raced.deadline).toBe(PREPARATION_DEADLINE);- if ('deadline' in raced) await expect(raced.work).rejects.toMatchObject({ code: 'preparation_deadline' });+ const run = startPreparation(async signal => new Promise<string>((_, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true })), 20);+ expect(await run.outcome).toEqual({ deadline: PREPARATION_DEADLINE });+ expect(run.expired).toBe(true);+ await expect(run.work).rejects.toMatchObject({ code: 'preparation_deadline' });});test('a preparer that ignores its signal is cut off at the budget too, and its late result is left to the caller', async () => {const release = Promise.withResolvers<string>();let seen = 0;const started = performance.now();- const raced = await racePreparation(async () => release.promise, 20, { onDeadline: () => { seen++; } });+ const run = startPreparation(async () => release.promise, 20, { onDeadline: () => { seen++; } });+ expect(await run.outcome).toEqual({ deadline: PREPARATION_DEADLINE });expect(performance.now() - started).toBeGreaterThanOrEqual(15);- expect('deadline' in raced).toBe(true);+ expect(run.signal.aborted).toBe(true);expect(seen).toBe(1);release.resolve('late');- if ('deadline' in raced) expect(await raced.work).toBe('late');+ expect(await run.work).toBe('late');});test('a synchronous preparation that outruns the timer still reads as a deadline (resolve and reject)', async () => {for (const reject of [false, true]) {@@ -116,19 +118,20 @@ describe('racePreparation', () => {if (reject) throw new DOMException('late', 'AbortError');return 'late';}, 10);- expect('deadline' in raced).toBe(true);+ expect(raced).toEqual({ deadline: PREPARATION_DEADLINE });}});- test('a real failure inside the budget propagates', async () => {+ test('a real failure inside the budget propagates; without a budget the outcome follows the work', async () => {await expect(racePreparation(async () => { throw new Error('boom'); }, 500)).rejects.toThrow('boom');+ const unbounded = startPreparation(async () => { await sleep(30); return 'done'; }, undefined);+ expect(unbounded.late()).toBe(false);+ expect(await unbounded.outcome).toEqual({ result: 'done' });+ expect(unbounded.expired).toBe(false);});- test('an outer cancellation aborts the work with its own reason and rejects the race', async () => {- const outer = new AbortController();- let reason: unknown;- const racing = racePreparation(async signal => new Promise<never>((_, reject) => signal.addEventListener('abort', () => { reason = signal.reason; reject(signal.reason); }, { once: true })),- 5_000, { signal: outer.signal });- outer.abort({ code: 'consumer_stopping' });- await expect(racing).rejects.toMatchObject({ code: 'consumer_stopping' });- expect(reason).toMatchObject({ code: 'consumer_stopping' });+ test('abort(reason) cancels the preparer with that reason and the outcome follows the work, not the deadline', async () => {+ const run = startPreparation(async signal => new Promise<never>((_, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true })), 5_000);+ run.abort({ code: 'consumer_stopping' });+ await expect(run.outcome).rejects.toMatchObject({ code: 'consumer_stopping' });+ expect(run.expired).toBe(false);});});