Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): stop at once on a page-write recovery blocked by an edited file

garrytanf1b39a4e47e9
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 2e5c4c8a32..895bc170f6 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -545,8 +545,10 @@ bytes or finishes the write. When the file matches neither the recorded prior
nor the published bytes (usually a hand edit made while the write was
publishing), recovery refuses to overwrite it: the request stays `recovering`
with `unexpected_file_bytes`, no write on that worktree is claimed, and the
-resident writer re-checks it every 30 seconds without progress. Do not delete
-the file to unblock it.
+resident writer re-checks it every 30 seconds without progress. A sync queued
+behind it stops at once with
+[`drain_stalled`, `cause: head_blocked`](write-refusals.md#head-blocked),
+naming the file and this command. Do not delete the file to unblock it.
`gbrain repair stuck-recovery` is the sanctioned exit. Run it on the host that
owns the source.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 7ee3a745a1..abf6954a83 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -515,7 +515,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run
| <a id="drain-write-capacity"></a>`write_capacity` | `queue_capacity` | `blocked` | The sync could not admit its next write for the whole no-progress window (30 s) because other writers' requests held the outstanding-request cap of its write principal (`persistence.limits.principal_outstanding`, default 100; the brain cap `persistence.limits.brain_outstanding`, 1000, works the same way): on one host the CLI sync and a maintenance run (fact-fence adoption, `dream`) share the `local_cli` principal, so a long adoption queue leaves no room for a sync write. Nothing failed and the cursor is intact: the drain retried the admission with backoff while they settled, printing `waiting for write capacity (N outstanding of M)`, and stopped only when the window passed. `drain.capacity` carries the counts and the wait; exit 1. A cumulative cap (permanent request IDs, receipt bytes) is a different refusal: it names its config key and stops at once. | `gbrain sources writer status --source <source> --json` lists the outstanding requests (read-only). Let them finish, or raise the cap (`gbrain config set persistence.limits.principal_outstanding 200`), then rerun the same sync; it resumes where it stopped. |
| <a id="drain-connection-lost"></a>`connection_lost` | `connection_lost` | `blocked` | The database connection dropped three times in a row (`write ECONNABORTED`, `ECONNRESET`, `ETIMEDOUT`, `EPIPE`: a pooler closing the socket mid-statement) with no page committed between the drops (#6340). Each drop was reconnected and retried after 5, 15 and 45 s; a drop that then moves data is not reported at all. Nothing is recorded against the source: the cursor and its frozen manifest stand, and `drain.connection` carries the count and the last error text (never a URL). Exit 1. | Check the database and pooler (`gbrain doctor --json`), then rerun `next.command` (`safe_to_loop` is true, `retry_after_ms` 60 s): it resumes at the stored cursor without re-freezing the manifest, with or without `--retry-failed`. Runbook: [sync unblock](sync-unblock-runbook.md#connection). |
| <a id="drain-capacity-paused"></a>`capacity_paused` | `capacity_paused` | `resumable` | The run passed its capacity preflight, then a cumulative write cap refused its next admission (`write_quota_exhausted`) or, for a background sync, the pause line did (`write_capacity_backpressure`): another writer used the room the preflight counted on. Nothing failed; the cursor and every accepted write stand, and `drain.capacity_pause` names the refusal and its config raise. | Run the `gbrain config set` the report names on the brain host (request ids never free; receipt bytes also free as receipts compact), then rerun the same `gbrain sync`. Verify with `gbrain doctor --only persistence_capacity --json`. |
-| <a id="head-blocked"></a>`drain_stalled` with `cause: head_blocked` | `drain_stalled` | `blocked` | The queued write at the head of the source cannot be claimed by any consumer, and its blocker needs an operator (#6543). `drain.stall.blocked_by` names the predicate, its ids, state and owner: `refresh_fence` (a refresh left the checkout `fenced`, `merged` or `recovery_required` and no refresh process holds its lock), `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`), or `effect_recovery` with state `unexpected_file_bytes` (a fact-withdrawal mirror's page file was edited while the mirror was publishing, so its forward-only recovery refuses to overwrite it; `blocked_by.file` names the page and path). The drain stops after one governor tick of confirmation instead of the no-progress window. Live blockers (`root_hold`, a foreground publication; `lease`, a lapsed claim the next consumer reclaims; `withdrawal_mirror`, an `effect_recovery` that can still finish forward, `request_recovery`, `worktree_owner`) never stop it: the stall line names them as `blocked_by=` beside `consumer=` and the drain keeps waiting. `claimable here` is read for the head itself and prints `unknown` when the probe could not read it. | Run `next.fix`: `refresh_fence` resumes the refresh (`gbrain sources refresh <source> --resume`, which lifts the fence or names why it cannot); `zombie_publication` tells the host admin to restart the named process; `effect_recovery` asks the user to copy the edited file aside and put it back to a version gbrain recorded (undo the edit, or restore the committed version), never to delete it, and to redo the edit after the withdrawal finishes. Then rerun the sync. `gbrain sources writer status --source <source> --json` names the same blocker for every queued head and, only when the caller may cancel the blocking request, `gbrain cancel-write-request <request_id>`. |
+| <a id="head-blocked"></a>`drain_stalled` with `cause: head_blocked` | `drain_stalled` | `blocked` | The queued write at the head of the source cannot be claimed by any consumer, and its blocker needs an operator (#6543). `drain.stall.blocked_by` names the predicate, its ids, state and owner: `refresh_fence` (a refresh left the checkout `fenced`, `merged` or `recovery_required` and no refresh process holds its lock), `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`), or `effect_recovery` with state `unexpected_file_bytes` (a fact-withdrawal mirror's page file was edited while the mirror was publishing, so its forward-only recovery refuses to overwrite it), or `request_recovery` with state `unexpected_file_bytes` (a page write's file was edited while it was publishing, #6650; this also covers a head that is itself that recovering write). For both, `blocked_by.file` names the page and path. A recovery stuck on `unexpected_staging_bytes` is not classified yet and still waits out the window. The drain stops after one governor tick of confirmation instead of the no-progress window. Live blockers (`root_hold`, a foreground publication; `lease`, a lapsed claim the next consumer reclaims; `withdrawal_mirror`, an `effect_recovery` or `request_recovery` that can still finish, `worktree_owner`) never stop it: the stall line names them as `blocked_by=` beside `consumer=` and the drain keeps waiting. `claimable here` is read for the head itself and prints `unknown` when the probe could not read it. | Run `next.fix`: `refresh_fence` resumes the refresh (`gbrain sources refresh <source> --resume`, which lifts the fence or names why it cannot); `zombie_publication` tells the host admin to restart the named process; `effect_recovery` asks the user to copy the edited file aside and put it back to a version gbrain recorded (undo the edit, or restore the committed version), never to delete it, and to redo the edit after the withdrawal finishes; `request_recovery` runs the [`gbrain repair stuck-recovery --source <source>`](repair.md#stuck-recovery) preview, and the user either keeps one version through it or undoes the edit. Then rerun the sync. `gbrain sources writer status --source <source> --json` names the same blocker for every queued head and, only when the caller may cancel the blocking request, `gbrain cancel-write-request <request_id>`. |
| <a id="sync_drain_lease_held"></a>`drain_lease_held` | `sync_drain_lease_held` | `resumable` | Another process holds the source's drain lease (#6712): one managed drainer per source, and that holder (a serve, a `sync` job, the dream cycle, another terminal) is still committing pages. `gbrain sync` follows it within its own `--timeout` and run deadline, printing the holder (kind, pid, host, gbrain version) and the pages it commits (every 10 s on a terminal, 60 s otherwise), and takes the lease when the holder releases it. This code means the budget ended first, or the lease moved to another process mid-pass (`lost`); nothing this run admitted is lost and the cursor is intact. `--no-delegate` never skips the lease. `drain.lease_held.holder` reuses the drain's owner fields: `kind`, `id`, `host`, `pid`, `started_at`, `last_heartbeat_at`, `version` and `progress` (`committed`, `last_committed_at`, `last_progress_at`); `next.retry_after_ms` is 60 s and `next.safe_to_loop` is true. Exit 0. A cron that runs `gbrain sync` every few minutes beside a serve exits 0 here on each tick while the serve works. | Rerun `next.command` after `next.retry_after_ms`, or let the holder finish. Ctrl-C while following stops only this run; the holder keeps going. A holder that commits nothing for 5 minutes is not reported here: the run stops [`drain_stalled`](#drain-lease-stalled) instead. |
| <a id="drain-lease-stalled"></a>`drain_stalled` with `cause: no_progress` and `stall.lease_holder` | `drain_stalled` | `blocked` | The process holding the source's drain lease committed no page and saved no cursor for 5 minutes, so following it would exit 0 forever (#6712). `drain.stall.lease_holder` names it with the fields above; the lease itself is renewed by a live process, so a wedged holder keeps it. A holder that died lets its lease lapse within 2 minutes and the next run takes over without this stop. Exit 1, `next.safe_to_loop` false. | `gbrain sources writer status --source <source> --json` (read-only) shows what the holder is waiting on. Stop or restart the named process; when it is gone but its lock row remains, `gbrain sync --source <source> --no-pull --break-lock` releases a lock whose pid is dead (`--force-break-lock` skips the liveness check: only when you know the holder is gone). Then rerun the same sync. |
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 4c41f6763e..1329304672 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -692,8 +692,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.258.0', text: 'A connector source\'s autopilot cycle now extracts facts and recomputes emotional weight only for that source\'s pages changed since its last completed cycle. Before, both phases walked every page in the brain on every connector cycle, which on a large brain ran past the 30-minute job deadline, so the cycle never finished and repeated the full walk.' },
// LHF wave 2 item 0 (GBRA-94): tokenmax `query` no longer expands by default.
{ since: '0.60.259.0', text: '`gbrain query` no longer runs LLM query expansion by default on `tokenmax`, so no search mode expands by default. On 300 LongMemEval-S questions with the reranker, `query` without expansion kept retrieval within noise (298 vs 299 of 300) and its p50 fell from about 2 s to about 230 ms (gbrain-evals expansion-latency report, 2026-10-14). To keep expanding: `gbrain config set search.expansion true` for the brain, or pass `--expand` / `expand: true` per call.' },
- // A sync behind a withdrawal-mirror recovery blocked on unexpected_file_bytes stops at once instead of waiting 5 minutes.
- { since: '0.60.260.0', text: 'A sync queued behind a fact-withdrawal mirror whose page file was edited while the mirror was publishing (its recovery refuses `unexpected_file_bytes` and only the user can resolve the file) now stops after one governor tick with `drain_stalled`, `cause: head_blocked` and `blocked_by=effect_recovery(unexpected_file_bytes …)`, instead of waiting out the 5-minute no-progress window. Its fix names the file and asks the user to put it back to a version gbrain recorded, then rerun the sync; `gbrain sources writer status` names the same file. A mirror recovery that can still finish forward keeps the wait.' },
+ // A sync behind a withdrawal-mirror or page-write recovery blocked on unexpected_file_bytes stops at once instead of waiting 5 minutes.
+ { since: '0.60.260.0', text: 'A sync queued behind a recovery that only the user can resolve now stops after one governor tick with `drain_stalled`, `cause: head_blocked`, instead of waiting out the 5-minute no-progress window. Two recoveries count: a fact-withdrawal mirror whose page file was edited while the mirror was publishing (`blocked_by=effect_recovery(unexpected_file_bytes …)`; the fix asks the user to put the file back to a version gbrain recorded, then rerun the sync), and a page write whose file was edited while it was publishing (`blocked_by=request_recovery(unexpected_file_bytes …)`, whether it blocks the queued head or is the head; the fix runs the `gbrain repair stuck-recovery` preview, or the user undoes the edit). Both name the file, and `gbrain sources writer status` shows the same advice. A recovery that can still finish (its file back on a recorded version) keeps the wait. Known gap: a recovery stuck on `unexpected_staging_bytes` still waits out the window.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/head-blocker.ts b/src/core/persistence/head-blocker.ts
index 5c580714d2..8dd8dea998 100644
--- a/src/core/persistence/head-blocker.ts
+++ b/src/core/persistence/head-blocker.ts
@@ -6,7 +6,8 @@
* governor tick of confirmation: a durable refresh fence no live refresh process holds, a running row ahead whose owner
* reports `restart_required` (a zombie publication), or a withdrawal-mirror effect recovery its own last attempt refused
* `unexpected_file_bytes` whose file still matches neither recorded version (an edit made while the mirror was publishing;
- * recovery only finishes forward and never overwrites it). Every other blocker is live and transient (a foreground publication,
+ * recovery only finishes forward and never overwrites it), or a page write's publication recovery refused the same way (#6650;
+ * `gbrain repair stuck-recovery` is its exit), whether it blocks a queued head or is the head itself. Every other blocker is live and transient (a foreground publication,
* a refresh or recovery making progress, a lapsed lease the next consumer reclaims), so the drain keeps its progress-aware wait.
*/
import { existsSync, readFileSync } from 'node:fs';
@@ -14,6 +15,7 @@ import { basename, dirname } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { cliRenderContext, renderAction, type Action, type RenderedAction } from '../agent-output.ts';
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';
@@ -29,7 +31,7 @@ export interface HeadBlocker {
owner: { kind: string | null; pid: number | null; live: boolean | null; restart_required: boolean } | null;
/** True when only an operator clears it; the drain stops on these and keeps waiting on the rest. */
intervention: boolean;
- /** The canonical file an `unexpected_file_bytes` effect recovery refuses to overwrite. */
+ /** The canonical file an `unexpected_file_bytes` effect or request recovery refuses to overwrite. */
file?: { slug: string; path: string };
}
/** A blocking request this caller may cancel: not publishing, no recovery record; `cancel-write-request` is scoped to its principal. */
@@ -39,22 +41,35 @@ export type HeadBlockerRead = { status: 'claimable' } | { status: 'blocked'; blo
interface RowRef { request_id: string; state: string; claim_phase: unknown; execution_token: string | null; claim_lapsed: boolean;
publication_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: string[] | null;
+ fence: { id: string; state: string } | null; effect_recovery: EffectRecoveryRef[] | null; mirrors: string[] | null; request_recovery: RequestRecoveryRef[] | 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 }
+const REQUEST_RECOVERY = (alias: string) => `jsonb_build_object('request_id',${alias}.request_id::text,'state',${alias}.state,'blocked_reason',${alias}.blocked_reason,
+ 'slug',${alias}.slug,'version',${alias}.recovery->>'version','path',${alias}.recovery->>'path','before',${alias}.recovery->>'beforeHash','after',${alias}.recovery->>'afterHash')`;
/**
- * Whether an effect recovery cannot finish without the user: its last attempt refused `unexpected_file_bytes` and the file still
- * matches neither recorded hash (the check recovery itself refuses on). A file put back on a recorded version is live again before
- * the next retry clears the code; a file this process cannot read keeps the recovery's own verdict.
+ * Whether a recovery's last attempt refused `unexpected_file_bytes` and its file still matches neither recorded hash (the check
+ * recovery itself refuses on), so only the user clears it. A file put back on a recorded version is live again before the next
+ * attempt clears the code; a file this process cannot read keeps the recovery's own verdict.
*/
-function effectRecoveryStuck(effect: EffectRecoveryRef): boolean {
- if (effect.error_code !== 'unexpected_file_bytes' || !effect.path) return false;
+function stuckOnFile(code: string | null, path: string | null, before: string | null, after: string | null): path is string {
+ if (code !== 'unexpected_file_bytes' || !path) return false;
try {
- const actual = existsSync(effect.path) ? sha256(readFileSync(effect.path)) : null;
- return actual !== effect.before && actual !== effect.after;
+ const actual = existsSync(path) ? sha256(readFileSync(path)) : null;
+ return actual !== before && actual !== after;
} catch { return true; }
}
+const effectRecoveryStuck = (effect: EffectRecoveryRef) => stuckOnFile(effect.error_code, effect.path, effect.before, effect.after);
+/** A live page recovery (a terminal one never restores its file; a skill bundle has no stuck-recovery exit). */
+const requestRecoveryStuck = (request: RequestRecoveryRef) => request.version === '1' && !isTerminal(request)
+ && stuckOnFile(request.blocked_reason, request.path, request.before, request.after);
+const requestRecoveryBlocker = (refs: RequestRecoveryRef[]): HeadBlocker => {
+ const stuck = refs.find(requestRecoveryStuck);
+ return { predicate: 'request_recovery', ids: refs.map(ref => ref.request_id), state: stuck ? 'unexpected_file_bytes' : null, owner: null, intervention: !!stuck,
+ ...(stuck ? { file: { slug: stuck.slug, path: stuck.path! } } : {}) };
+};
const REF = (alias: string) => `jsonb_build_object('request_id',${alias}.request_id::text,'state',${alias}.state,'claim_phase',${alias}.claim_phase,
'execution_token',${alias}.execution_token::text,'claim_lapsed',COALESCE(${alias}.claim_expires_at<now(),false),'publication_started',COALESCE(${alias}.publication_started,false),
@@ -77,7 +92,7 @@ export async function readHeadBlockers(engine: BrainEngine, ids: string[], hostI
'before',e.recovery->>'beforeHash','after',e.recovery->>'afterHash') ORDER BY e.id) FROM persistence_effects e WHERE e.worktree_id=r.worktree_id AND e.recovery IS NOT NULL) AS effect_recovery,
(SELECT array_agg(m.id::text) FROM persistence_effects m WHERE m.worktree_id=r.worktree_id AND m.kind='withdrawal-mirror' AND m.state IN ('queued','running')
AND (NOT (m.data ? 'targets') OR m.data->'targets' @> jsonb_build_array(jsonb_build_object('slug',r.slug)))) AS mirrors,
- (SELECT array_agg(b.request_id::text) FROM persistence_requests b WHERE b.worktree_id=r.worktree_id AND b.recovery IS NOT NULL) AS request_recovery,
+ (SELECT jsonb_agg(${REQUEST_RECOVERY('b')} ORDER BY b.sequence) FROM persistence_requests b WHERE b.worktree_id=r.worktree_id AND b.recovery IS NOT NULL) AS request_recovery,
(SELECT jsonb_agg(${REF('e')} ORDER BY e.sequence) FROM persistence_requests e
WHERE ((r.worktree_id IS NOT NULL AND e.worktree_id=r.worktree_id) OR (r.worktree_id IS NULL AND e.worktree_id IS NULL AND e.source_incarnation=r.source_incarnation))
AND ${EARLIER_HEAD('e', 'r', priority, "'{}'::text[]")}) AS earlier,
@@ -106,7 +121,7 @@ export async function readHeadBlockers(engine: BrainEngine, ids: string[], hostI
continue;
}
if (row.mirrors?.length) { blocked({ predicate: 'withdrawal_mirror', ids: row.mirrors, state: null, owner: null, intervention: false }); continue; }
- if (row.request_recovery?.length) { blocked({ predicate: 'request_recovery', ids: row.request_recovery, state: null, owner: null, intervention: false }); continue; }
+ if (row.request_recovery?.length) { blocked(requestRecoveryBlocker(row.request_recovery)); 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 });
@@ -125,6 +140,17 @@ export async function readHeadBlockers(engine: BrainEngine, ids: string[], hostI
return out;
}
+/**
+ * A head that is itself a recovering page write: its blocker only when its recovery is stuck on the user (see `requestRecoveryStuck`)
+ * and this host owns its worktree, so the recorded path is this host's file; null otherwise, the recovery being live work.
+ */
+async function recoveringHeadBlocker(engine: BrainEngine, id: string, hostId: string | null, opts: { timeoutMs?: number; signal?: AbortSignal }): Promise<HeadBlocker | null> {
+ const [row] = await engine.executeRaw<{ ref: RequestRecoveryRef; owner_host_id: string | null }>(`SELECT ${REQUEST_RECOVERY('r')} AS ref, w.owner_host_id::text AS owner_host_id
+ FROM persistence_requests r JOIN persistence_worktrees w ON w.id=r.worktree_id WHERE r.id=$1::uuid AND r.recovery IS NOT NULL`, [id], opts);
+ if (!row || !hostId || row.owner_host_id !== hostId || !requestRecoveryStuck(row.ref)) return null;
+ return requestRecoveryBlocker([row.ref]);
+}
+
/** Whether a refresh process holds the worktree's refresh lock: true held, false free, null when the lock cannot be probed here. */
async function refreshOwnerLive(worktreeId: string): Promise<boolean | null> {
try {
@@ -159,6 +185,18 @@ export function headBlockerAction(blocker: HeadBlocker, sourceId: string, resume
why: `Request ${blocker.ids[0]} ahead of the head is held by ${who}, which reports restart_required; its root stays held until that process exits. Status names it, read-only.`,
user_message: `Restart ${who} on the brain host, then run: ${resumeCommand}`, verify: { argv: status } };
}
+ if (blocker.predicate === 'request_recovery' && blocker.intervention && blocker.file) {
+ const { path, slug } = blocker.file;
+ const preview = ['gbrain', 'repair', 'stuck-recovery', '--source', sourceId];
+ return { argv: preview, consent: [], actor: 'agent', requires_exclusive: false,
+ why: `A write to ${path} (page ${slug}) was interrupted while publishing and the file was edited after that: it matches neither the bytes from before the write `
+ + `nor the bytes the write published, so recovery will not overwrite it, every write to source ${sourceId} waits, and waiting does not clear it. `
+ + 'The preview changes no page or canonical file (it writes only private diffs) and lists the file, its diff and the choices; which version to keep is the user\'s call.',
+ user_message: `${path} was edited while gbrain was writing page ${slug}, so gbrain will not touch the file and writes to source ${sourceId} are paused. `
+ + `Either undo the edit (put the file back as it was) and run: ${resumeCommand}. Or choose which version to keep with ${preview.join(' ')}, which shows the diff: `
+ + 'the bytes from before gbrain\'s write, or the edited bytes. Do not delete the file.',
+ verify: { argv: status } };
+ }
if (blocker.predicate === 'effect_recovery' && blocker.intervention && blocker.file) {
const { path, slug } = blocker.file;
return { argv: status, consent: [], actor: 'user', requires_exclusive: false,
@@ -205,9 +243,15 @@ export async function describeHostConsumer(engine: BrainEngine, opts: { signal?:
} catch { return 'unknown'; }
}
-/** `claimable_here` and `blocked_by` for a head: a queued head is probed (a failed read is `null`, printed `unknown`); any other head is not claimable. */
+/**
+ * `claimable_here` and `blocked_by` for a head: a queued head is probed (a failed read is `null`, printed `unknown`); any other head is not
+ * claimable, and a recovering head names itself as its blocker only when its recovery is stuck on the user.
+ */
export async function headClaimability(engine: BrainEngine, head: { id: string | null; state: string | null }, hostId: string | null,
opts: { timeoutMs?: number; signal?: AbortSignal } = {}): Promise<{ claimable_here: boolean | null; blocked_by: HeadBlocker | null }> {
+ if (head.id && head.state === 'recovering') {
+ return recoveringHeadBlocker(engine, head.id, hostId, opts).then(blocker => ({ claimable_here: false, blocked_by: blocker }), () => ({ claimable_here: false, blocked_by: null }));
+ }
if (!head.id || head.state !== 'queued') return { claimable_here: false, blocked_by: null };
const read = await readHeadBlockers(engine, [head.id], hostId, opts).then(found => found.get(head.id!) ?? { status: 'unknown' as const }, () => ({ status: 'unknown' as const }));
return read.status === 'claimable' ? { claimable_here: true, blocked_by: null } : read.status === 'blocked' ? { claimable_here: false, blocked_by: read.blocker } : { claimable_here: null, blocked_by: null };
@@ -236,7 +280,7 @@ export async function readQueuedHeadBlockers(engine: BrainEngine, rows: Array<{
? `gbrain cancel-write-request ${read.cancel.request_id}` : null;
const action = headBlockerAction(read.blocker, source ?? '<source>', `gbrain sync --source ${source ?? '<source>'}`);
out.set(id, { fields: { claimable_here: false, blocked_by: read.blocker, ...(cancel ? { cancel_command: cancel } : {}) },
- advice: `Blocked by ${headBlockerText(read.blocker)}: ${action.user_message ?? action.why}${read.blocker.predicate === 'refresh_fence' ? ` Run: ${action.argv!.join(' ')}.` : ''}`
+ advice: `Blocked by ${headBlockerText(read.blocker)}: ${action.user_message ?? action.why}${read.blocker.predicate === 'refresh_fence' || (read.blocker.predicate === 'request_recovery' && read.blocker.intervention) ? ` Run: ${action.argv!.join(' ')}.` : ''}`
+ `${cancel ? ` Cancelling the blocking request (it has not started publishing) also frees the head; a sync rerun admits it again: ${cancel}` : ''}` });
}
return out;
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index 667e05730f..79913f75ce 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -460,8 +460,9 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
const base = { request_id: head?.request_id ?? 'none', state: head?.head_state ?? 'none', blocked_reason: null, head_request_id: head?.request_id ?? null,
head_state: head?.head_state ?? null, claimable_here: !read.ok ? null : head?.claimable_here === undefined ? false : head.claimable_here, owner_is_this_host: null, in_pass: true,
blocked_by: head?.blocked_by ?? null, consumer: head?.consumer ?? null };
- // #6543 (B2): an intervention-required blocker on a queued head, read on two ticks in a row, stops the drain now; live blockers keep the wait below.
- const blocker = head?.head_state === 'queued' && head.blocked_by?.intervention ? head.blocked_by : null;
+ // #6543 (B2): an intervention-required blocker on a queued head (or a recovering head stuck on the user), read on two ticks in a row, stops the
+ // drain now; live blockers keep the wait below.
+ const blocker = (head?.head_state === 'queued' || head?.head_state === 'recovering') && head.blocked_by?.intervention ? head.blocked_by : null;
const seen = blocker ? `${head!.request_id}|${blocker.predicate}|${blocker.ids.join(',')}` : null;
if (blocker && seen === blockedKey) { stop({ ...base, stalled_seconds: Math.round(quiet / 1000), cause: 'head_blocked' }); return; }
blockedKey = seen;
diff --git a/test/sync-drain-effect-recovery-blocked.test.ts b/test/sync-drain-effect-recovery-blocked.test.ts
index c57b9137c2..107e114a39 100644
--- a/test/sync-drain-effect-recovery-blocked.test.ts
+++ b/test/sync-drain-effect-recovery-blocked.test.ts
@@ -4,6 +4,8 @@
* classify every effect recovery as live, so a sync behind it waited the whole no-progress window (5 minutes) before stopping.
* Such a recovery is now intervention-required: the drain stops `drain_stalled` / `cause: head_blocked` after one governor tick
* with a fix naming the file. A recovery that can still finish forward (the file holds a recorded version) keeps the wait.
+ * A page write's own publication recovery refused the same way (#6650) stops the same way, its fix pointing at
+ * `gbrain repair stuck-recovery`.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
@@ -24,7 +26,10 @@ import { serializePageToMarkdown } from '../src/core/markdown.ts';
import { headClaimability } from '../src/core/persistence/head-blocker.ts';
import { drainNext, engineStallProbe, formatDrainSummary, runDrain } from '../src/core/persistence/sync-drain.ts';
import { readWriterDiagnostics } from '../src/core/persistence/diagnostics.ts';
+import { recoverPublication } from '../src/core/persistence/coordinator.ts';
+import { getWriteRequestById } from '../src/core/persistence/journal.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { AFTER, EDITED, PRIOR, stuckRecoveryFixture } from './helpers/stuck-recovery-fixture.ts';
import { testBackends } from './helpers/test-backends.ts';
import type { SyncResult } from '../src/commands/sync.ts';
@@ -152,3 +157,48 @@ describe('withdrawal-mirror effect recovery blocking a sync', () => {
}
}, 120_000);
});
+
+describe('page-write request recovery blocking a sync', () => {
+ test('a request recovery refusing unexpected_file_bytes stops the sync at once and points at gbrain repair stuck-recovery; undoing the edit clears it', async () => {
+ for (const [kind, engine] of engines) {
+ const s = await stuckRecoveryFixture(engine, roots).stuck({ prior: PRIOR, after: AFTER, disk: EDITED, follower: true });
+ const started = Date.now();
+ const result = await runDrain({ governMs: 20, noProgressMs: 10_000, publicationCeilingMs: 60_000, probe: engineStallProbe(engine, s.sourceId),
+ pass: () => new Promise<SyncResult>(() => undefined) });
+ const elapsed = Date.now() - started;
+ const blockedBy = { predicate: 'request_recovery', ids: [s.requestId], state: 'unexpected_file_bytes', intervention: true, file: { slug: 'page', path: s.path } };
+ expect(result.drain, kind).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled',
+ stall: { cause: 'head_blocked', in_pass: true, head_request_id: s.id, head_state: 'recovering', claimable_here: false, blocked_by: blockedBy } });
+ expect(elapsed, kind).toBeLessThan(5_000);
+ const resume = `gbrain sync --source ${s.sourceId}`, preview = ['gbrain', 'repair', 'stuck-recovery', '--source', s.sourceId];
+ const next = drainNext(result, resume, s.sourceId)!;
+ expect(next, kind).toMatchObject({ code: 'drain_stalled', cause: 'head_blocked', safe_to_loop: false, command: preview.join(' '),
+ fix: { actor: 'agent', next: 'run', argv: preview } });
+ expect(next.why, kind).toContain(s.path);
+ expect(next.fix!.user_message, kind).toContain(s.path);
+ expect(next.fix!.user_message, kind).toContain(resume);
+ expect(next.fix!.user_message, kind).toContain(preview.join(' '));
+ expect(formatDrainSummary(result, resume, s.sourceId).join('\n'), kind).toContain(`blocked_by=request_recovery(unexpected_file_bytes ${s.requestId})`);
+
+ // The queued write behind it is classified the same way, and writer status names the preview.
+ expect(await headClaimability(engine, { id: s.follower!, state: 'queued' }, hostId), kind).toMatchObject({ claimable_here: false, blocked_by: blockedBy });
+ const follower = (await getWriteRequestById(engine, s.follower!))!;
+ const status = await readWriterDiagnostics(engine);
+ const row = (status.blockers as Array<Record<string, unknown>>).find(b => b.request_id === follower.request_id)!;
+ expect(row, kind).toMatchObject({ claimable_here: false, blocked_by: { predicate: 'request_recovery', intervention: true } });
+ expect(String(row.next_action), kind).toContain(preview.join(' '));
+
+ // Undoing the edit makes the recovery live again before its next pass: the drain keeps waiting, then the pass finishes it.
+ writeFileSync(s.path, PRIOR);
+ expect(await headClaimability(engine, { id: s.follower!, state: 'queued' }, hostId), kind)
+ .toMatchObject({ claimable_here: false, blocked_by: { predicate: 'request_recovery', intervention: false } });
+ let reads = 0;
+ const probe = engineStallProbe(engine, s.sourceId), head = probe.head!;
+ const waited = await runDrain({ governMs: 10, noProgressMs: 60_000, publicationCeilingMs: 60_000, probe: { ...probe, head: async () => { reads++; return head(); } },
+ pass: () => new Promise<SyncResult>(resolve => setTimeout(() => resolve(done), 400)) });
+ expect(reads, kind).toBeGreaterThanOrEqual(3);
+ expect(waited.drain, kind).toMatchObject({ outcome: 'synced' });
+ expect(await recoverPublication(engine, s.id), kind).toMatchObject({ state: 'queued', blocked_reason: null });
+ }
+ }, 120_000);
+});