Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): bound a publish that never settles (#6288 part 1, #6352)
time-attack75e537162e16
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 828cf877ce..90f33c478f 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -48,3 +48,4 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor- `src/core/persistence/consumer-diagnostics.ts` — #6317 (B3, I1): `hostConsumersReport` (the `host.consumers` block of `writer status --json`), `consumerOverlap` (two resident-kind full rows alive over 30 s), `ownersWithoutHeartbeat` (claim owners on running claims with no row) and `hostIdentityMismatches` (this process's `host.json` id differs from a binding owner's while the owner's checkout resolves on this filesystem or the machine id matches), read-only and shared by doctor and writer status.- `src/core/postgres-engine/pool-stats.ts` — #6317 (C1, G1): `driverPoolStats(sql)` reads the vendored postgres.js driver's `sql.pool` getter (`vendor/postgres`, patch regenerated) for real `{checked_out, max, waiters}`; `enginePoolStats(engine)` labels the source (`driver` or `tracked_subset` from `pool-gauge.ts`). Filled into the heartbeat row, `writer status` running claims and `getPoolDiagnostics()`.- `src/core/persistence/sync-drain.ts` (#6405, #6423 in-pass governor) + `src/core/persistence/drain-step.ts` — `runDrain` races every pass against a governor that runs with or without `announce`: the pass gets its own `AbortController`, the governor's head read is bounded (`GOVERN_PROBE_MS`, or the window when shorter), and on a stop the pass signal is aborted (the pass's `assertActive` / `stampDrainStep` boundaries throw, so it admits and writes nothing more) and its late result or rejection is dropped. A head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; `PUBLICATION_CEILING_DEFAULT_MS`) stops `blocked` / `drain_stalled` / `publication_overdue` with `stall.in_pass` and a `next` that says restart (never a promised reclaim); a pass with no commit, no unfinished request and nothing changing for `IN_PASS_NO_PROGRESS_MS` (5 min) stops `no_admission`, an unchanged non-empty head `no_progress` / `owner_missing`; a live preparation is left to its own budget and ceiling. `drain-step.ts` holds the process-local step (`freeze`, `waiver_run`, `admission`, `await_receipt`, stamped in `sync-run.ts`) and the last statement label (`noteDrainSql`, from `waiveNoopRun`). `enterClaimPhase(clock, 'publishing')` stamps `waiting_on: 'publication'`. `drainManagedSync` prints one line when the sync's own pool is a transaction-mode pooler. `sync-waivers.ts` `waiveNoopRun` pipelines at most `WAIVER_PIPELINE_MAX` (64) calls per round trip and sends the next chunk only while the prefix holds. `commands/sync-delegate.ts`: a serve-delegated `no_admission` stop continues once with the CLI's own consumer (`serve_no_admission`); a `publication_overdue` stop is reported as it is. Tests: `test/sync-drain-inpass-stall.test.ts`, `test/sync-drain-no-admission.test.ts`, `test/sync-waivers-chunk.test.ts`.+- `src/core/persistence/publication-deadline.ts` (#6288 part 1, #6352; UC2) — what bounds a publish that neither resolves nor rejects. On Postgres the publish transaction is the real bound: `declareDurablePersistence` already sets a transaction-local `statement_timeout` (5 s) and `lock_timeout`, and `bindPublicationTimeouts` (first statement of `publishMutation`'s and `publishGroup`'s transactions, pipelined, no extra round trip) adds a transaction-local `idle_in_transaction_session_timeout` of `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; never above the pool's own `GBRAIN_IDLE_TX_TIMEOUT`), so a publisher stuck between statements is ended by the server and commits nothing; both survive a transaction pooler that drops startup parameters. Never set on PGLite: it would enforce the bound, and a transaction it ends wedges the engine's only connection. `boundPublication` (the consumer's single path and `executeClaimedGroup`'s group publish and per-member fallback) settles only with the publish's own outcome, so nothing releases or reports a request or group while its transaction can still commit; at the ceiling the claim stamp reads `waiting_on: publication_deadline`, after `PUBLICATION_GRACE_MS` (30 s) it aborts the publication's signal (passed to `engine.transaction(fn, { signal })` through `publicationTransaction`; an engine without the option ignores it), and after `PUBLICATION_SETTLE_MS` (5 s) more the consumer lists it in `stuck_publications` and reports `restart_required` (its root stays held: restarting the owner is the recovery, never a promised reclaim). The lease keeps renewing, so a reclaim never races a publisher that may still write files. The wave 9 yield between groups is outside any one bound. Tests: `test/persistence-publication-deadline.test.ts` (barriers after the token lock, after the file rename and before commit; the server-side idle end on Postgres; the wiring probe).diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 8907777fe4..c103e926ee 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -462,7 +462,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run| Stop reason | Code | Outcome | What it means | Recovery || --- | --- | --- | --- | --- || <a id="drain-stopped-at-its-deadline"></a>`deadline` | `writer_pending` | `resumable` | `--timeout`, `--hard-deadline`, Ctrl-C or the run deadline stopped the drain. Accepted page writes keep their request IDs and the cursor is intact. | Rerun `next.command` (the same options). It resumes where the last run stopped. |-| <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout made no progress for the whole stall window: no committed receipt and no step advance. A lease renewal is not a change: the detector keys on the head claim's phase and step. With a live owner on **this host**, the drain does not stop at the allowance (the preparation budget plus 30 s): from there it prints `stalled <N>s on <step>` with the owner's pid and kind every 10 s and keeps going, because the owner's own budget frees the root by `persistence.preparation_ceiling_ms` (600 s) and the next pass holds the entry. It stops `drain_stalled` only when the ceiling passes without the root being released, or when the owner's `persistence_consumers` row reads wedged (`restart_required`, or a root barrier older than the ceiling); the stop then carries `cause: owner_wedged_here`, the owner `{kind, pid, nonce}`, `retry_after_ms` (the time left to the ceiling, 0 once past), `next.safe_to_loop: true` while the ceiling is ahead and `next.fix.next` `wait` before it, `tell_user_to_run` (restart the named pid) after it. A lapsed claim (`owner_missing`) stops at once, unless this host owns the checkout and a live full consumer exists, which gets exactly one more window. Other causes: `preparation_overdue` / `publication_overdue` (a live owner elsewhere past its allowance) and `no_progress` (an unstamped head). A pass that never returns is stopped from inside (`drain.stall.in_pass: true`, the same rules whether or not the drain prints progress): a head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300 s) stops `publication_overdue`, and its `next` says to restart the process that owns the publication, because an unfinished publish can hold its locks until it settles and nothing reclaims it for you; a pass that admitted nothing and left no unfinished request for 5 minutes stops `no_admission` with the step it was in (`freeze`, `waiver_run`, `admission`, `await_receipt`) and the last statement label, which is what a transaction-mode pooler that never answers a round trip looks like. A serve-delegated `no_admission` continues once with the CLI's own consumer. `drain.stall` carries `phase`, `step`, `waiting_on`, `cause`, the owner and whether this host owns the checkout. | `gbrain sources writer status --source <source> --json`: its `next_action` says whether to wait (`retry_after_ms`) or which pid to restart. Before the ceiling, rerun `next.command` after `retry_after_ms` (safe in a loop). Past it, or with a wedged owner, restart the named owner process (`gbrain serve`, the jobs worker or autopilot) on the brain host, then rerun `next.command`; the held entry needs `gbrain sources retry-held <source>` afterwards. When this host is not the owner, make sure the owner's `gbrain serve` is running. |+| <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout made no progress for the whole stall window: no committed receipt and no step advance. A lease renewal is not a change: the detector keys on the head claim's phase and step. With a live owner on **this host**, the drain does not stop at the allowance (the preparation budget plus 30 s): from there it prints `stalled <N>s on <step>` with the owner's pid and kind every 10 s and keeps going, because the owner's own budget frees the root by `persistence.preparation_ceiling_ms` (600 s) and the next pass holds the entry. It stops `drain_stalled` only when the ceiling passes without the root being released, or when the owner's `persistence_consumers` row reads wedged (`restart_required`, or a root barrier older than the ceiling); the stop then carries `cause: owner_wedged_here`, the owner `{kind, pid, nonce}`, `retry_after_ms` (the time left to the ceiling, 0 once past), `next.safe_to_loop: true` while the ceiling is ahead and `next.fix.next` `wait` before it, `tell_user_to_run` (restart the named pid) after it. A lapsed claim (`owner_missing`) stops at once, unless this host owns the checkout and a live full consumer exists, which gets exactly one more window. Other causes: `preparation_overdue` / `publication_overdue` (a live owner elsewhere past its allowance) and `no_progress` (an unstamped head). A pass that never returns is stopped from inside (`drain.stall.in_pass: true`, the same rules whether or not the drain prints progress): a head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300 s) stops `publication_overdue`, and its `next` says to restart the process that owns the publication, because an unfinished publish can hold its locks until it settles and nothing reclaims it for you; a pass that admitted nothing and left no unfinished request for 5 minutes stops `no_admission` with the step it was in (`freeze`, `waiver_run`, `admission`, `await_receipt`) and the last statement label, which is what a transaction-mode pooler that never answers a round trip looks like. A serve-delegated `no_admission` continues once with the CLI's own consumer. The owner process bounds its own publish the same way: past the ceiling the claim reads `waiting_on: publication_deadline`, a Postgres publish transaction idle past it is ended by the server (nothing commits), and a publish that still has not settled 35 s later makes the owner report `restart_required` (its heartbeat row carries `restart_required`, which the drain reads as `owner_wedged_here`; the consumer status lists it under `stuck_publications`); restart that process. `drain.stall` carries `phase`, `step`, `waiting_on`, `cause`, the owner and whether this host owns the checkout. | `gbrain sources writer status --source <source> --json`: its `next_action` says whether to wait (`retry_after_ms`) or which pid to restart. Before the ceiling, rerun `next.command` after `retry_after_ms` (safe in a loop). Past it, or with a wedged owner, restart the named owner process (`gbrain serve`, the jobs worker or autopilot) on the brain host, then rerun `next.command`; the held entry needs `gbrain sources retry-held <source>` afterwards. When this host is not the owner, make sure the owner's `gbrain serve` is running. || <a id="drain-database-contention"></a>`database_contention` | `database_contention` | `blocked` (or an error) | Three consecutive passes hit database contention, a statement timeout or a dropped connection, or reading the awaited write's state failed (an authentication or permission failure stops at once). The drain retries transient failures with backoff before giving up. Accepted writes keep their request IDs. | Fix database access (`gbrain engine status --probe`), then rerun `next.command`. || <a id="drain-writer-blocked"></a>`recovery_required`, `owner_unavailable`, `unexpected_file_bytes`, `unexpected_staging_bytes` | `recovery_required` | `blocked` | The checkout's writer needs intervention before more pages can publish: interrupted publication recovery, no live owner, or unexpected bytes in the file or staging area. | `gbrain sources writer status <source>` and the fix it prints. Unexpected bytes are the user's edits; ask before discarding them. Then rerun `next.command`. || <a id="drain-blocked-by-a-failed-page"></a>`blocked_by_failures` | `blocked_by_failures` | `blocked` | A page write failed terminally. `managed_write` and `failures` name the page and cause. Rerunning without a fix returns the same failure. | Fix the cause, then run `next.command` (it adds `--retry-failed`). Ask the user before skipping content. |diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.tsindex 0f6c1bca33..bccbb7c59e 100644--- a/src/core/persistence/claim-phase.ts+++ b/src/core/persistence/claim-phase.ts@@ -43,8 +43,8 @@ import { VERSION } from '../../version.ts';import { consumerIdentity, sameProcess } from './consumer-heartbeat.ts';export type ClaimPhaseName = 'preparing' | 'publishing';-/** #6405: `publication` is the publish phase's own wait (a stamp in `publishing` no longer reads `unknown`). */-export const WAITING_ON = ['git', 'fs', 'db', 'pool', 'publication', 'unknown'] as const;+/** #6405: `publication` is the publish phase's own wait (a stamp in `publishing` no longer reads `unknown`); #6288 `publication_deadline` is a publish past `persistence.publication_ceiling_ms`. */+export const WAITING_ON = ['git', 'fs', 'db', 'pool', 'publication', 'publication_deadline', 'unknown'] as const;export type WaitingOn = typeof WAITING_ON[number];export interface ClaimPhaseClock {phase: ClaimPhaseName;diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 72b4307071..05f0cd5abc 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -32,6 +32,7 @@ import { consumerConnectionRoute, consumerStatementEngine, poolerExposureLine }import { isConnectionLoss } from '../retry-matcher.ts';import { INSPECT_OWNER_RETRY_MS } from './health.ts';import { lockOpenOsError } from './native-lock.ts';+import { boundPublication, readPublicationCeilingMs, type PublicationBound } from './publication-deadline.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. */@@ -154,6 +155,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {private abandoned = new Map<Promise<void>, number>();/** #6278: abandoned preparations past the ceiling, by request row id. */private zombies = new Map<string, AbandonedPreparation>();+ /** #6288 (P2.3): publications past the ceiling, its grace and the settle window; any one makes this owner report restart_required. */+ private stuckPublications = new Map<string, { request_id: string; stuck_at: string }>();private policy: EffectivePreparationPolicy = { ...DEFAULT_PREPARATION_POLICY, deadlines: true };private activeRoots = new Set<string>();/** #5984 Phase 4.5: active roots whose only task is a foreground write publishing beside this process's lane groups. */@@ -622,7 +625,20 @@ export class PersistenceConsumer implements PersistenceConsumerLike {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); }+ restartRequired(): boolean { return this.zombies.size >= (this.opts.zombieCap ?? DEFAULT_ZOMBIE_CAP) || this.stuckPublications.size > 0; }+ /** #6288 (P2.3): the consumer's side of `boundPublication`: the claim stamp at the ceiling, restart_required past it. */+ private publicationBound(row: WriteRequest, ceilingMs: number, clock?: ClaimPhaseClock): PublicationBound {+ return { ceilingMs,+ onOverdue: () => {+ if (clock) clock.waitingOn = 'publication_deadline';+ this.log('publication', 'publication_deadline', `request ${row.request_id}: publishing past the ${ceilingMs} ms ceiling; its transaction's server-side timeouts end it on Postgres`);+ },+ onStuck: settled => {+ this.stuckPublications.set(row.id, { request_id: row.request_id, stuck_at: new Date().toISOString() });+ void settled.then(() => { this.stuckPublications.delete(row.id); });+ this.log('publication', 'restart_required', `request ${row.request_id}: the publication has not settled past the ceiling and its grace; restart this process (its root stays held until then)`);+ } };+ }status() {const { deadlines, syncMs, maintenanceMs, ceilingMs, maxAttempts } = this.policy;return { accepting: !this.stopping, active_preparations: this.active.size, active_worktrees: this.activeRoots.size,@@ -635,6 +651,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {abandoned_preparations: this.abandoned.size,outlived_ceiling: [...this.zombies.values()].map(value => ({ ...value })),restart_required: this.restartRequired(),+ stuck_publications: [...this.stuckPublications.values()].map(value => ({ ...value })),// #6317: which connection this consumer's statements take, and whether the ordinary pool is a transaction-mode pooler.connection: consumerConnectionRoute(this.engine),...(this.lastError ? { last_error: { ...this.lastError } } : {}) };@@ -848,7 +865,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {preparationActive = false;enterClaimPhase(clock, 'publishing');await faultPoint('consumer:prepared', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });- const { done, settled } = await this.publishSingle(row, prepared);+ const { done, settled } = await boundPublication(() => this.publishSingle(row, prepared), this.publicationBound(row, await readPublicationCeilingMs(this.engine), clock));if (done.state === 'failed') this.log('publication', done.error_code ?? 'storage_error', failureLogText(done));if (done.state === 'queued' && done.blocked_reason === 'writer_lock_unavailable') {root.retryAfterMs = INSPECT_OWNER_RETRY_MS;@@ -904,6 +921,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {return await executeClaimedGroup(this.engine, rows, { hostId: this.hostId, lane,prepare: (member, engine, signal, clock) => this.prepare(engine, member, this.config, signal, clock),lease: this.leaseTiming(), policy: this.policy, foregroundMs: this.opts.preparationMs ?? 30_000,+ publication: this.publicationBound(row, await readPublicationCeilingMs(this.engine)),leftRunning: (work, blocksRoot, abandoned) => {if (!blocksRoot) { this.keepUntilSettled(work); return; }// #6278: an abandoned member blocks its root until it settles or the ceiling passes; several abandoned members all hold it.diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 0819a04fcb..7697a479a2 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -31,6 +31,7 @@ import { authorizePageVisibility } from './page-visibility.ts';import { withNoRepoWriteThroughWarning } from '../write-through.ts';import { assertUnboundPublication, classifyUnboundPage, unboundWriteWarning } from './unbound-source.ts';import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFile, upgradeRecoveryStaging } from './staging.ts';+import { bindPublicationTimeouts, publicationTransaction } from './publication-deadline.ts';import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePersistence, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';@@ -343,7 +344,8 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prrecovery = record;await hooks.boundary?.('prepared', row);}- const done = await engine.transaction(async tx => {+ const done = await publicationTransaction(engine, async tx => {+ bindPublicationTimeouts(tx);await declareDurablePersistence(tx);const liveBinding = await guardOwnership(tx, row, hostId);if (prepared.sourceExclusive && !prepared.exclusiveSources?.length) await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [row.source_id]);diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex a5d1477ad6..1b0c104af5 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -51,6 +51,7 @@ import { tryAcquirePublicationCapacity } from './pool-capacity.ts';import { queuePublicationEffects, queuesMentionLinks, reconcileFinishedBatch } from './effect-journal.ts';import { assertUnboundPublication, classifyUnboundPage } from './unbound-source.ts';import { declareDurablePersistence } from './protocol.ts';+import { bindPublicationTimeouts, boundPublication, publicationTransaction, type PublicationBound } from './publication-deadline.ts';import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { authorizePageVisibility } from './page-visibility.ts';import { withFilesystemPublication } from './filesystem-guard.ts';@@ -203,7 +204,7 @@ export type TransactionRunner = <T>(fn: (tx: BrainEngine) => Promise<T>) => Promconst publishingBeside = new Set<string>();export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prepared: PreparedMutation[], hostId = localHostId(),- hooks: GroupHooks = {}, lane: LaneState | null = null, transaction: TransactionRunner = fn => engine.transaction(fn)): Promise<{ done: WriteRequest[] | null; requeued: string[]; reason?: GroupFailure }> {+ hooks: GroupHooks = {}, lane: LaneState | null = null, transaction: TransactionRunner = fn => publicationTransaction(engine, fn)): Promise<{ done: WriteRequest[] | null; requeued: string[]; reason?: GroupFailure }> {const head = rows[0];const none: { done: null; requeued: string[]; reason?: GroupFailure } = { done: null, requeued: [] };if (!head?.worktree_id || rows.some((row, i) => row.worktree_id !== head.worktree_id || row.source_id !== head.source_id || !groupable(row, prepared[i]!)@@ -261,6 +262,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr}if (lane) await awaitLaneBegin(lane, rows);const done = await transaction(async opened => {+ bindPublicationTimeouts(opened);timed.apply?.end(rows.length);if (lane) timed.apply = laneApplyBegin(lane);const tx = groupReads(opened);@@ -517,6 +519,8 @@ export interface GroupExecution {* or (#6278) a deadline; `abandoned` names the member and its clock for the ceiling.*/leftRunning?(work: Promise<unknown>, blocksRoot: boolean, abandoned?: { row: WriteRequest; clock: ClaimPhaseClock }): void;+ /** #6288 (P2.3): the publication ceiling and what the owner does at it and past it (publication-deadline.ts); absent, unbounded. */+ publication?: PublicationBound;}/**@@ -645,6 +649,10 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques}for (const clock of clocks) if (clock) enterClaimPhase(clock, 'publishing');enterClaimPhase(groupClock, 'publishing');+ const bounded = <T>(publish: () => Promise<T>): Promise<T> => run.publication ? boundPublication(publish, { ...run.publication, onOverdue: () => {+ for (const clock of [...clocks, groupClock]) if (clock) clock.waitingOn = 'publication_deadline';+ run.publication!.onOverdue?.();+ } }) : publish();const live = rows.map((row, i) => ({ row, i })).filter(({ row }) => !released.has(row.id));if (!live.length) return progressed;const liveRows = live.map(({ row }) => row);@@ -652,7 +660,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequesif (live.every(({ i }) => 'ok' in prepared[i]!)) {// #6278 lanes: a prefix publishes under the original group's order key, then drops its own begun mark.if (run.lane && liveRows.length < rows.length) await awaitLaneBegin(run.lane, rows);- const result = await publishGroup(engine, liveRows, live.map(({ i }) => (prepared[i] as { ok: PreparedMutation }).ok), run.hostId, run.hooks, run.lane ?? null);+ const result = await bounded(() => publishGroup(engine, liveRows, live.map(({ i }) => (prepared[i] as { ok: PreparedMutation }).ok), run.hostId, run.hooks, run.lane ?? null));if (run.lane && liveRows.length < rows.length) run.lane.begun.delete(liveRows.at(-1)!.request_id);if (result.done) { for (const row of result.done) run.settled(row); return true; }requeued = new Set(result.requeued);@@ -684,7 +692,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequesconst p = prepared[i]!;// #6278: a member aborted by our own cancellation (never a deadline here) is released, not failed.if ('released' in p) { await releaseUnpublishedClaim(engine, row, p.released === 'claim_lost' ? 'claim_lost' : 'group_member_waiting'); stop ??= independent ? null : 'release'; continue; }- const done = 'ok' in p ? await publishMutation(engine, row, p.ok, run.hostId) : await finishUnpublishedFailure(engine, current, p.error, 'preparation');+ const done = 'ok' in p ? await bounded(() => publishMutation(engine, row, p.ok, run.hostId)) : await finishUnpublishedFailure(engine, current, p.error, 'preparation');run.settled(done);if (done.state === 'committed') { progressed = true; continue; }if (['conflict', 'failed', 'cancelled'].includes(done.state)) { progressed = true; if (!independent) stop = 'cancel'; } else stop = 'release';diff --git a/src/core/persistence/publication-deadline.ts b/src/core/persistence/publication-deadline.tsnew file mode 100644index 0000000000..863d495ca3--- /dev/null+++ b/src/core/persistence/publication-deadline.ts@@ -0,0 +1,91 @@+/**+ * #6288 part 1 / #6352 (P2.3, UC2): a publish that neither resolves nor rejects used to hold its claim, its root and its+ * locks forever while the lease kept renewing. What bounds it now:+ *+ * - On Postgres the publish transaction itself is the real bound. `declareDurablePersistence` already sets a+ * transaction-local `statement_timeout` (5 s) and `lock_timeout`; `bindPublicationTimeouts` adds a transaction-local+ * `idle_in_transaction_session_timeout` of the publication ceiling, so a publisher stuck between statements with the+ * transaction open is ended by the server (its connection is terminated and nothing it did can commit). Both are+ * transaction-scoped, so they hold behind a transaction pooler that drops startup parameters.+ * - `boundPublication` never settles before the publish does, so nothing releases or reports a request or group while+ * its transaction can still commit. At the ceiling it marks the publication overdue (the claim stamp reads+ * `waiting_on: publication_deadline`); a grace later it aborts the publication's signal, which reaches the transaction+ * only on an engine whose `transaction(fn, { signal })` accepts one (GBRA-76's primitive; ignored until then); if the+ * publish still has not settled shortly after, the owner reports `restart_required`. The root stays held: restarting+ * the owner process is the only honest recovery, never a promised reclaim.+ * - On PGLite nothing below the publish can be cancelled: the ceiling only marks the publication overdue and, past the+ * grace, `restart_required`.+ *+ * The wave 9 yield between groups is outside any one `boundPublication` call, so it never counts against a group.+ */+import { AsyncLocalStorage } from 'node:async_hooks';+import type { BrainEngine } from '../engine.ts';+import { gucMilliseconds, resolveSessionTimeouts } from '../db.ts';++export const PUBLICATION_CEILING_KEY = 'persistence.publication_ceiling_ms';+/** `persistence.publication_ceiling_ms`' default (60000 to 3600000 accepted). */+export const PUBLICATION_CEILING_DEFAULT_MS = 5 * 60_000;+/** After the ceiling: how long before the publication's signal is aborted, and how long after that before `restart_required`. */+export const PUBLICATION_GRACE_MS = 30_000;+export const PUBLICATION_SETTLE_MS = 5_000;+const CEILING_TTL_MS = 5_000;++let ceiling = { value: PUBLICATION_CEILING_DEFAULT_MS, at: 0 };+const signals = new AsyncLocalStorage<AbortSignal>();++/** 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 (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() };+ return ceiling.value;+}++/** 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 {+ const session = gucMilliseconds(resolveSessionTimeouts().idle_in_transaction_session_timeout);+ return session !== null && session > 0 ? Math.min(ceilingMs, session) : ceilingMs;+}++/**+ * Sets the transaction-local idle bound as the transaction's first statement. Not awaited: postgres.js sends it ahead of+ * the caller's next statement on the same connection (the `pipelined` contract), so it costs no round trip; a failure+ * surfaces on the statements after it. Skipped on PGLite: it would enforce the bound, and a transaction it ends there+ * wedges the engine's only connection.+ */+export function bindPublicationTimeouts(tx: BrainEngine): void {+ if (tx.kind !== 'postgres') return;+ tx.executeRaw("SELECT set_config('idle_in_transaction_session_timeout',$1,true)", [`${publicationIdleTimeoutMs()}ms`]).catch(() => undefined);+}++/** `engine.transaction`, passing the current publication's signal on as `{ signal }` (an engine without the option ignores it). */+export function publicationTransaction<T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {+ const signal = signals.getStore();+ const run = engine.transaction as (this: BrainEngine, fn: (tx: BrainEngine) => Promise<T>, opts?: { signal?: AbortSignal }) => Promise<T>;+ return run.call(engine, fn, signal ? { signal } : undefined);+}++export interface PublicationBound {+ ceilingMs: number;+ graceMs?: number;+ settleMs?: number;+ /** At the ceiling, with the publish still running. */+ onOverdue?(): void;+ /** Past the ceiling, the grace and the settle window: the owner must restart. `settled` resolves when the publish finally does. */+ onStuck?(settled: Promise<void>): void;+}++/** Runs `publish` under the ceiling; settles only with `publish`'s own outcome. */+export function boundPublication<T>(publish: () => Promise<T>, bound: PublicationBound): Promise<T> {+ const controller = new AbortController();+ const work = signals.run(controller.signal, publish);+ const settled = work.then(() => undefined, () => undefined);+ const timers: Array<ReturnType<typeof setTimeout>> = [];+ const later = (ms: number, fn: () => void) => { const timer = setTimeout(fn, ms); timer.unref?.(); timers.push(timer); };+ const grace = bound.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));+ void settled.then(() => { for (const timer of timers) clearTimeout(timer); });+ return work;+}diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex c9bf9cb953..d665022b5f 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -24,6 +24,7 @@ import { cliRenderContext, renderAction, type Action, type RenderedAction } fromimport { managedSyncResumeArgs, syncResumeCommand } from '../sync-reconcile.ts';import { isWriteCapacityWait, outstandingCapacityOf } from './admission-retry.ts';import { clearDrainStep, readDrainStep } from './drain-step.ts';+import { PUBLICATION_CEILING_DEFAULT_MS, readPublicationCeilingMs } from './publication-deadline.ts';import { isOwnerThisProcess, stampLastSql, WAITING_ON, type ClaimLastSql, type WaitingOn } from './claim-phase.ts';export type DrainOutcome = 'synced' | 'resumable' | 'blocked';@@ -164,8 +165,6 @@ const DEADLINE_MARGIN_MS = 15_000;const PROGRESS_EVERY_MS = 10_000;/** #6405/#6423: a pass with no commit, no admission and no change at the head for this long is ended by the in-pass governor. */const IN_PASS_NO_PROGRESS_MS = 5 * 60_000;-/** #6405: `persistence.publication_ceiling_ms`' default; a live claim in `publishing` past it ends the pass. */-export const PUBLICATION_CEILING_DEFAULT_MS = 5 * 60_000;/** #6405 (R6): the governor's head read is abandoned past this, so a stuck read never parks the governor. */const GOVERN_PROBE_MS = 5_000;const GOVERN_EVERY_MS = 5_000;@@ -587,11 +586,6 @@ function ownerPid(stamp: Record<string, unknown>): number | null {return typeof pid === 'number' ? pid : null;}/** The preparation budgets the drain's allowance reads (Lane A defines and validates the keys; defaults are the documented ones). */-/** #6405: `persistence.publication_ceiling_ms` (60000 to 3600000; anything else reads as the default). */-async function readPublicationCeilingMs(engine: Pick<BrainEngine, 'getConfig'>): Promise<number> {- const n = Number((await engine.getConfig('persistence.publication_ceiling_ms').catch(() => null))?.trim());- return Number.isInteger(n) && n >= 60_000 && n <= 3_600_000 ? n : PUBLICATION_CEILING_DEFAULT_MS;-}async function readPreparationBudgets(engine: Pick<BrainEngine, 'getConfig'>): Promise<{ syncMs: number; maintenanceMs: number; ceilingMs: number }> {const read = async (key: string, fallback: number) => { const n = Number((await engine.getConfig(key).catch(() => null))?.trim()); return Number.isInteger(n) && n > 0 ? n : fallback; };return { syncMs: await read('persistence.sync_preparation_ms', SYNC_PREPARATION_DEFAULT_MS), maintenanceMs: await read('persistence.maintenance_preparation_ms', MAINTENANCE_PREPARATION_DEFAULT_MS),diff --git a/test/persistence-publication-deadline.test.ts b/test/persistence-publication-deadline.test.tsnew file mode 100644index 0000000000..b0976d2a4f--- /dev/null+++ b/test/persistence-publication-deadline.test.ts@@ -0,0 +1,179 @@+/**+ * #6288 part 1 / #6352 (P2.3, UC2): a publish that neither resolves nor rejects. `boundPublication` never settles before+ * the publish does (nothing releases or reports a request while its transaction can still commit), marks it overdue at+ * the ceiling, aborts its signal after the grace (it reaches the transaction only on an engine that takes+ * `transaction(fn, { signal })`) and reports stuck after the settle window. Barrier cases hold a real publishMutation at+ * `before_publication` (after the token lock), `after_publication` (after the file rename) and `before_commit`, then+ * release it: the write commits exactly once. On Postgres the publish transaction carries a transaction-local+ * idle_in_transaction_session_timeout, so a publisher idle past it is ended by the server and commits nothing.+ * Synthetic content only.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import { admitWrite, claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { preparePageMutation } from '../src/core/persistence/page-prepare.ts';+import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { bindPublicationTimeouts, boundPublication, publicationIdleTimeoutMs, publicationTransaction, PUBLICATION_CEILING_DEFAULT_MS } from '../src/core/persistence/publication-deadline.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++const putPage = operations.find(o => o.name === 'put_page')!;+const page = (body: string) => `---\ntitle: Example\ntype: note\n---\n\n${body}\n`;+const tick = (ms: number) => new Promise(r => setTimeout(r, ms));++describe('boundPublication', () => {+ test('never settles before the publish; overdue at the ceiling, signal aborted after the grace, stuck after the settle window', async () => {+ const events: string[] = [];+ let release!: (value: string) => void, seen: AbortSignal | undefined;+ const fake = { transaction: (fn: (tx: unknown) => Promise<unknown>, opts?: { signal?: AbortSignal }) => { seen = opts?.signal; return fn({}); } } as unknown as BrainEngine;+ let stuckSettled: Promise<void> | undefined;+ const work = boundPublication(() => publicationTransaction(fake, () => new Promise<string>(resolve => { release = resolve; })),+ { ceilingMs: 20, graceMs: 20, settleMs: 20, onOverdue: () => events.push('overdue'), onStuck: settled => { events.push('stuck'); stuckSettled = settled; } });+ let outcome: string | undefined;+ void work.then(value => { outcome = value; });+ await tick(10); expect(events).toEqual([]); expect(seen?.aborted).toBe(false);+ await tick(20); expect(events).toEqual(['overdue']); expect(seen?.aborted).toBe(false);+ await tick(20); expect(seen?.aborted).toBe(true); expect(events).toEqual(['overdue']);+ await tick(25); expect(events).toEqual(['overdue', 'stuck']);+ expect(outcome).toBeUndefined();+ release('committed');+ expect(await work).toBe('committed');+ await stuckSettled;+ });++ test('a publish that settles in time fires nothing; a rejection propagates; outside a publication no signal is passed', async () => {+ const events: string[] = [];+ expect(await boundPublication(async () => 'ok', { ceilingMs: 30, onOverdue: () => events.push('overdue'), onStuck: () => events.push('stuck') })).toBe('ok');+ await expect(boundPublication(async () => { throw new Error('boom'); }, { ceilingMs: 30 })).rejects.toThrow('boom');+ await tick(50);+ expect(events).toEqual([]);+ let opts: unknown = 'unset';+ await publicationTransaction({ transaction: (fn: (tx: unknown) => Promise<unknown>, o?: unknown) => { opts = o; return fn({}); } } as unknown as BrainEngine, async () => 1);+ expect(opts).toBeUndefined();+ expect(PUBLICATION_CEILING_DEFAULT_MS).toBe(300_000);+ expect(publicationIdleTimeoutMs(60_000)).toBe(60_000);+ });+});++for (const kind of testBackends()) {+ describe(`a publish held past the publication ceiling (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let root = '';+ const home = mkdtempSync(join(tmpdir(), 'gbrain-pub-deadline-home-'));+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; close = () => lite.disconnect(); }+ }, 120_000);+ afterAll(async () => { await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine)); await close?.(); rmSync(home, { recursive: true, force: true }); });+ beforeEach(async () => {+ await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine));+ if (kind === 'pglite') await resetPgliteState(engine as PGLiteEngine);+ _resetWriteThroughCacheForTest();+ if (kind === 'postgres' && root) return;+ root = mkdtempSync(join(home, 'brain-'));+ await engine.setConfig('sync.repo_path', root);+ if (kind === 'postgres') {+ // Postgres binds no worktree on first write; claim it once for this file (a second claim would need a transfer).+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);+ await withEnv({ GBRAIN_HOME: home }, () => claimWorktree(engine, 'default', root));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ }+ });+ const context = (): OperationContext => ({ engine, config: { engine: kind, embedding_disabled: true } as OperationContext['config'],+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default' });++ /** Admits and claims one put_page of `slug` the way the resident consumer would, after a first write bound the worktree. */+ async function claimedPut(slug: string) {+ await putPage.handler(context(), { slug: `notes/bootstrap-${randomUUID().slice(0, 8)}`, content: page('Binds the worktree.'), request_id: randomUUID() });+ await disposePersistenceConsumer(engine);+ const binding = (await getWorktreeBinding(engine, 'default'))!;+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");+ const authority = await submissionAuthority(context(), 'put_page', 'default', source!.incarnation, slug);+ const intent = { content: page('Written by a process that cannot lock.') };+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default', sourceIncarnation: source!.incarnation,+ slug, pageId: null, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation, requestId: randomUUID(), callerIntent: intent, intent });+ const row = (await claimNextWrite(engine, localHostId()))!;+ return { row, binding, prepared: await preparePageMutation(engine, row, context().config) };+ }+ for (const boundary of ['before_publication', 'after_publication', 'before_commit'] as const) {+ test(`a publish held at ${boundary} past the ceiling is reported overdue and stuck, never settled early; released, it commits once`, async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const slug = `notes/held-${boundary.replaceAll('_', '-')}`;+ const { row, prepared } = await claimedPut(slug);+ let open!: () => void;+ const barrier = new Promise<void>(resolve => { open = resolve; });+ const events: string[] = [];+ const work = boundPublication(() => publishMutation(engine, row, prepared, localHostId(), { boundary: async name => { if (name === boundary) await barrier; } }),+ { ceilingMs: 30, graceMs: 30, settleMs: 30, onOverdue: () => events.push('overdue'), onStuck: () => events.push('stuck') });+ let settled = false;+ void work.then(() => { settled = true; }, () => { settled = true; });+ await tick(150);+ expect(events).toEqual(['overdue', 'stuck']);+ expect(settled).toBe(false);+ // PGLite has one connection, held by the open publish transaction: a read there would wait behind it.+ if (kind === 'postgres') expect((await getWriteRequestById(engine, row.id))?.state).toBe('running');+ open();+ const done = await work;+ expect(done.state).toBe('committed');+ const [count] = await engine.executeRaw<{ n: number | string }>("SELECT count(*) AS n FROM persistence_requests WHERE id=$1::uuid AND state='committed'", [row.id]);+ expect(Number(count!.n)).toBe(1);+ expect(await engine.getPage(slug, { sourceId: 'default' })).not.toBeNull();+ }), 120_000);+ }++ test('the publish transaction opens with the idle bound (Postgres) and receives the publication signal', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const { row, prepared } = await claimedPut('notes/bound-wiring');+ const first: string[] = [], signals: Array<AbortSignal | undefined> = [];+ const recording = new Proxy(engine, { get(target, key) {+ if (key === 'transaction') return <T>(fn: (tx: BrainEngine) => Promise<T>, opts?: { signal?: AbortSignal }) => {+ signals.push(opts?.signal);+ let seen = false;+ return target.transaction(tx => fn(new Proxy(tx, { get(t, k) {+ if (k === 'executeRaw') return (sql: string, ...rest: unknown[]) => { if (!seen) { seen = true; first.push(sql); } return (t.executeRaw as (...a: unknown[]) => unknown)(sql, ...rest); };+ const member = Reflect.get(t, k, t); return typeof member === 'function' ? member.bind(t) : member;+ } })));+ };+ const member = Reflect.get(target, key, target); return typeof member === 'function' ? member.bind(target) : member;+ } }) as BrainEngine;+ const done = await boundPublication(() => publishMutation(recording, row, prepared, localHostId()), { ceilingMs: 60_000 });+ expect(done.state).toBe('committed');+ const publish = first.findIndex(sql => sql.includes('idle_in_transaction_session_timeout'));+ if (kind === 'postgres') expect(publish).toBeGreaterThanOrEqual(0); else expect(publish).toBe(-1);+ expect(signals.some(signal => signal instanceof AbortSignal)).toBe(true);+ }), 120_000);++ test(kind === 'postgres' ? 'a publish transaction idle past its bound is ended by the server and commits nothing' : 'PGLite: the idle bound is never applied (an ended idle transaction would wedge its only connection)', async () => {+ const before = await engine.executeRaw<{ n: number | string }>("SELECT count(*) AS n FROM config WHERE key='p23.probe'");+ const attempt = publicationTransaction(engine, async tx => {+ bindPublicationTimeouts(tx);+ const [shown] = await tx.executeRaw<{ v: string }>("SELECT current_setting('idle_in_transaction_session_timeout') AS v");+ // PGLite would enforce the bound too, and an idle transaction it ends wedges its only connection, so it is never set there.+ expect(shown!.v === '0').toBe(kind !== 'postgres');+ if (kind === 'postgres') await tx.executeRaw("SELECT set_config('idle_in_transaction_session_timeout','300ms',true)");+ await tx.executeRaw("INSERT INTO config(key,value) VALUES('p23.probe','x')");+ await tick(1200);+ await tx.executeRaw('SELECT 1');+ return 'committed';+ });+ if (kind === 'postgres') await expect(attempt).rejects.toBeDefined();+ else expect(await attempt).toBe('committed');+ const [after] = await engine.executeRaw<{ n: number | string }>("SELECT count(*) AS n FROM config WHERE key='p23.probe'");+ expect(Number(after!.n) - Number(before[0]!.n)).toBe(kind === 'postgres' ? 0 : 1);+ if (kind !== 'postgres') await engine.executeRaw("DELETE FROM config WHERE key='p23.probe'");+ }, 30_000);+ });+}