Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(persistence): preparation_stalled in the registry and write-error allowlist; writer status and doctor name the step, wait cause, owner and the preparation_overdue verdict (#6278)

garrytan068b04ae12b8
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index af5b089d84..077bb3a08e 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1890,6 +1890,14 @@ Reasons: `timeout`, `live_serve`.
More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)
+### preparation_stalled
+
+<a id="preparation_stalled"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A managed write's preparation was cut off at its deadline persistence.max_preparation_attempts times (default 2), so the owner finished it failed instead of claiming it again. | One request whose preparation never finished used to hold its root for as long as its owner renewed the claim; now each attempt has a budget, a cut-off attempt is counted (a kill mid-preparation included), and at the limit the request is terminal so the rest of the root keeps moving. A sync holds that file with the same code; the receipt names the last recorded step and what it was waiting on. | Inspect the owner with gbrain sources writer status --source <id> --json (the step and its wait cause), fix or report the cause, then gbrain sources retry-held <id> and the same gbrain sync with the same options; a foreground write needs a new request_id. Run: gbrain sources status '{source_id}' --json | host_admin | `gbrain doctor --json` | 1 | no |
+
### preview_changed
<a id="preview_changed"></a>
diff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.ts
index b25f856200..d95ff12cb5 100644
--- a/src/commands/doctor/checks/persistence-requests.ts
+++ b/src/commands/doctor/checks/persistence-requests.ts
@@ -2,7 +2,9 @@ import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { readRequestIndexStates, REQUEST_INDEXES_REPAIR_COMMAND } from '../../../core/persistence/checkpoint-validation.ts';
import { oneYearCapacity, readJournalLimits, journalLimitKey } from '../../../core/persistence/limits.ts';
-import { claimStateOf, MAX_CLAIM_CONFIG_KEY, readMaxClaimMs } from '../../../core/persistence/claim-phase.ts';
+import { claimStall, claimStateOf, MAX_CLAIM_CONFIG_KEY, readMaxClaimMs } from '../../../core/persistence/claim-phase.ts';
+import { preparationBudgetMs } from '../../../core/persistence/preparation-budget.ts';
+import { readPreparationPolicy } from '../../../core/persistence/switches.ts';
import { agentFix, checkError } from '../check-fix.ts';
const WINDOW_DAYS = 7;
@@ -106,14 +108,18 @@ export async function requestGrowthCheck(engine: BrainEngine): Promise<Check> {
* its root waits behind it. Names the stuck phase (claim-phase.ts), the root,
* the claim's age, how many writes wait behind it and whether the same request
* resumes on its own, with the read-only writer status as the next step.
+ * #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.
*/
export async function writeStallCheck(engine: BrainEngine): Promise<Check> {
const docs = 'docs/guides/troubleshooting.md#persistence-write-stall';
try {
const maxClaimMs = await readMaxClaimMs(engine);
- const rows = await engine.executeRaw<{ request_id: string; source_id: string; worktree_id: string | null; operation: string; state: string; claim_phase: unknown;
+ 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 }>(
- `SELECT r.request_id::text,r.source_id,r.worktree_id::text,r.operation,r.state,r.claim_phase,r.execution_token::text,r.claim_expires_at<now() AS claim_lapsed,
+ `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,
(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`);
@@ -124,10 +130,13 @@ export async function writeStallCheck(engine: BrainEngine): Promise<Check> {
// 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 [];
- return [{ request_id: row.request_id, source_id: row.source_id, root: row.worktree_id, operation: row.operation, phase: claim.phase,
- claim_age_ms: held, phase_age_ms: claim.phase_age_ms, waiting_behind: row.waiting, resumes_on_its_own: claim.resumes_on_its_own, why: claim.why }];
+ 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 }];
});
- const details = { max_claim_ms: maxClaimMs, config_key: MAX_CLAIM_CONFIG_KEY, count: stalls.length, stalls, docs };
+ 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 } };
if (!stalls.length) return { name: 'persistence_write_stall', status: 'ok', details,
message: `No write request has held its claim longer than ${MAX_CLAIM_CONFIG_KEY} (${maxClaimMs} ms).` };
const first = stalls[0]!;
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 7005abaf87..e31e1312a8 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -266,6 +266,11 @@ export const CODES = {
plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },
plan_stale: { class: 'caller', summary: "The saved plan has no valid repository identity." },
port_in_use: { class: 'retryable', summary: "Google connect credential error: port in use.", docs: 'docs/guides/google-connect.md#troubleshooting' },
+ preparation_stalled: { class: 'server', retryable: false, actor: 'host_admin',
+ summary: "A managed write's preparation was cut off at its deadline persistence.max_preparation_attempts times (default 2), so the owner finished it failed instead of claiming it again.",
+ why: "One request whose preparation never finished used to hold its root for as long as its owner renewed the claim; now each attempt has a budget, a cut-off attempt is counted (a kill mid-preparation included), and at the limit the request is terminal so the rest of the root keeps moving. A sync holds that file with the same code; the receipt names the last recorded step and what it was waiting on.",
+ suggestion: 'Inspect the owner with gbrain sources writer status --source <id> --json (the step and its wait cause), fix or report the cause, then gbrain sources retry-held <id> and the same gbrain sync with the same options; a foreground write needs a new request_id.',
+ fix: { argv: ['gbrain', 'sources', 'status', '{source_id}', '--json'], consent: [], actor: 'host_admin', why: 'Read-only: lists the held files of the source with their repair route.', requires_exclusive: false } },
preview_changed: { class: 'caller', summary: "The state changed since the approved preview." },
profile_incompatible: { class: 'caller', summary: "The stored profile is incompatible with this operation." },
projection_owner_resident: { class: 'host_only', summary: "A resident owner holds the projection." },
diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.ts
index 493181f8f9..d94fdc0cab 100644
--- a/src/core/persistence/diagnostics.ts
+++ b/src/core/persistence/diagnostics.ts
@@ -4,8 +4,10 @@ import type { JournalLimits } from './model.ts';
import { publicationConcurrency } from './pool-capacity.ts';
import { WRITER_INSPECTION_HINT } from './admin-intent.ts';
import { writeHealth } from './health.ts';
-import { claimStateOf, type ClaimRow } from './claim-phase.ts';
+import { claimStall, claimStateOf, type ClaimRow } from './claim-phase.ts';
import type { WriteRequestState } from './types.ts';
+import { preparationBudgetMs } from './preparation-budget.ts';
+import { readWriteSwitchSnapshot } from './switches.ts';
import { DATABASE_REFUSAL_HINT, DATABASE_TRIGGER_HINT } from './connector-errors.ts';
export const WRITER_NEXT_ACTIONS: Record<string, string> = {
@@ -26,6 +28,9 @@ export const WRITER_NEXT_ACTIONS: Record<string, string> = {
source_changed: 'Inspect the source incarnation and worktree binding; queued requests cannot follow a recreated source.',
permission_denied: 'Inspect the durable principal and current source, operation, and namespace grants.',
writer_coordinator_required: DATABASE_REFUSAL_HINT,
+ // #6278: a preparation the budget cut off, and the terminal give-up at the attempt limit.
+ preparation_deadline: 'Keep the same request_id: the owner cut this preparation off at its budget and will claim it again; a second cut-off finishes it preparation_stalled. Read claim.stall on the running blocker for the step and what it waited on.',
+ preparation_stalled: 'Do not resubmit under the same request_id. The receipt names the last recorded step; for a sync file run gbrain sources retry-held <source> after the cause is fixed, then the same gbrain sync with the same options; a foreground write needs a new request_id.',
};
export function writerNextAction(reason: string | null | undefined): string {
return reason && WRITER_NEXT_ACTIONS[reason] || 'Inspect the sanitized receipt and owner diagnostics before retrying with the same request_id.';
@@ -63,9 +68,11 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
FROM persistence_worktrees w LEFT JOIN persistence_requests r ON r.worktree_id=w.id
GROUP BY w.id ORDER BY w.id`);
const counters = await engine.executeRaw<Counter>(`SELECT key,outstanding_count::text,intent_bytes::text,lifetime_ids::text,terminal_bytes::text,recovery_bytes::text FROM persistence_counters ORDER BY key`);
- const blockers = await engine.executeRaw<{ request_id: string; worktree_id: string | null; state: WriteRequestState; created_at: Date | string; blocked_reason: string | null; error_code: string | null }
- & Omit<ClaimRow, 'state'>>(
- `SELECT request_id,worktree_id,state,blocked_reason,error_code,created_at,claim_phase,execution_token,claim_expires_at<now() AS claim_lapsed,publication_started
+ // #6278: the operation and intent kind say which budget applies and tell a sync member from a maintenance write; the owner process comes from the live claim's stamp.
+ const blockers = await engine.executeRaw<{ request_id: string; worktree_id: string | null; state: WriteRequestState; created_at: Date | string; blocked_reason: string | null; error_code: string | null;
+ operation: string; intent_kind: string | null; preparation_attempts: number | null } & Omit<ClaimRow, 'state'>>(
+ `SELECT request_id,worktree_id,state,blocked_reason,error_code,created_at,claim_phase,execution_token,claim_expires_at<now() AS claim_lapsed,publication_started,
+ operation,intent->>'kind' AS intent_kind,preparation_attempts
FROM persistence_requests WHERE state IN ('queued','running','recovering') OR blocked_reason IS NOT NULL ORDER BY sequence LIMIT 100`);
const queue = await engine.executeRaw(`SELECT state,COUNT(*)::integer AS count,COALESCE(SUM(intent_bytes),0)::text AS intent_bytes,
MIN(created_at) AS oldest_request_at,
@@ -80,6 +87,10 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
`SELECT request_id,operation,source_id,state,error_code,error_detail,completed_at FROM persistence_requests
WHERE error_detail IS NOT NULL AND COALESCE(error_detail->>'origin','')<>'fence' ORDER BY sequence DESC LIMIT 20`);
const limits = await readJournalLimits(engine);
+ // #6278: the budgets, ceiling, attempt limit and switch in effect, next to every running blocker's step age.
+ const snapshot = await readWriteSwitchSnapshot(engine).catch(() => null);
+ const preparation_policy = snapshot ? { deadlines: snapshot.switches.preparation_deadlines, sync_preparation_ms: snapshot.preparation.syncMs,
+ maintenance_preparation_ms: snapshot.preparation.maintenanceMs, preparation_ceiling_ms: snapshot.preparation.ceilingMs, max_preparation_attempts: snapshot.preparation.maxAttempts } : null;
const { persistenceConsumerStatus } = await import('./service.ts');
// C-NEW-4: the consumer is per process, so this is the answering process's own ingress, never proof the brain's owner is down.
const local = persistenceConsumerStatus(engine);
@@ -87,14 +98,18 @@ export async function readWriterDiagnostics(engine: BrainEngine) {
? 'The process that answered has no resident consumer (a one-shot CLI, for example); another process may own writes. See worktrees and bindings for ownership.'
: 'The resident consumer of the process that answered this status.' };
return { ...brain, sampled_at: new Date().toISOString(), publication_concurrency: publicationConcurrency(engine),
- local_process_ingress, worktrees, counters, queue, effects, limits, capacity: capacityDiagnostics(counters, limits),
+ local_process_ingress, worktrees, counters, queue, effects, limits, capacity: capacityDiagnostics(counters, limits), preparation_policy,
recent_failures: failures.map(row => ({ ...row, next_action: row.error_detail?.origin === 'database_guard' ? DATABASE_REFUSAL_HINT : DATABASE_TRIGGER_HINT })),
blockers: blockers.map(({ claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started, ...row }) => {
const health = writeHealth(row);
const advice = writerNextAction(row.blocked_reason ?? row.error_code);
- // #6176: a running request names the phase its claim is in and how long it has held it.
- const claim = claimStateOf({ state: row.state, claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started });
- return { ...row, ...health, ...(claim ? { claim } : {}), next_action: health.diagnostic?.next_action === 'inspect_owner' && advice !== WRITER_INSPECTION_HINT
+ // #6176: a running request names the phase its claim is in and how long it has held it; #6278: its step, wait cause, owner
+ // process and, past its budget, the `preparation_overdue` verdict (the running state; `preparation_stalled` is only the terminal give-up).
+ const state = claimStateOf({ state: row.state, claim_phase: _phase, execution_token: _token, claim_lapsed: _lapsed, publication_started: _started });
+ const budget = snapshot ? preparationBudgetMs({ operation: row.operation, intent: row.intent_kind ? { kind: row.intent_kind } : null }, snapshot.preparation, 30_000) : null;
+ const stall = state && budget !== null ? claimStall(state, budget) : null;
+ const claim = state ? { ...state, ...(budget === null ? {} : { budget_ms: budget }), stall } : undefined;
+ return { ...row, preparation_attempts: row.preparation_attempts ?? 0, ...health, ...(claim ? { claim } : {}), next_action: health.diagnostic?.next_action === 'inspect_owner' && advice !== WRITER_INSPECTION_HINT
? `${WRITER_INSPECTION_HINT} ${advice}` : advice };
}) };
}
diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.ts
index 7378d7435b..9de644e4dd 100644
--- a/src/core/persistence/types.ts
+++ b/src/core/persistence/types.ts
@@ -18,7 +18,7 @@ export const WRITE_ERROR_CODES = [
'connector_account_changed', 'connector_intent_outdated', 'checkpoint_validation_timeout',
'invalid_connector_text', 'connector_holds_exhausted', 'connector_fence_below_timeline',
'core_budget_exceeded', 'core_mark_owner_only', 'core_remote_edit_refused', 'core_delete_owner_only',
- 'timeline_rows_would_be_removed',
+ 'timeline_rows_would_be_removed', 'preparation_stalled',
] as const;
export type WriteErrorCode = typeof WRITE_ERROR_CODES[number];
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index fb6d78f5a9..c9fb5f91bf 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -743,6 +743,12 @@
"count": 0,
"docs": "docs/guides/troubleshooting.md#persistence-write-stall",
"max_claim_ms": "<volatile>",
+ "preparation_policy": {
+ "maintenance_preparation_ms": "<volatile>",
+ "max_preparation_attempts": 2,
+ "preparation_ceiling_ms": "<volatile>",
+ "sync_preparation_ms": "<volatile>"
+ },
"stalls": []
},
"message": "No write request has held its claim longer than persistence.max_claim_ms (600000 ms).",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 1530d5fcbe..9a3a4f9b6c 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -831,6 +831,12 @@
"count": 0,
"docs": "docs/guides/troubleshooting.md#persistence-write-stall",
"max_claim_ms": "<volatile>",
+ "preparation_policy": {
+ "maintenance_preparation_ms": "<volatile>",
+ "max_preparation_attempts": 2,
+ "preparation_ceiling_ms": "<volatile>",
+ "sync_preparation_ms": "<volatile>"
+ },
"stalls": []
},
"message": "No write request has held its claim longer than persistence.max_claim_ms (600000 ms).",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index fadc6348be..210f063736 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -820,6 +820,12 @@
"count": 0,
"docs": "docs/guides/troubleshooting.md#persistence-write-stall",
"max_claim_ms": "<volatile>",
+ "preparation_policy": {
+ "maintenance_preparation_ms": "<volatile>",
+ "max_preparation_attempts": 2,
+ "preparation_ceiling_ms": "<volatile>",
+ "sync_preparation_ms": "<volatile>"
+ },
"stalls": []
},
"message": "No write request has held its claim longer than persistence.max_claim_ms (600000 ms).",
diff --git a/test/persistence-preparation-kill-accounting.test.ts b/test/persistence-preparation-kill-accounting.test.ts
index b775f298b5..8e97ec99a7 100644
--- a/test/persistence-preparation-kill-accounting.test.ts
+++ b/test/persistence-preparation-kill-accounting.test.ts
@@ -14,6 +14,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { admitWrite, claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
import { releaseAbandonedClaims } from '../src/core/persistence/effect-journal.ts';
import { claimPhaseStamp, startClaimPhase } from '../src/core/persistence/claim-phase.ts';
import { admission, fixtures, initializeFixtures, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';
@@ -38,7 +39,7 @@ test('the PGLite reclaim charges a preparing claim of the reclaimed token only,
const sources = await fixtures(engine, config);
// Three roots, one claimed request each: claimed (stamped preparing at claim), publishing, and an earlier claim's stamp.
const rows = await Promise.all(sources.map((source, i) => admitWrite(engine, admission(config, source, `kill/${i}`, `body ${i}`))));
- const claimed = [];
+ const claimed: WriteRequest[] = [];
for (let i = 0; i < 3; i++) claimed.push((await claimNextWrite(engine, config.hostId, 30_000, claimed.map(row => row.worktree_id!)))!);
expect(claimed.map(row => row.slug).sort()).toEqual(rows.map(row => row.slug).sort());
const byIndex = (i: number) => claimed.find(row => row.slug === `kill/${i}`)!;
@@ -50,7 +51,7 @@ test('the PGLite reclaim charges a preparing claim of the reclaimed token only,
expect(await releaseAbandonedClaims(engine, future, false)).toBe(3);
for (let i = 0; i < 3; i++) expect(await getWriteRequestById(engine, byIndex(i).id)).toMatchObject({ state: 'queued', preparation_attempts: 0 });
// Claim again (fresh stamps), restore the two control stamps, then reclaim with the switch on.
- const again = [];
+ const again: WriteRequest[] = [];
for (let i = 0; i < 3; i++) again.push((await claimNextWrite(engine, config.hostId, 30_000, again.map(row => row.worktree_id!)))!);
const second = (i: number) => again.find(row => row.slug === `kill/${i}`)!;
await engine.executeRaw('UPDATE persistence_requests SET claim_phase=$2::text::jsonb WHERE id=$1::uuid', [second(1).id, claimPhaseStamp(publishing, second(1).execution_token)]);
diff --git a/test/persistence-writer-status-stall.test.ts b/test/persistence-writer-status-stall.test.ts
new file mode 100644
index 0000000000..cd64953199
--- /dev/null
+++ b/test/persistence-writer-status-stall.test.ts
@@ -0,0 +1,109 @@
+/**
+ * #6278: writer status and doctor on a preparation past its budget. Protects:
+ * a running blocker carries operation, intent_kind, preparation_attempts, the
+ * claim's step, step age, waiting_on and owner process (kind, pid, build) from
+ * the live stamp, the budget that applies to its kind, and, once the step is
+ * older than that budget, `claim.stall { reason: 'preparation_overdue', ... }`;
+ * writer status also reports the budgets, ceiling, limit and switch in effect;
+ * `WRITER_NEXT_ACTIONS` has non-circular advice for `preparation_deadline` and
+ * `preparation_stalled`; doctor `persistence_write_stall` prints the same
+ * claim fields. Nothing here extends the wire enum (`WRITE_HEALTH_REASONS`).
+ * Fails when the blocker reads `cause_unknown` without a step, when the stall
+ * verdict fires for a publishing claim, or when the owner is inferred rather
+ * than read from the stamp. PGLite only: the fields come from the stamp, not
+ * the engine.
+ */
+import { afterAll, beforeAll, expect, setSystemTime, 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 { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PersistenceConsumer } from '../src/core/persistence/consumer.ts';
+import { admitWrite } from '../src/core/persistence/journal.ts';
+import { readWriterDiagnostics, WRITER_NEXT_ACTIONS } from '../src/core/persistence/diagnostics.ts';
+import { enterClaimStep, setClaimOwnerForTest } from '../src/core/persistence/claim-phase.ts';
+import { WRITE_HEALTH_REASONS } from '../src/core/persistence/types.ts';
+import { resetWriteSwitches } from '../src/core/persistence/switches.ts';
+import { writeStallCheck } from '../src/commands/doctor/checks/persistence-requests.ts';
+import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, type HarnessConfig } from '../scripts/persistence/harness.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { waitFor } from './helpers/wait-for.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-writer-status-stall-'));
+const config: HarnessConfig = { kind: 'pglite', root: home, dataDir: join(home, 'data'), hostId: randomUUID(),
+ seed: 6278, schedules: 0, operations: 0, sourceIds: ['status-stall'], principalIds: [randomUUID()] };
+const env = { GBRAIN_HOME: home, GBRAIN_PERSISTENCE_FIXTURE_HOME: home };
+let engine: PGLiteEngine;
+
+beforeAll(async () => withEnv(env, async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ selectFixtureHost(config.hostId);
+ await initializeFixtures(engine, config);
+}), 120_000);
+afterAll(async () => { setSystemTime(); setClaimOwnerForTest(undefined); resetWriteSwitches(); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });
+
+test('the wire enum is unchanged: the overdue verdict lives on claim.stall, not on diagnostic.reason', () => {
+ expect(WRITE_HEALTH_REASONS).not.toContain('preparation_overdue');
+ expect(WRITE_HEALTH_REASONS).not.toContain('preparation_stalled');
+ expect(WRITER_NEXT_ACTIONS.preparation_deadline).toContain('claim.stall');
+ expect(WRITER_NEXT_ACTIONS.preparation_stalled).toContain('retry-held');
+ expect(WRITER_NEXT_ACTIONS.preparation_stalled).not.toContain('writer status --json');
+});
+
+test('a preparing blocker names its step, wait cause, owner and budget, and turns preparation_overdue once the step outlives the budget', async () => withEnv(env, async () => {
+ setClaimOwnerForTest({ kind: 'sync', pid: 4242, version: '0.60.200.0' });
+ await engine.setConfig('persistence.maintenance_preparation_ms', '90000');
+ resetWriteSwitches();
+ const sources = await fixtures(engine, config);
+ // A maintenance-kind request (intent kind set) takes the maintenance budget.
+ const row = await admitWrite(engine, admission(config, sources[0]!, 'status/stuck', 'stuck body', 0, { intent: { content: 'stuck body', kind: 'managed_maintenance_page' } }));
+ const hang = Promise.withResolvers<void>();
+ const consumer = new PersistenceConsumer(engine, { engine: 'pglite' }, async (_engine, current, _config, _signal, clock) => {
+ enterClaimStep(clock, 'adoption_read_facts', undefined, 'db');
+ await hang.promise;
+ return prepared(current, sources);
+ }, { hostId: config.hostId, concurrency: 1, pollMs: 20, renewalIntervalMs: 20, phaseMs: 2_000, claimLeaseMs: 86_400_000,
+ preparationBudgets: { maintenanceMs: 90_000, ceilingMs: 3_600_000, maxAttempts: 5 }, onError: () => {} });
+ try {
+ consumer.start();
+ await waitFor(async () => (await engine.executeRaw<{ step: string | null }>("SELECT claim_phase->>'step' AS step FROM persistence_requests WHERE id=$1::uuid", [row.id]))[0]?.step === 'adoption_read_facts',
+ { timeoutMs: 15_000, label: 'the renewal records the step' });
+ const status = await readWriterDiagnostics(engine);
+ expect(status.preparation_policy).toEqual({ deadlines: true, sync_preparation_ms: 120_000, maintenance_preparation_ms: 90_000, preparation_ceiling_ms: 600_000, max_preparation_attempts: 2 });
+ const blocker = status.blockers.find(b => b.request_id === row.request_id)!;
+ expect(blocker).toMatchObject({ operation: 'put_page', intent_kind: 'managed_maintenance_page', preparation_attempts: 0, state: 'running' });
+ expect(blocker.claim).toMatchObject({ phase: 'preparing', step: 'adoption_read_facts', waiting_on: 'db', owner: { kind: 'sync', pid: 4242, version: '0.60.200.0' }, budget_ms: 90_000, stall: null });
+ expect(blocker.claim?.step_age_ms).toBeGreaterThanOrEqual(0);
+ expect(blocker).not.toHaveProperty('execution_token');
+ // The step outlives the budget: the verdict appears on the claim; the wire diagnostic is untouched.
+ const live = async () => (await engine.executeRaw<{ live: boolean }>('SELECT claim_expires_at>now() AS live FROM persistence_requests WHERE id=$1::uuid', [row.id]))[0]?.live === true;
+ setSystemTime(new Date(Date.now() + 2 * 60_000));
+ try {
+ await waitFor(live, { timeoutMs: 10_000, label: 'a renewal under the shifted clock' });
+ const overdue = (await readWriterDiagnostics(engine)).blockers.find(b => b.request_id === row.request_id)!;
+ expect(overdue.claim?.stall).toEqual({ reason: 'preparation_overdue', step: 'adoption_read_facts', step_age_ms: expect.any(Number), waiting_on: 'db', budget_ms: 90_000 });
+ expect(overdue.claim!.stall!.step_age_ms).toBeGreaterThanOrEqual(90_000);
+ expect((WRITE_HEALTH_REASONS as readonly string[]).includes(overdue.diagnostic!.reason)).toBe(true);
+ // Doctor: below max_claim_ms nothing warns; the stall fields ride along once it does.
+ expect((await writeStallCheck(engine)).status).toBe('ok');
+ } finally { setSystemTime(); }
+ setSystemTime(new Date(Date.now() + 11 * 60_000));
+ try {
+ await waitFor(live, { timeoutMs: 10_000, label: 'a renewal under the shifted clock' });
+ const check = await writeStallCheck(engine);
+ expect(check.status).toBe('warn');
+ expect(check.details).toMatchObject({ preparation_policy: { maintenance_preparation_ms: 90_000, max_preparation_attempts: 2 },
+ stalls: [{ request_id: row.request_id, phase: 'preparing', step: 'adoption_read_facts', waiting_on: 'db', owner: { kind: 'sync', pid: 4242 }, budget_ms: 90_000,
+ stall: { reason: 'preparation_overdue', step: 'adoption_read_facts', waiting_on: 'db', budget_ms: 90_000 } }] });
+ expect(check.message).toContain('step adoption_read_facts, waiting on db');
+ } finally { setSystemTime(); }
+ } finally {
+ hang.resolve();
+ await consumer.stop();
+ await engine.executeRaw("DELETE FROM config WHERE key='persistence.maintenance_preparation_ms'");
+ resetWriteSwitches();
+ }
+}), 60_000);