Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
persistence: transient interruptions get their own bounded retry budget with backoff (LPH b/c)
garrytan3e06fd59a366
diff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.tsindex b4fcf64816..33dcc7fefe 100644--- a/src/commands/doctor/checks/persistence-requests.ts+++ b/src/commands/doctor/checks/persistence-requests.ts@@ -173,7 +173,7 @@ export async function writeStallCheck(engine: BrainEngine): Promise<Check> {? `${claim.why} No request on this root reached a terminal state during the claim window, even though its claim was renewed.` : claim.why }];});const details = { max_claim_ms: maxClaimMs, config_key: MAX_CLAIM_CONFIG_KEY, count: stalls.length, stalls, docs,- preparation_policy: { sync_preparation_ms: policy.syncMs, maintenance_preparation_ms: policy.maintenanceMs, preparation_ceiling_ms: policy.ceilingMs, max_preparation_attempts: policy.maxAttempts } };+ preparation_policy: { sync_preparation_ms: policy.syncMs, maintenance_preparation_ms: policy.maintenanceMs, preparation_ceiling_ms: policy.ceilingMs, max_preparation_attempts: policy.maxAttempts, max_transient_retries: policy.transientRetries } };if (!stalls.length) return { name: 'persistence_write_stall', status: 'ok', details,message: `No write request has held its claim longer than ${MAX_CLAIM_CONFIG_KEY} (${maxClaimMs} ms).` };const first = stalls[0]!;diff --git a/src/core/config.ts b/src/core/config.tsindex f64a6ba6c5..874c586f71 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1780,6 +1780,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['persistence.limits.brain_recovery_bytes', 'persistence.limits.worktree_recovery_bytes','persistence.receipt_retention_days', 'persistence.unbound_write', 'persistence.max_claim_ms', // #5254: persistence/unbound-source.ts; #6176: persistence/claim-phase.ts'persistence.sync_preparation_ms', 'persistence.maintenance_preparation_ms', 'persistence.preparation_ceiling_ms', 'persistence.max_preparation_attempts', 'persistence.preparation_deadlines', // #6278: persistence/preparation-budget.ts, switches.ts+ 'persistence.max_transient_retries', // large-pages hardening (b): persistence/preparation-budget.ts, transient-retry.ts'persistence.publication_ceiling_ms', 'persistence.terminal_failures.window_days', 'persistence.terminal_failures.spike_factor', 'persistence.terminal_failures.spike_min', // #6405: persistence/sync-drain.ts (in-pass publication ceiling); #6650: persistence/terminal-failures.ts'persistence.capacity.warn_days', 'persistence.capacity.fail_days', 'persistence.capacity.background_pause_pct', // #6696: persistence/capacity-forecast.ts, admission-origin.ts'persistence.maintenance.compaction_stale_hours', // #6696 (A11): persistence/compaction-pass.ts, doctor persistence_compactiondiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex e885922ff7..b998703ee3 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -645,8 +645,8 @@ export const CODES = {write_gate_rejected: { class: 'caller', summary: "The write gate refused external instruction-like content because the operator set `write_gate.external_mode` to `reject`.", why: "Text from an untrusted source that reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request) is refused instead of held under that setting, so nothing was written. The same content refuses on every retry.", reasons: ['override', 'standing_instruction', 'exfiltration', 'credential', 'detector_error'], suggestion: 'Tell the user the content was refused; whether to accept it or switch `write_gate.external_mode` back to `quarantine` is their decision.' },write_held: { class: 'consent', summary: "The write gate held this content for the owner's review instead of saving it as memory.", why: "Content from an untrusted source read like an instruction to an agent, so it was quarantined in the write-gate holding table. It is not searchable or recalled until the owner releases it; retrying the same write only re-opens the same hold.", reasons: ['override', 'standing_instruction', 'exfiltration', 'credential', 'detector_error'], actor: 'user', exit: 3, suggestion: 'Do not retry. Tell the user what was held and give them the release command from the fix; releasing is their decision.' },write_interrupted: { class: 'retryable', retryable: false, actor: 'agent',- summary: "The database ended this managed write's statements (SQLSTATE 57014, a statement timeout or cancel) persistence.max_preparation_attempts times (default 2), so the owner finished it failed instead of preparing it again; nothing was published.",- why: "Each cancelled statement throws the write's preparation away, and a write whose work outlasts the bound every time (a large page publishing under a 5 s statement bound on a loaded host) used to be released as database_contention and prepared again, its whole body streamed again, without limit. These cancellations now count with cut-off preparations. Contention with other transactions (lock timeout, serialization failure, deadlock), a dropped connection and a restarting database are never counted. The receipt names the attempts, the limit and the SQLSTATE.",+ summary: "The database kept ending this managed write's statements (SQLSTATE 57014, a statement timeout or cancel), or its publication kept running past persistence.publication_ceiling_ms and was cancelled, after persistence.max_transient_retries retries with backoff (default 5), so the owner finished it failed instead of preparing it again; nothing was published.",+ why: "Each such interruption throws the write's preparation away. It is load or latency, not the write's content, so it has its own retry budget: the request is claimed again after a backoff (1 s, 2 s, 4 s, 8 s, then 15 s; no claim is held while it waits) up to persistence.max_transient_retries times, and the next interruption ends it instead of preparing it again without limit. It never charges persistence.max_preparation_attempts, which preparations cut off at their deadline keep. Contention with other transactions (lock timeout, serialization failure, deadlock), a dropped connection and a restarting database are never counted. The receipt names the interruptions (attempts), the retry limit, the cause and the SQLSTATE.",docs: 'docs/guides/write-refusals.md#write_interrupted',suggestion: 'Inspect the owner with gbrain sources writer status --source <id> --json (read-only), then submit the write again with a new request_id once the database is less loaded; a held sync file needs gbrain sources retry-held <id> and the same sync. If the same write ends this way again, report its request id with gbrain doctor --json.',fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: 'Read-only: the owner process, its pool and what its writes wait on.', requires_exclusive: false } },diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 3bc05957b6..62c18d58cd 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -784,14 +784,14 @@ export class PersistenceConsumer implements PersistenceConsumerLike {}status() {const drain = this.draining;- const { deadlines, syncMs, maintenanceMs, ceilingMs, maxAttempts } = this.policy;+ const { deadlines, syncMs, maintenanceMs, ceilingMs, maxAttempts, transientRetries } = 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 },+ preparation_policy: { deadlines, sync_preparation_ms: syncMs, maintenance_preparation_ms: maintenanceMs, preparation_ceiling_ms: ceilingMs, max_preparation_attempts: maxAttempts, max_transient_retries: transientRetries },abandoned_preparations: this.abandoned.size,outlived_ceiling: [...this.zombies.values()].map(value => ({ ...value })),restart_required: this.restartRequired(),diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 49f10e92d2..799827e928 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -15,7 +15,8 @@ import { localHostId } from './identity.ts';import { acquireWorktree, getWorktreeBinding, guardOwnership, type WorktreeBinding } from './ownership.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 { PREPARATION_BUDGET_KEYS, preparationKind } from './preparation-budget.ts';+import { chargeTransientInterruption, transientInterruption, type TransientInterruption } from './transient-retry.ts';import { readWriteSwitchSnapshot } from './switches.ts';import { isSharedReadFailure } from './bounded-reads.ts';import { isTerminal, principalKey, requestPrincipal, recoveryFiles, type FileRecoveryRecord, type RecoveryRecord, type WriteRequest } from './model.ts';@@ -203,16 +204,6 @@ 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));}-/**- * The SQLSTATE of a transient failure that ended this write's own statement while the database stayed up (57014: a- * statement timeout or cancel), else null. It throws the preparation away and recurs while the write's work outlasts- * its bound, so it is charged like a cut-off preparation (`chargedInterruption`). Contention with other transactions- * (a lock timeout, a serialization failure, a deadlock) clears when they finish, and a lost connection or a database- * shutting down or out of connections is not the write's doing: neither is charged, so a restart never fails a write.- */-function writeInterruption(error: unknown): string | null {- return String((error as {code?:string})?.code) === '57014' ? '57014' : null;-}/*** Flip lane C: the shared-read failures (`sharedReadFailure`) already charged. A group's memoized read the database cancelled* ran once, for the whole group, and every member waiting on it gets the same failure: it is charged once, to the first@@ -220,43 +211,53 @@ function writeInterruption(error: unknown): string | null {* released uncounted. A read cancelled on every pass so still reaches the limit, one member at a time, never unbounded.*/const chargedSharedReads = new WeakSet<object>();-function writeInterruptedFailure(row: WriteRequest, sqlstate: string, attempts: number, limit: number): PublicationFailure {+/**+ * Large-pages hardening (b)/(c): the terminal failure once a write's transient interruptions (transient-retry.ts) pass+ * persistence.max_transient_retries: `attempts` interruptions, `limit` retries. The detail keeps the shipped+ * `origin`/`sqlstate`/`attempts`/`limit` fields and adds the cause and the key the limit came from.+ */+function writeInterruptedFailure(row: WriteRequest, interruption: TransientInterruption, attempts: number, limit: number): PublicationFailure {const fix = preparationKind(row) === 'sync'? `The file is held and the rest of the source syncs; reduce the load, then gbrain sources retry-held ${row.source_id} and the same gbrain sync with the same options.`: 'Submit the write again with a new request_id once the database is less loaded.';+ const what = interruption.cause === 'publication_ceiling'+ ? `Publication of this write ran past persistence.publication_ceiling_ms and was cancelled ${attempts} time(s)${interruption.sqlstate ? ` (SQLSTATE ${interruption.sqlstate})` : ''}`+ : `The database ended this write's statements ${attempts} time(s) (SQLSTATE ${interruption.sqlstate}, a statement timeout or cancel)`;return { code: 'write_interrupted',- message: `The database ended this write's statements ${attempts} time(s) (SQLSTATE ${sqlstate}, a statement timeout or cancel), the limit of persistence.max_preparation_attempts (${limit}); it is not prepared again. `+ message: `${what}; it was retried with backoff ${limit} time(s), the limit of ${TRANSIENT_RETRIES_KEY} (${limit}), and is not prepared again. `+ `Run gbrain sources writer status --source ${row.source_id} --json to see the load on the owner. ${fix}`,- detail: { origin: 'database_interruption', sqlstate, attempts, limit } as unknown as PublicationFailureDetail };+ detail: { origin: 'database_interruption', cause: interruption.cause, sqlstate: interruption.sqlstate, attempts, limit, limit_key: TRANSIENT_RETRIES_KEY } as unknown as PublicationFailureDetail };}+const TRANSIENT_RETRIES_KEY = PREPARATION_BUDGET_KEYS.transientRetries;/**- * Flip lane C: the limit an interruption (`writeInterruption`) is charged against, persistence.max_preparation_attempts.- * Null when the failure is not an interruption, the `preparation_deadlines` switch is off (nothing is counted, as- * before), or the database cannot be read (the claim is then released uncounted).+ * The transient interruption `error` reports (transient-retry.ts) and the retries it is charged against,+ * persistence.max_transient_retries. Null when the failure is not one, the `preparation_deadlines` switch is off+ * (nothing is counted and no backoff applies, as before), or the database cannot be read (released uncounted).*/-async function interruptionCharge(engine: BrainEngine, error: unknown): Promise<{ sqlstate: string; limit: number } | null> {- const sqlstate = writeInterruption(error);- if (!sqlstate) return null;+async function interruptionCharge(engine: BrainEngine, error: unknown): Promise<{ interruption: TransientInterruption; limit: number } | null> {+ const interruption = transientInterruption(error);+ if (!interruption) return null;if (isSharedReadFailure(error)) {if (chargedSharedReads.has(error as object)) return null;chargedSharedReads.add(error as object);}try {const { switches, preparation } = await readWriteSwitchSnapshot(engine);- return switches.preparation_deadlines ? { sqlstate, limit: preparation.maxAttempts } : null;+ return switches.preparation_deadlines ? { interruption, limit: preparation.transientRetries } : null;} catch { return null; }}/**- * Flip lane C: the recovery route's charge, returning the terminal `write_interrupted` failure once the count reaches the- * limit. It runs in its own statement before `markRecovering`: the request already holds its recovery record, which the- * expired-owner sweep never takes, so a crash in between leaves the one charge for the owner's recovery to finish.+ * Flip lane C: the recovery route's charge: `failure` is the terminal `write_interrupted` once the count passes the+ * limit, else null (the restored request goes back to the queue with the backoff the charge scheduled). It runs in its+ * own statement before `markRecovering`: the request already holds its recovery record, which the expired-owner sweep+ * never takes, so a crash in between leaves the one charge for the owner's recovery to finish. Null when not charged.*/-async function chargedInterruption(engine: BrainEngine, row: WriteRequest, error: unknown): Promise<PublicationFailure | null> {+async function chargedInterruption(engine: BrainEngine, row: WriteRequest, error: unknown): Promise<{ failure: PublicationFailure | null } | null> {const charge = await interruptionCharge(engine, error);if (!charge) return null;try {- const attempts = await chargePreparationAttempt(engine, row);- return attempts >= charge.limit ? writeInterruptedFailure(row, charge.sqlstate, attempts, charge.limit) : null;+ const attempts = await chargeTransientInterruption(engine, row);+ return { failure: attempts > charge.limit ? writeInterruptedFailure(row, charge.interruption, attempts, charge.limit) : null };} catch { return null; }}/**@@ -313,10 +314,11 @@ export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteReconst charge = await interruptionCharge(engine, error);if (charge) {// Flip lane C: charged in the transaction that releases or finishes the claim. A crash before it commits leaves the claim- // uncharged (the expired-owner sweep charges a preparing claim once), after it the charged outcome; never both.+ // uncharged (the expired-owner sweep charges a preparing claim once), after it the charged outcome; never both. The+ // release carries the backoff the charge scheduled (`next_attempt_at`), so no claim waits it out.const done = await engine.transaction(async tx => {- const attempts = await chargePreparationAttempt(tx, row);- if (attempts >= charge.limit) return completeWrite(tx, row, 'failed', {}, withAttempt(writeInterruptedFailure(row, charge.sqlstate, attempts, charge.limit), stage));+ const attempts = await chargeTransientInterruption(tx, row);+ if (attempts > charge.limit) return completeWrite(tx, row, 'failed', {}, withAttempt(writeInterruptedFailure(row, charge.interruption, attempts, charge.limit), stage));await releaseUnpublishedClaim(tx, row, 'database_contention');return null;}).then(outcome => ({ outcome }), () => null);@@ -595,10 +597,13 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prif (recovery) {// Even a rejected prepare can retain a journal record; do not leave that// record unaccounted or let a sibling publication bypass its recovery.- const interrupted = transactionBodyCompleted ? null : await chargedInterruption(engine, row, error);- if (!transactionBodyCompleted && writeInterruption(error)) await faultPoint('persistence:recovery_interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation });- const failure = interrupted || (!transactionBodyCompleted && !mayReprepare(row, requestError(error)) && !transientDatabaseFailure(error))- ? withAttempt(interrupted ?? requestError(error), published ? 'after_file_publication' : 'publication') : undefined;+ // A charged interruption under the limit is retried after its backoff whatever error it surfaced as (a publication the+ // ceiling cancelled can reject with a bare AbortError); past the limit it is the terminal failure.+ const charged = transactionBodyCompleted ? null : await chargedInterruption(engine, row, error);+ if (!transactionBodyCompleted && transientInterruption(error)) await faultPoint('persistence:recovery_interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation });+ const terminal = charged ? charged.failure+ : !transactionBodyCompleted && !mayReprepare(row, requestError(error)) && !transientDatabaseFailure(error) ? requestError(error) : null;+ const failure = terminal ? withAttempt(terminal, published ? 'after_file_publication' : 'publication') : undefined;try { await markRecovering(engine, row, failure ? 'publication_failed' : published ? 'commit_outcome_uncertain' : 'publication_not_started', failure); }catch { /* database outage: durable recovery record remains discoverable */ }if (lock) {diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.tsindex 6f20c47cfb..a927ebb807 100644--- a/src/core/persistence/diagnostics.ts+++ b/src/core/persistence/diagnostics.ts@@ -180,7 +180,8 @@ export async function readWriterDiagnostics(engine: BrainEngine) {// #6278: the budgets, ceiling, attempt limit and switch in effect, next to every running blocker's step age.const snapshot = await readWriteSwitchSnapshot(engine).catch(() => null);const preparation_policy = snapshot ? { deadlines: snapshot.switches.preparation_deadlines, sync_preparation_ms: snapshot.preparation.syncMs,- maintenance_preparation_ms: snapshot.preparation.maintenanceMs, preparation_ceiling_ms: snapshot.preparation.ceilingMs, max_preparation_attempts: snapshot.preparation.maxAttempts } : null;+ maintenance_preparation_ms: snapshot.preparation.maintenanceMs, preparation_ceiling_ms: snapshot.preparation.ceilingMs, max_preparation_attempts: snapshot.preparation.maxAttempts,+ max_transient_retries: snapshot.preparation.transientRetries } : null;const { persistenceConsumerStatus } = await import('./service.ts');// #6317 (C1): the heartbeat rows of this host, read once, so each running claim can name its owner's liveness and pool.const { existingLocalHostId } = await import('./identity.ts');diff --git a/src/core/persistence/head-blocker.ts b/src/core/persistence/head-blocker.tsindex 8dd8dea998..681d2af64a 100644--- a/src/core/persistence/head-blocker.ts+++ b/src/core/persistence/head-blocker.ts@@ -18,14 +18,15 @@ import { claimStateOf } from './claim-phase.ts';import { isTerminal, type RequestState } from './model.ts';import { sha256 } from './digest.ts';import { claimableWriteSql, EARLIER_HEAD, foregroundPrioritySql, SYNC_KIND } from './journal.ts';+import { BACKOFF_ELAPSED } from './transient-retry.ts';export type HeadBlockerPredicate = 'worktree_owner' | 'refresh_fence' | 'effect_recovery' | 'withdrawal_mirror' | 'request_recovery'- | 'zombie_publication' | 'lease' | 'root_hold';+ | 'zombie_publication' | 'lease' | 'root_hold' | 'transient_backoff';export interface HeadBlocker {predicate: HeadBlockerPredicate;- /** The refresh id for a fence, the request ids of blocking requests, the effect ids of blocking effects, or the worktree id. */+ /** The refresh id for a fence, the request ids of blocking requests (the head itself for `transient_backoff`), the effect ids of blocking effects, or the worktree id. */ids: string[];- /** The fence state, the blocking request's state, the worktree state (`other_host` when another host owns it), or why an effect recovery cannot finish. */+ /** The fence state, the blocking request's state, the worktree state (`other_host` when another host owns it), why an effect recovery cannot finish, or when a backoff ends (ISO time). */state: string | null;/** The process behind the blocker when one is known: a refresh process (`live` from its lock) or a claim's stamped owner. */owner: { kind: string | null; pid: number | null; live: boolean | null; restart_required: boolean } | null;@@ -42,7 +43,7 @@ interface RowRef { request_id: string; state: string; claim_phase: unknown; execpublication_started: boolean; recovery: boolean; principal_kind: string; principal_id: string }interface ProbeRow { id: string; worktree_id: string | null; owner_host_id: string | null; worktree_state: string | null; claimable: boolean;fence: { id: string; state: string } | null; effect_recovery: EffectRecoveryRef[] | null; mirrors: string[] | null; request_recovery: RequestRecoveryRef[] | null;- earlier: RowRef[] | null; ahead: RowRef[] | null }+ request_id: string; backoff_until: string | Date | null; earlier: RowRef[] | null; ahead: RowRef[] | null }interface EffectRecoveryRef { id: string; error_code: string | null; slug: string | null; path: string | null; before: string | null; after: string | null }interface RequestRecoveryRef { request_id: string; state: RequestState; blocked_reason: string | null; slug: string; version: string | null; path: string | null;before: string | null; after: string | null }@@ -84,7 +85,8 @@ export async function readHeadBlockers(engine: BrainEngine, ids: string[], hostIconst out = new Map<string, HeadBlockerRead>();if (!ids.length) return out;const priority = foregroundPrioritySql();- const rows = await engine.executeRaw<ProbeRow>(`SELECT r.id::text AS id, r.worktree_id::text AS worktree_id, w.owner_host_id::text AS owner_host_id, w.state AS worktree_state,+ const rows = await engine.executeRaw<ProbeRow>(`SELECT r.id::text AS id, r.request_id::text AS request_id, r.worktree_id::text AS worktree_id, w.owner_host_id::text AS owner_host_id, w.state AS worktree_state,+ CASE WHEN NOT ${BACKOFF_ELAPSED('r')} THEN r.next_attempt_at END AS backoff_until,(${claimableWriteSql(priority)}) AS claimable,(SELECT jsonb_build_object('id',f.id::text,'state',f.state) FROM persistence_worktree_refreshes fWHERE f.worktree_id=r.worktree_id AND f.state IN ('fenced','merged','recovery_required') LIMIT 1) AS fence,@@ -122,6 +124,8 @@ export async function readHeadBlockers(engine: BrainEngine, ids: string[], hostI}if (row.mirrors?.length) { blocked({ predicate: 'withdrawal_mirror', ids: row.mirrors, state: null, owner: null, intervention: false }); continue; }if (row.request_recovery?.length) { blocked(requestRecoveryBlocker(row.request_recovery)); continue; }+ // v261: the head itself waits out a transient interruption's backoff (transient-retry.ts); it is claimed again when it ends.+ if (row.backoff_until) { blocked({ predicate: 'transient_backoff', ids: [row.request_id], state: new Date(row.backoff_until).toISOString(), owner: null, intervention: false }); continue; }const ref = row.earlier?.[0] ?? row.ahead?.[0];if (!ref) { out.set(row.id, { status: 'unknown' }); continue; }const claim = claimStateOf({ state: ref.state, claim_phase: ref.claim_phase, execution_token: ref.execution_token, claim_lapsed: ref.claim_lapsed, publication_started: ref.publication_started });diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex d8725f66e1..c79da27103 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -31,6 +31,7 @@ import { schemaAdmissionRefusal } from './schema-admission.ts';import { CAPACITY_VERIFY } from './capacity-verify.ts';import { readManagedMode } from './managed-mode.ts';import { localHostId } from './identity.ts';+import { BACKOFF_ELAPSED } from './transient-retry.ts';import { segmentWriteScope } from '../page-body/ingest.ts';import {isTerminal, principalKey, requestPrincipal, recoveryFiles,@@ -450,9 +451,10 @@ export async function claimGroupFollowers(engine: BrainEngine, head: WriteReques// #5984 G6: only the group's candidate prefix is locked. Locking every next row also held a foreground write's row// (the first non-member) for the claim's round trips, so its recovery record and reads waited on the lane.const next = await tx.executeRaw<{ id: string; state: string; grp: string | null; recovering: boolean; claim_phase: unknown }>(`WITH next AS (- SELECT id,sequence,state,${GROUP_KEY_SQL} AS grp,recovery IS NOT NULL AS recovering FROM persistence_requests+ SELECT id,sequence,state,${GROUP_KEY_SQL} AS grp,recovery IS NOT NULL AS recovering,NOT ${BACKOFF_ELAPSED('persistence_requests')} AS backoff FROM persistence_requestsWHERE worktree_id=$1::uuid AND sequence>$2 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) ORDER BY sequence LIMIT $3),- bound AS (SELECT min(sequence) AS sequence FROM next WHERE grp IS DISTINCT FROM $4 OR state<>'queued' OR recovering)+ -- v261: a member still in its transient backoff ends the group's prefix like a non-member.+ bound AS (SELECT min(sequence) AS sequence FROM next WHERE grp IS DISTINCT FROM $4 OR state<>'queued' OR recovering OR backoff)SELECT r.id,r.state,${GROUP_KEY_SQL} AS grp,r.recovery IS NOT NULL AS recovering,r.claim_phaseFROM persistence_requests r WHERE r.id IN (SELECT id FROM next WHERE sequence<COALESCE((SELECT sequence FROM bound),9223372036854775807))ORDER BY r.sequence FOR UPDATE OF r`, [head.worktree_id, head.sequence, max, group]);@@ -617,6 +619,7 @@ export const claimableWriteSql = (priority: string, laneRoots = "'{}'::text[]")AND mirror.kind='withdrawal-mirror' AND mirror.state IN ('queued','running')AND (NOT (mirror.data ? 'targets') OR mirror.data->'targets' @> jsonb_build_array(jsonb_build_object('slug',r.slug))))AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)+ AND ${BACKOFF_ELAPSED('r')}AND NOT EXISTS (SELECT 1 FROM persistence_requests earlierWHERE r.worktree_id IS NOT NULL AND earlier.worktree_id=r.worktree_id AND ${EARLIER_HEAD('earlier', 'r', priority, laneRoots)})AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier@@ -746,7 +749,7 @@ export async function claimNextLaneHead(engine: BrainEngine, hostId: string, worawait declarePersistenceProtocol(tx);const [row] = await tx.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests rJOIN persistence_worktrees w ON w.id=r.worktree_id- WHERE r.worktree_id=$2::uuid AND r.state='queued' AND r.intent->>'lane'=$3 AND r.intent->>'group'=r.request_id::text+ WHERE r.worktree_id=$2::uuid AND r.state='queued' AND ${BACKOFF_ELAPSED('r')} AND r.intent->>'lane'=$3 AND r.intent->>'group'=r.request_id::textAND w.owner_host_id=$1::uuid AND w.state='active' AND ${refreshFenceClear('r')}AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)AND NOT EXISTS (SELECT 1 FROM persistence_effects mirror WHERE mirror.worktree_id=r.worktree_iddiff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 4639dfedef..8d7708e318 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -102,6 +102,10 @@ export interface WriteRequest {/** #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;+ /** Large-pages hardening (v261): transient interruptions counted against `persistence.max_transient_retries` (transient-retry.ts). */+ transient_interruptions?: number;+ /** v261: the earliest time a claim takes this queued row again (a transient interruption's backoff); null means now. */+ next_attempt_at?: Date | string | null;/** #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;diff --git a/src/core/persistence/preparation-budget.ts b/src/core/persistence/preparation-budget.tsindex 1028a15229..2c80ee5187 100644--- a/src/core/persistence/preparation-budget.ts+++ b/src/core/persistence/preparation-budget.ts@@ -15,6 +15,11 @@* ignores cancellation may keep its root blocked, measured from the claim;* - `persistence.max_preparation_attempts` (default 2, 1 to 10): the request is* finished `failed`/`preparation_stalled` once its counter reaches it.+ * - `persistence.max_transient_retries` (default 5, 0 to 20): how many transient+ * interruptions (a statement the database ended with 57014, a publication+ * cancelled at its ceiling) a request is retried after, with backoff, before it+ * ends `failed`/`write_interrupted` (transient-retry.ts). Its own budget: a+ * transient interruption never charges `max_preparation_attempts`.** `remember`, `put_page` and `edit_page` without an internal intent keep the* consumer's `preparationMs` (30 s). The deadlines sit behind the@@ -31,6 +36,7 @@ export const PREPARATION_BUDGET_KEYS = {maintenanceMs: 'persistence.maintenance_preparation_ms',ceilingMs: 'persistence.preparation_ceiling_ms',maxAttempts: 'persistence.max_preparation_attempts',+ transientRetries: 'persistence.max_transient_retries',} as const;export type PreparationBudgetKey = keyof typeof PREPARATION_BUDGET_KEYS;export const PREPARATION_BUDGET_CONFIG_KEYS: readonly string[] = Object.values(PREPARATION_BUDGET_KEYS);@@ -40,8 +46,9 @@ export interface PreparationPolicy {maintenanceMs: number;ceilingMs: number;maxAttempts: number;+ transientRetries: number;}-export const DEFAULT_PREPARATION_POLICY: Readonly<PreparationPolicy> = Object.freeze({ syncMs: 120_000, maintenanceMs: 120_000, ceilingMs: 600_000, maxAttempts: 2 });+export const DEFAULT_PREPARATION_POLICY: Readonly<PreparationPolicy> = Object.freeze({ syncMs: 120_000, maintenanceMs: 120_000, ceilingMs: 600_000, maxAttempts: 2, transientRetries: 5 });/** The ceiling must leave an abandoned preparation this much past the larger budget before the root is freed. */export const PREPARATION_CEILING_GRACE_MS = 30_000;const RANGES: Record<PreparationBudgetKey, { min: number; max: number; unit: string }> = {@@ -49,6 +56,7 @@ const RANGES: Record<PreparationBudgetKey, { min: number; max: number; unit: strmaintenanceMs: { min: 1_000, max: 3_600_000, unit: 'milliseconds' },ceilingMs: { min: 60_000, max: 3_600_000, unit: 'milliseconds' },maxAttempts: { min: 1, max: 10, unit: 'attempts' },+ transientRetries: { min: 0, max: 20, unit: 'retries' },};function parseWhole(raw: string | null | undefined): number | null {diff --git a/src/core/persistence/publication-deadline.ts b/src/core/persistence/publication-deadline.tsindex d7e77a101d..3316df94da 100644--- a/src/core/persistence/publication-deadline.ts+++ b/src/core/persistence/publication-deadline.ts@@ -39,8 +39,12 @@ const CEILING_TTL_MS = 5_000;let ceiling = { value: PUBLICATION_CEILING_DEFAULT_MS, at: 0 };const signals = new AsyncLocalStorage<AbortSignal>();+/** Test seam (`_setPublicationTimingForTest`): a ceiling and grace below the accepted range, so a test can overrun the ceiling. */+let testTiming: { ceilingMs: number; graceMs: number } | undefined;+/** The ceiling (cached for 5 s); anything missing or outside 60000..3600000 reads as the default. */export async function readPublicationCeilingMs(engine: Pick<BrainEngine, 'getConfig'>): Promise<number> {+ if (testTiming) return testTiming.ceilingMs;if (Date.now() - ceiling.at < CEILING_TTL_MS) return ceiling.value;const n = Number((await engine.getConfig(PUBLICATION_CEILING_KEY).catch(() => null))?.trim());ceiling = { value: Number.isInteger(n) && n >= 60_000 && n <= 3_600_000 ? n : PUBLICATION_CEILING_DEFAULT_MS, at: Date.now() };@@ -49,6 +53,17 @@ export async function readPublicationCeilingMs(engine: Pick<BrainEngine, 'getCon/** Test seam: the next readPublicationCeilingMs reads the config again. */export function _resetPublicationCeilingForTest(): void { ceiling = { ...ceiling, at: 0 }; }+/** Test seam: every publication's ceiling and grace (undefined restores the configured ceiling and `PUBLICATION_GRACE_MS`). */+export function _setPublicationTimingForTest(timing: { ceilingMs: number; graceMs: number } | undefined): void { testTiming = timing; }++/**+ * Large-pages hardening (c): whether the current publication (the `boundPublication` this async context runs in) was+ * cancelled at the ceiling. transient-retry.ts counts such a publication's failure against `persistence.max_transient_retries`.+ */+export function publicationDeadlinePassed(): boolean {+ const signal = signals.getStore();+ return !!signal?.aborted && (signal.reason as { code?: unknown } | null)?.code === 'publication_deadline';+}/** The idle-in-transaction bound a publish transaction gets: the ceiling, never above the pool's own session value. */export function publicationIdleTimeoutMs(ceilingMs = ceiling.value): number {@@ -121,7 +136,7 @@ export function boundPublication<T>(publish: () => Promise<T>, bound: Publicatioconst schedule = bound.later ?? realTimer;const cancels: Array<() => void> = [];const later = (ms: number, fn: () => void) => { cancels.push(schedule(ms, fn)); };- const grace = bound.graceMs ?? PUBLICATION_GRACE_MS, settle = bound.settleMs ?? PUBLICATION_SETTLE_MS;+ const grace = bound.graceMs ?? testTiming?.graceMs ?? PUBLICATION_GRACE_MS, settle = bound.settleMs ?? PUBLICATION_SETTLE_MS;later(bound.ceilingMs, () => bound.onOverdue?.());later(bound.ceilingMs + grace, () => controller.abort(Object.assign(new Error('publication_deadline'), { code: 'publication_deadline' })));later(bound.ceilingMs + grace + settle, () => bound.onStuck?.(settled));diff --git a/src/core/persistence/transient-retry.ts b/src/core/persistence/transient-retry.tsnew file mode 100644index 0000000000..4a9e151133--- /dev/null+++ b/src/core/persistence/transient-retry.ts@@ -0,0 +1,65 @@+/**+ * Large-pages hardening (b)/(c): the retry budget for a managed write's transient interruptions.+ *+ * A transient interruption ends a claim's work for a reason that is load or latency, not the write's content:+ *+ * - `statement_cancel`: the database ended one of the write's own statements with SQLSTATE 57014 (a statement timeout+ * or cancel) while it stayed up, at preparation or inside the publication transaction;+ * - `publication_ceiling`: the publication ran past `persistence.publication_ceiling_ms` and its grace, and the owner+ * cancelled it (publication-deadline.ts `boundPublication`), whatever error the cancelled publish then rejects with.+ *+ * Each one is counted in `transient_interruptions` (v261), never in `preparation_attempts` (the content-class budget+ * that preparations cut off at their deadline keep), and schedules the request's next claim at `next_attempt_at` with+ * a bounded exponential backoff: 1 s, 2 s, 4 s, 8 s, then 15 s. A claim never takes a queued row before it+ * (`BACKOFF_ELAPSED`), so the delay holds no claim, no root lock and no connection. The request is retried after up to+ * `persistence.max_transient_retries` interruptions (default 5); the next one ends it `failed`/`write_interrupted`.+ * The cap keeps every loop bounded: at most `max_transient_retries + 1` claims end this way.+ *+ * Contention with other transactions (a lock timeout, a serialization failure, a deadlock) and a lost connection or a+ * restarting database are not interruptions of the write's own work and are never counted (coordinator.ts+ * `transientDatabaseFailure` releases them as before). With `persistence.preparation_deadlines false` nothing is+ * counted and no backoff applies: the switch restores the uncounted release, as it does for the deadlines.+ */+import { OperationError } from '../ops/contract.ts';+import type { SqlEngine, WriteRequest } from './model.ts';+import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';+import { publicationDeadlinePassed } from './publication-deadline.ts';++export const TRANSIENT_BACKOFF_BASE_MS = 1_000;+/** The backoff's ceiling: under the managed sync drain's 30 s no-progress window (sync-drain.ts), so a backoff never reads as a stall. */+export const TRANSIENT_BACKOFF_MAX_MS = 15_000;++/** The delay before the claim after the `interruptions`-th transient interruption (1-based). */+export function transientBackoffMs(interruptions: number): number {+ return Math.min(TRANSIENT_BACKOFF_MAX_MS, TRANSIENT_BACKOFF_BASE_MS * 2 ** Math.min(30, Math.max(0, interruptions - 1)));+}++/** Whether a queued row's backoff has elapsed; every claim statement requires it. */+export const BACKOFF_ELAPSED = (alias: string) => `(${alias}.next_attempt_at IS NULL OR ${alias}.next_attempt_at<=now())`;++export type TransientCause = 'statement_cancel' | 'publication_ceiling';+export interface TransientInterruption { cause: TransientCause; sqlstate: string | null }++/**+ * The transient interruption `error` reports, else null. A publication the ceiling cancelled is read from the current+ * publication's signal (it is the cancellation, not the error it surfaces as: a discarded connection, an AbortError or a+ * 57014); a typed refusal (`OperationError`) that settles such a publication is the write's own outcome and is not one.+ */+export function transientInterruption(error: unknown): TransientInterruption | null {+ const code = (error as { code?: unknown } | null)?.code;+ const sqlstate = typeof code === 'string' && /^[0-9A-Z]{5}$/.test(code) ? code : null;+ if (publicationDeadlinePassed() && !(error instanceof OperationError)) return { cause: 'publication_ceiling', sqlstate };+ return code === '57014' ? { cause: 'statement_cancel', sqlstate: '57014' } : null;+}++/**+ * Counts one transient interruption on a claim this owner still holds and schedules its next claim. Token-fenced; run it+ * in the transaction that releases or finishes the claim, so a crash never counts an interruption twice. Returns the count.+ */+export async function chargeTransientInterruption(engine: SqlEngine, row: WriteRequest): Promise<number> {+ const [charged] = await engine.executeRaw<{ transient_interruptions: number }>(`UPDATE persistence_requests SET transient_interruptions=transient_interruptions+1,+ next_attempt_at=now()+(LEAST($3::double precision*power(2::double precision,LEAST(transient_interruptions,30)),$4::double precision)*interval '1 millisecond'),+ updated_at=now() WHERE id=$1::uuid AND execution_token=$2::uuid AND state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING transient_interruptions`,+ [row.id, row.execution_token, TRANSIENT_BACKOFF_BASE_MS, TRANSIENT_BACKOFF_MAX_MS]);+ return charged?.transient_interruptions ?? (row.transient_interruptions ?? 0) + 1;+}diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 52cfaf76dd..e10967188f 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 260;+export const LATEST_SCHEMA_VERSION = 261;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex c5a418daa8..6ab015000d 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -261,6 +261,7 @@ import { v257 } from './v257-pages-live-origin-key.ts';import { v258 } from './v258-pages-links-extract-failure.ts';import { v259 } from './v259-ingest-log-marked-index.ts';import { v260 } from './v260-segmented-page-size-index.ts';+import { v261 } from './v261-persistence-request-transient-retries.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -520,4 +521,5 @@ export const MIGRATIONS: Migration[] = [v258,v259,v260,+ v261,];diff --git a/src/core/schema-migrations/v261-persistence-request-transient-retries.ts b/src/core/schema-migrations/v261-persistence-request-transient-retries.tsnew file mode 100644index 0000000000..3fd7fb47f0--- /dev/null+++ b/src/core/schema-migrations/v261-persistence-request-transient-retries.ts@@ -0,0 +1,24 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Large-pages hardening (b)/(c): a managed write's transient interruptions (a+// statement the database ended with SQLSTATE 57014, or a publication cancelled at+// `persistence.publication_ceiling_ms`) get their own budget+// (`persistence.max_transient_retries`, persistence/transient-retry.ts) instead of+// `preparation_attempts`. `transient_interruptions` counts them; each one schedules+// the request's next claim at `next_attempt_at` (bounded exponential backoff), and+// a claim skips a queued row until then. Column-only, no backfill: existing rows+// start at 0 and NULL (claimable now). Like v217 and v220 the columns are+// migration-created (the `persistence_requests` CREATE TABLE of src/schema.sql+// carries only the original columns) and no index references them.+export const v261: Migration = {+ version: 261,+ name: 'persistence_request_transient_retries',+ idempotent: true,+ sql: `+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS transient_interruptions integer NOT NULL DEFAULT 0 CHECK (transient_interruptions >= 0);+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS next_attempt_at timestamptz;+ `,+};diff --git a/test/persistence-preparation-budget.test.ts b/test/persistence-preparation-budget.test.tsindex 908adbf884..410739361a 100644--- a/test/persistence-preparation-budget.test.ts+++ b/test/persistence-preparation-budget.test.ts@@ -36,14 +36,14 @@ describe('budget table', () => {});describe('config key family', () => {- test('defaults: 120 s budgets, 600 s ceiling, 2 attempts', () => {- expect(resolvePreparationPolicy(new Map())).toEqual({ syncMs: 120_000, maintenanceMs: 120_000, ceilingMs: 600_000, maxAttempts: 2 });+ test('defaults: 120 s budgets, 600 s ceiling, 2 attempts, 5 transient retries', () => {+ expect(resolvePreparationPolicy(new Map())).toEqual({ syncMs: 120_000, maintenanceMs: 120_000, ceilingMs: 600_000, maxAttempts: 2, transientRetries: 5 });});test('configured values are read; invalid ones keep their default; the ceiling floors at the larger budget plus 30 s', () => {const policy = resolvePreparationPolicy(new Map([[PREPARATION_BUDGET_KEYS.syncMs, '300000'], [PREPARATION_BUDGET_KEYS.maintenanceMs, 'abc'],[PREPARATION_BUDGET_KEYS.ceilingMs, '60000'], [PREPARATION_BUDGET_KEYS.maxAttempts, '3']]));- expect(policy).toEqual({ syncMs: 300_000, maintenanceMs: 120_000, ceilingMs: 330_000, maxAttempts: 3 });+ expect(policy).toEqual({ syncMs: 300_000, maintenanceMs: 120_000, ceilingMs: 330_000, maxAttempts: 3, transientRetries: 5 });expect(resolvePreparationPolicy(new Map([[PREPARATION_BUDGET_KEYS.maxAttempts, '11']])).maxAttempts).toBe(2);});test('config set refuses out-of-range values with the range and example, and ignores other keys', () => {diff --git a/test/persistence-writer-status-stall.test.ts b/test/persistence-writer-status-stall.test.tsindex cd64953199..3ec633afa7 100644--- a/test/persistence-writer-status-stall.test.ts+++ b/test/persistence-writer-status-stall.test.ts@@ -72,7 +72,7 @@ test('a preparing blocker names its step, wait cause, owner and budget, and turnawait waitFor(async () => (await engine.executeRaw<{ step: string | null }>("SELECT claim_phase->>'step' AS step FROM persistence_requests WHERE id=$1::uuid", [row.id]))[0]?.step === 'adoption_read_facts',{ timeoutMs: 15_000, label: 'the renewal records the step' });const status = await readWriterDiagnostics(engine);- expect(status.preparation_policy).toEqual({ deadlines: true, sync_preparation_ms: 120_000, maintenance_preparation_ms: 90_000, preparation_ceiling_ms: 600_000, max_preparation_attempts: 2 });+ expect(status.preparation_policy).toEqual({ deadlines: true, sync_preparation_ms: 120_000, maintenance_preparation_ms: 90_000, preparation_ceiling_ms: 600_000, max_preparation_attempts: 2, max_transient_retries: 5 });const blocker = status.blockers.find(b => b.request_id === row.request_id)!;expect(blocker).toMatchObject({ operation: 'put_page', intent_kind: 'managed_maintenance_page', preparation_attempts: 0, state: 'running' });expect(blocker.claim).toMatchObject({ phase: 'preparing', step: 'adoption_read_facts', waiting_on: 'db', owner: { kind: 'sync', pid: 4242, version: '0.60.200.0' }, budget_ms: 90_000, stall: null });