Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): a request parked recovering with its record is an active blocker; fence headroom pre-pass only on refusal (#6650)

garrytanfdef50b29488
diff --git a/src/core/facts/unfenced-facts.ts b/src/core/facts/unfenced-facts.ts
index b6af635f62..4572b89cd2 100644
--- a/src/core/facts/unfenced-facts.ts
+++ b/src/core/facts/unfenced-facts.ts
@@ -63,6 +63,7 @@ import { assertSourceFilesystemActive, hasSourceFilesystemLock, withSourceFilesy
import { withPageLock } from '../page-lock.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { assertLifetimeIdHeadroom } from '../persistence/journal.ts';
+import { OperationError } from '../ops/contract.ts';
import { managedPersistenceEnabled } from '../persistence/ownership.ts';
import { maintenancePreflight, planFactFenceAdoption, submitPlannedFactFenceAdoption, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
import { contentHash } from '../utils.ts';
@@ -414,12 +415,14 @@ async function fenceManaged(engine: BrainEngine, plan: UnfencedFactsPlan): Promi
if (!authorities.has(sourceId)) authorities.set(sourceId, (await maintenancePreflight(engine, sourceId))!);
}
// One admission per page that will submit: refuse up front, before any page publishes, when the permanent
- // request-ID caps cannot cover them. A read-only pre-pass counts them, so a page that is suppressed (an
- // identical adoption was refused within the day), unadoptable or gone never pushes the step over the cap.
+ // request-ID caps cannot cover them. Every page fitting is the common case and costs one read; only when it
+ // would refuse does a read-only pre-pass count the pages that will actually submit, so a page that is suppressed
+ // (an identical adoption was refused within the day), unadoptable or gone never pushes the step over the cap.
// The submit loop below plans each page again right before it submits, so the plan it publishes is never
// older than its own read (the facts-changed-since-planning guard keeps its short window).
const [first] = authorities.values();
- if (first) {
+ if (first) await assertLifetimeIdHeadroom(engine, first.writer.principal, groups.size).catch(async (error: unknown) => {
+ if (!(error instanceof OperationError) || error.code !== 'queue_capacity') throw error;
let submitting = 0;
for (const [key, group] of groups) {
const [sourceId, entitySlug] = key.split('\0');
@@ -427,7 +430,7 @@ async function fenceManaged(engine: BrainEngine, plan: UnfencedFactsPlan): Promi
catch { submitting++; }
}
await assertLifetimeIdHeadroom(engine, first.writer.principal, submitting);
- }
+ });
for (const [key, group] of groups) {
const [sourceId, entitySlug] = key.split('\0');
try {
diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.ts
index 8b49cfcdc8..ec067ebc53 100644
--- a/src/core/ops/persistence.ts
+++ b/src/core/ops/persistence.ts
@@ -138,9 +138,9 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: W
};
}
-/** A receipt the terminal classifier reads: ended without committing, or still holding a publication recovery record. */
+/** A receipt the terminal classifier reads: ended without committing, or holding a publication recovery record outside an in-flight claim (committed or parked `recovering`). */
function isTerminalOrRecovering(row: WriteRequest): boolean {
- return ['failed', 'conflict', 'cancelled'].includes(row.state) || (row.state === 'committed' && row.recovery != null);
+ return ['failed', 'conflict', 'cancelled'].includes(row.state) || ((row.state === 'committed' || row.state === 'recovering') && row.recovery != null);
}
function requiredRequestId(value: unknown): string {
diff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.ts
index 6b4650926a..df8012d02b 100644
--- a/src/core/persistence/terminal-failures.ts
+++ b/src/core/persistence/terminal-failures.ts
@@ -77,7 +77,8 @@ const HISTORICAL_BY_BUILD = (b: string) => `COALESCE(${Object.values(TERMINAL_HI
const BUILD = (r: string) => `COALESCE(${r}.error_detail->'attempt'->>'consumer_version', ${r}.admitter_version)`;
const ENDED = (r: string) => `COALESCE(${r}.completed_at, ${r}.updated_at)`;
const TERMINAL = (r: string) => `${r}.state IN ('failed','conflict','cancelled')`;
-const RECOVERY = (r: string) => `(${r}.recovery IS NOT NULL AND ${r}.state IN ('committed','failed','conflict','cancelled'))`;
+/** A request holding a publication recovery record outside an in-flight claim: it blocks its root. `recovering` is the durable parked state (a blocked restore). */
+const RECOVERY = (r: string) => `(${r}.recovery IS NOT NULL AND ${r}.state IN ('committed','recovering','failed','conflict','cancelled'))`;
interface KeyColumns { source_id: string; state: string; error_code: string | null; origin: string | null; reason: string | null; cause: string | null; operation: string;
has_recovery: boolean; blocked_reason: string | null; compacted: boolean; knock_on: boolean; routed_message: string | null; build: string | null }
@@ -123,7 +124,7 @@ export async function readTerminalFailureSummary(engine: BrainEngine, opts: { so
checkpointBlockers?: Map<string, Array<{ request_id: string; slug: string; knock_on: boolean; recovery: boolean }>> } = {}): Promise<TerminalSummary> {
const t = opts.thresholds ?? await readTerminalThresholds(engine);
const span = Math.max(t.windowDays, 8);
- const days = Array.from({ length: 7 }, (_, i) => `count(*) FILTER (WHERE state<>'committed' AND ended_at <= now()-interval '${i + 1} day' AND ended_at > now()-interval '${i + 2} day')::int AS d${i + 2}`).join(',\n ');
+ const days = Array.from({ length: 7 }, (_, i) => `count(*) FILTER (WHERE state IN ('failed','conflict','cancelled') AND ended_at <= now()-interval '${i + 1} day' AND ended_at > now()-interval '${i + 2} day')::int AS d${i + 2}`).join(',\n ');
const rows = await bounded<KeyColumns & { set: number; resolved: boolean | null; rows: number; in_window: number; n_24h: number; oldest: string | null; oldest_age: number | null;
distinct_slugs: number; distinct_intents: number; recovery_ids: string[] | null; recovery_slugs: string[] | null } & Record<string, number>>(engine,
`WITH base AS (
@@ -142,7 +143,7 @@ export async function readTerminalFailureSummary(engine: BrainEngine, opts: { so
)
SELECT GROUPING(state) AS set, source_id, state, error_code, origin, reason, cause, operation, has_recovery, blocked_reason, compacted, knock_on, routed_message, build, resolved,
count(*) FILTER (WHERE in_window)::int AS rows, count(*) FILTER (WHERE in_window)::int AS in_window,
- count(*) FILTER (WHERE state<>'committed' AND ended_at > now()-interval '1 day')::int AS n_24h,
+ count(*) FILTER (WHERE state IN ('failed','conflict','cancelled') AND ended_at > now()-interval '1 day')::int AS n_24h,
${days},
to_char(min(ended_at) FILTER (WHERE in_window) AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS oldest,
floor(EXTRACT(EPOCH FROM now()-min(ended_at) FILTER (WHERE in_window)))::bigint AS oldest_age,
diff --git a/test/terminal-failures-6650.test.ts b/test/terminal-failures-6650.test.ts
index 9d6a0c1afb..7faa0b52b0 100644
--- a/test/terminal-failures-6650.test.ts
+++ b/test/terminal-failures-6650.test.ts
@@ -185,6 +185,25 @@ for (const kind of testBackends()) describe(`the aggregate, doctor and the drill
expect(validateTerminalConfigValue('persistence.terminal_failures.spike_factor', '2.5')).toBeNull();
});
+ test('a request parked recovering with its record (a blocked restore) is an active blocker everywhere, never a 24 h failure', async () => {
+ const parked = await seed({ slug: 'notes/parked', state: 'recovering', code: 'storage_error', detail: { origin: 'owner_exception' },
+ recovery: { version: 1, path: '/nonexistent/p.md', root: '/nonexistent', beforeHash: null, afterHash: 'a' }, blocked: 'unexpected_file_bytes' });
+ await seed({ slug: 'notes/flight', state: 'running', recovery: { version: 1, path: '/nonexistent/f.md', root: '/nonexistent', beforeHash: null, afterHash: 'b' } });
+ const summary = await readTerminalFailureSummary(engine);
+ if (summary.status !== 'ok') throw new Error('unknown');
+ const s = summary.sources.find(x => x.source_id === SOURCE)!;
+ // An in-flight claim's record is publication in progress, not a blocker.
+ expect(s.active_blockers).toEqual([expect.objectContaining({ kind: 'recovery', request_id: parked, slug: 'notes/parked', category: 'recovery_blocked', needs_human: true })]);
+ expect(s.new_last_24h).toBe(0);
+ expect(s.unresolved.rows).toBe(0);
+ const check = (await terminalFailuresCheck(engine))!;
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain(`recovery record ${parked} (notes/parked)`);
+ const listing = await readTerminalFailures(engine, { sourceId: SOURCE });
+ if (listing.status !== 'ok') throw new Error('unknown');
+ expect(listing.rows!.map(r => [r.request_id, r.blocking, r.category])).toEqual([[parked, true, 'recovery_blocked']]);
+ });
+
test('a spike an older write owner drives says so and names its build, instead of reading as a new defect', async () => {
await engine.setConfig('persistence.terminal_failures.spike_min', '3');
for (let i = 0; i < 4; i++) await seed({ slug: `notes/k${i}`, operation: 'submit_job', state: 'cancelled', code: 'cancelled', detail: knockOnDetail('window_predecessor', null), build: '0.60.200.0', hoursAgo: 1 });
diff --git a/test/write-request-diagnosis-6650.test.ts b/test/write-request-diagnosis-6650.test.ts
index f57b795f6d..8db98209b2 100644
--- a/test/write-request-diagnosis-6650.test.ts
+++ b/test/write-request-diagnosis-6650.test.ts
@@ -61,6 +61,22 @@ test('a compacted storage_error with no recorded origin is diagnosis_required, w
expect(receipt.diagnosis.human_reason).toContain('does not record enough to name a fix');
});
+test('a receipt parked recovering with its record is diagnosed as the blocked recovery it is', async () => {
+ const requestId = randomUUID();
+ await withVerifiedLocalRegistration(engine, owner, async () => {
+ const [s] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [SOURCE]);
+ const authority = await submissionAuthority(context(), 'put_page', SOURCE, s.incarnation, 'notes/parked');
+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: SOURCE, sourceIncarnation: s.incarnation, slug: 'notes/parked', requestId,
+ callerIntent: { content: 'z' }, intent: { content: 'z' } });
+ });
+ await engine.executeRaw(`UPDATE persistence_requests SET state='recovering', blocked_reason='unexpected_file_bytes',
+ recovery='{"version":1,"path":"/nonexistent/p.md","root":"/nonexistent","beforeHash":null,"afterHash":"a"}'::jsonb WHERE request_id=$1::uuid`, [requestId]);
+ const op = operations.find(operation => operation.name === 'get_write_request')!;
+ const receipt = await withVerifiedLocalRegistration(engine, owner, () => op.handler(context(), { request_id: requestId })) as Record<string, any>;
+ expect(receipt.diagnosis).toMatchObject({ category: 'recovery_blocked', needs_human: true });
+ expect(receipt.diagnosis.fix.argv.slice(0, 4)).toEqual(['gbrain', 'sources', 'writer', 'status']);
+});
+
test('a committed receipt carries no diagnosis', async () => {
const requestId = randomUUID();
await withVerifiedLocalRegistration(engine, owner, async () => {