Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): persistence_write_stall catches re-taken claims on a root with no progress (#6635)

time-attackf1ad7beb555b
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 4ad14c61f6..4252bc1e87 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -197,7 +197,7 @@ default: moved (3 pages committed, head advanced import_screen -> knowledge_publ
Two calls, no SQL: the doctor or `sources status` row names the command, and `writer status` ends in the action. A `data_moving: false` that returns after the restart means a different owner is wedged or the same one wedged again: the same two calls name it.
-<a id="persistence-write-stall"></a>**A managed write stays `running` and later writes queue behind it, or doctor warns `persistence_write_stall`?** The owner keeps renewing a hung claim; doctor warns past `persistence.max_claim_ms` (default 600000) and names the request, root, age, phase and, for a preparation, its step and what it waited on. A write stuck *preparing* is released at its deadline and finally held or failed `preparation_stalled` on its own: see [catch-up stuck](#catch-up-stuck). A write stuck *publishing*, or one whose owner predates the deadlines, still needs the owner restarted: run `gbrain sources writer status --source <id> --json` (read-only), then restart the `gbrain serve` that owns the root and attach that output when reporting it.
+<a id="persistence-write-stall"></a>**A managed write stays `running` and later writes queue behind it, or doctor warns `persistence_write_stall`?** The owner keeps renewing a hung claim; doctor warns past `persistence.max_claim_ms` (default 600000) and names the request, root, age, phase and, for a preparation, its step and what it waited on. A claim released and taken again every few seconds never ages that far, so doctor also warns about a running request at least `persistence.max_claim_ms` old when no request on its root (its worktree, or for a database-only request the source's other database-only requests) reached a terminal state within that window (#6635); each stall carries `request_age_ms` and the message uses the larger age. A write stuck *preparing* is released at its deadline and finally held or failed `preparation_stalled` on its own: see [catch-up stuck](#catch-up-stuck). A write stuck *publishing*, or one whose owner predates the deadlines, still needs the owner restarted: run `gbrain sources writer status --source <id> --json` (read-only), then restart the `gbrain serve` that owns the root and attach that output when reporting it.
<a id="terminal-write-failures"></a>**Doctor warns `persistence_terminal_failures`, or `gbrain sync status` reports terminal write failures?** Every write leaves a receipt, and a receipt that ended `failed`, `conflict` or `cancelled` stays in `persistence_requests` until compaction. gbrain reads them at query time and sorts each one into a category with a class, safe actions, whether a person decides, and a structured fix (nothing new is stored). Most rows need no action, so the check separates three things:
diff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.ts
index 2e1f907109..8c85fcbafe 100644
--- a/src/commands/doctor/checks/persistence-requests.ts
+++ b/src/commands/doctor/checks/persistence-requests.ts
@@ -118,6 +118,9 @@ export async function requestGrowthCheck(engine: BrainEngine): Promise<Check> {
* #6278: each stall also carries the claim's step, what it waits on, the owner
* process and, for a preparation past its budget, `claim.stall`
* (`preparation_overdue`); the budgets in effect are in the details.
+ * A claim that is released and taken again every few seconds never ages past
+ * `max_claim_ms`, so a running request is also a stall once it is that old and
+ * no request on its root reached a terminal state within the same window.
*/
export async function writeStallCheck(engine: BrainEngine): Promise<Check> {
const docs = 'docs/guides/troubleshooting.md#persistence-write-stall';
@@ -125,22 +128,31 @@ export async function writeStallCheck(engine: BrainEngine): Promise<Check> {
const maxClaimMs = await readMaxClaimMs(engine);
const policy = await readPreparationPolicy(engine);
const rows = await engine.executeRaw<{ request_id: string; source_id: string; worktree_id: string | null; operation: string; intent_kind: string | null; state: string; claim_phase: unknown;
- execution_token: string | null; claim_lapsed: boolean | null; publication_started: boolean; request_age_ms: string; waiting: number }>(
+ execution_token: string | null; claim_lapsed: boolean | null; publication_started: boolean; request_age_ms: string; no_root_progress: boolean; waiting: number }>(
`SELECT r.request_id::text,r.source_id,r.worktree_id::text,r.operation,r.intent->>'kind' AS intent_kind,r.state,r.claim_phase,r.execution_token::text,r.claim_expires_at<now() AS claim_lapsed,
r.publication_started,(EXTRACT(EPOCH FROM (now()-r.created_at))*1000)::bigint::text AS request_age_ms,
+ NOT EXISTS (SELECT 1 FROM persistence_requests q WHERE ((r.worktree_id IS NOT NULL AND q.worktree_id=r.worktree_id)
+ OR (r.worktree_id IS NULL AND q.worktree_id IS NULL AND q.source_id=r.source_id))
+ AND q.state IN ('committed','conflict','failed','cancelled') AND q.completed_at>=now()-($1::double precision*interval '1 millisecond')
+ AND q.recovery IS NULL AND NOT q.compacted) AS no_root_progress,
(SELECT count(*)::int FROM persistence_requests q WHERE q.worktree_id=r.worktree_id AND q.state='queued' AND q.sequence>r.sequence) AS waiting
- FROM persistence_requests r WHERE r.state='running' ORDER BY r.sequence LIMIT 100`);
+ FROM persistence_requests r WHERE r.state='running' ORDER BY r.sequence LIMIT 100`, [maxClaimMs]);
const now = Date.now();
const stalls = rows.flatMap(row => {
const claim = claimStateOf(row, now);
if (!claim) return [];
// An owner that predates phase recording never stamps its claims; the request's own age bounds the claim's.
const held = claim.claim_age_ms ?? (row.claim_phase == null ? Math.max(0, Number(row.request_age_ms)) : null);
- if (held === null || !(held >= maxClaimMs)) return [];
+ const stalledWithoutProgress = row.no_root_progress && Number(row.request_age_ms) >= maxClaimMs;
+ if (!(held !== null && held >= maxClaimMs) && !stalledWithoutProgress) return [];
+ const claimAgeMs = held ?? claim.claim_age_ms ?? 0;
+ const requestAgeMs = Math.max(0, Number(row.request_age_ms));
const budget = preparationBudgetMs({ operation: row.operation, intent: row.intent_kind ? { kind: row.intent_kind } : null }, policy, 30_000);
return [{ request_id: row.request_id, source_id: row.source_id, root: row.worktree_id, operation: row.operation, intent_kind: row.intent_kind, phase: claim.phase,
- claim_age_ms: held, phase_age_ms: claim.phase_age_ms, step: claim.step, step_age_ms: claim.step_age_ms, waiting_on: claim.waiting_on, owner: claim.owner,
- budget_ms: budget, stall: claimStall(claim, budget), waiting_behind: row.waiting, resumes_on_its_own: claim.resumes_on_its_own, why: claim.why }];
+ claim_age_ms: claimAgeMs, request_age_ms: requestAgeMs, phase_age_ms: claim.phase_age_ms, step: claim.step, step_age_ms: claim.step_age_ms, waiting_on: claim.waiting_on, owner: claim.owner,
+ budget_ms: budget, stall: claimStall(claim, budget), waiting_behind: row.waiting, resumes_on_its_own: claim.resumes_on_its_own,
+ why: stalledWithoutProgress && !(held !== null && held >= maxClaimMs)
+ ? `${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 } };
@@ -149,9 +161,9 @@ export async function writeStallCheck(engine: BrainEngine): Promise<Check> {
const first = stalls[0]!;
const minutes = (ms: number) => `${Math.round(ms / 60_000)} min`;
return { name: 'persistence_write_stall', status: 'warn', details,
- message: `${stalls.length} write request(s) have held their claim longer than ${MAX_CLAIM_CONFIG_KEY} (${maxClaimMs} ms). `
+ message: `${stalls.length} write request(s) have stalled beyond ${MAX_CLAIM_CONFIG_KEY} (${maxClaimMs} ms). `
+ stalls.slice(0, 3).map(stall => `Request ${stall.request_id} (${stall.operation}) on source ${stall.source_id}, root ${stall.root ?? 'database-only'}, `
- + `is stuck in phase ${stall.phase} after ${minutes(stall.claim_age_ms)}; ${stall.waiting_behind} queued write(s) wait behind it. ${stall.why}`).join(' ')
+ + `is stuck in phase ${stall.phase} after ${minutes(Math.max(stall.claim_age_ms, stall.request_age_ms))}; ${stall.waiting_behind} queued write(s) wait behind it. ${stall.why}`).join(' ')
+ ` Next: inspect it with gbrain sources writer status --source ${first.source_id} --json, then restart the gbrain serve that owns the root`
+ `${first.resumes_on_its_own ? ' if it is still stuck after its transaction ends' : ''}. The root trigger of a hang is not known yet; attach that status output when reporting it.`,
fix: agentFix(['gbrain', 'sources', 'writer', 'status', '--source', first.source_id, '--json'],
diff --git a/test/persistence-write-stall.test.ts b/test/persistence-write-stall.test.ts
index 41d55060ed..fd82123fb6 100644
--- a/test/persistence-write-stall.test.ts
+++ b/test/persistence-write-stall.test.ts
@@ -87,6 +87,53 @@ async function scenario(engine: BrainEngine, config: HarnessConfig) {
installFaultHook(undefined);
await consumer.stop();
}
+ const churn = await admitWrite(engine, admission(config, sources[1]!, 'stall/churn', 'churning body'));
+ const churnToken = randomUUID();
+ await engine.executeRaw(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,claim_expires_at=now()+interval '30 seconds',
+ claim_phase=jsonb_build_object('phase','preparing','claimed_at',now()::text,'since',now()::text,'token',$2::text),created_at=now()-interval '39 hours'
+ WHERE id=$1::uuid`, [churn.id, churnToken]);
+ const churnCheck = await writeStallCheck(engine);
+ expect(churnCheck.status).toBe('warn');
+ expect(churnCheck.details).toMatchObject({ stalls: [{ request_id: churn.request_id, source_id: sources[1]!.id, root: churn.worktree_id }] });
+ expect((churnCheck.details as { stalls: Array<{ why: string }> }).stalls[0]!.why).toContain('No request on this root reached a terminal state');
+ expect(churnCheck.message).toContain('after 2340 min');
+
+ const progress = await admitWrite(engine, admission(config, sources[1]!, 'stall/progress', 'progress body'));
+ await engine.executeRaw(`UPDATE persistence_requests SET state='committed',completed_at=now()-interval '1 minute' WHERE id=$1::uuid`, [progress.id]);
+ const progressCheck = await writeStallCheck(engine);
+ expect(progressCheck.status).toBe('ok');
+ expect(progressCheck.details).toMatchObject({ count: 0, stalls: [] });
+
+ await engine.executeRaw('DELETE FROM persistence_requests WHERE id=$1::uuid OR id=$2::uuid', [churn.id, progress.id]);
+ const young = await admitWrite(engine, admission(config, sources[1]!, 'stall/young', 'young body'));
+ const youngToken = randomUUID();
+ await engine.executeRaw(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,claim_expires_at=now()+interval '30 seconds',
+ claim_phase=jsonb_build_object('phase','preparing','claimed_at',now()::text,'since',now()::text,'token',$2::text),created_at=now()-interval '2 minutes'
+ WHERE id=$1::uuid`, [young.id, youngToken]);
+ const youngCheck = await writeStallCheck(engine);
+ expect(youngCheck.status).toBe('ok');
+ expect(youngCheck.details).toMatchObject({ count: 0, stalls: [] });
+
+ // A database-only root (no worktree): progress is judged per source among database-only requests.
+ await engine.executeRaw('DELETE FROM persistence_requests WHERE id=$1::uuid', [young.id]);
+ const dbOnly = await admitWrite(engine, admission(config, sources[1]!, 'stall/db-only', 'db-only body'));
+ const dbOnlyToken = randomUUID();
+ await engine.executeRaw(`UPDATE persistence_requests SET state='running',worktree_id=NULL,execution_token=$2::uuid,claim_expires_at=now()+interval '30 seconds',
+ claim_phase=jsonb_build_object('phase','preparing','claimed_at',now()::text,'since',now()::text,'token',$2::text),created_at=now()-interval '39 hours'
+ WHERE id=$1::uuid`, [dbOnly.id, dbOnlyToken]);
+ const dbOnlyCheck = await writeStallCheck(engine);
+ expect(dbOnlyCheck.status).toBe('warn');
+ expect(dbOnlyCheck.details).toMatchObject({ stalls: [{ request_id: dbOnly.request_id, source_id: sources[1]!.id, root: null }] });
+ expect(dbOnlyCheck.message).toContain('root database-only');
+ // A worktree request's completion on the same source is not progress of the database-only root.
+ const worktreeDone = await admitWrite(engine, admission(config, sources[1]!, 'stall/worktree-done', 'worktree body'));
+ await engine.executeRaw(`UPDATE persistence_requests SET state='committed',completed_at=now()-interval '1 minute' WHERE id=$1::uuid`, [worktreeDone.id]);
+ expect((await writeStallCheck(engine)).status).toBe('warn');
+ const dbOnlyDone = await admitWrite(engine, admission(config, sources[1]!, 'stall/db-only-done', 'db-only done body'));
+ await engine.executeRaw(`UPDATE persistence_requests SET state='committed',worktree_id=NULL,completed_at=now()-interval '1 minute' WHERE id=$1::uuid`, [dbOnlyDone.id]);
+ expect((await writeStallCheck(engine)).status).toBe('ok');
+ await engine.executeRaw('DELETE FROM persistence_requests WHERE id=ANY($1::uuid[])', [[dbOnly.id, worktreeDone.id, dbOnlyDone.id]]);
+
// An owner that predates phase recording never stamps its claim: the request's own age stands in for the claim's.
const legacy = await admitWrite(engine, admission(config, sources[1]!, 'stall/legacy', 'legacy body'));
await engine.executeRaw(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,claim_expires_at=now()+interval '30 seconds',