Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(atoms): explicit managed atom retry honors cancel, deadline and lock loss (#6622)

time-attack6dc9bbeef6d1
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 71c4df7a62..2f24bd8fbf 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -16,7 +16,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/{admin-lock,blocking-effects,writer-versions}.ts` — `admin-lock.ts` owns the opt-in brain-level writer admin lock: reserved config key `persistence.writer_admin_lock` (`{locked, set_at, host_id, generation}`), written only by local `gbrain sources writer lock|unlock` under the `persistence_brain` row `FOR UPDATE`; lock refuses while a prepared transfer is unaccepted. `assertWriterAdminUnlocked` runs inside the claim, managed claim, activation, shared-skill activation and transfer prepare/accept transactions for every caller (share lock on the brain row) and refuses with `writer_admin_locked`; only the ordinary first-write auto-claim (`claimWorktree(..., { automatic: true })` from page and memory mutations) is exempt. Generic `config set`/`unset`/`unset --pattern` refuse the key; engine migration copies it. It is not a security boundary and older binaries ignore it. `blocking-effects.ts` lists queued, running or recovering effects (`listBlockingEffects`) and builds `writer_not_quiesced` suggestions naming the first blocking request or effect with `gbrain sources writer status <source> --json`. `writer-versions.ts` stamps admitter version/host at admission and consumer version/host/`published_at` only on committed publication (migration 178, cutoff `persistence_brain.writer_version_cutoff` on the database clock); replay and compaction keep stamps. `sources writer status` reports `admin_lock`, `local_host_id`, `blocking_effects` and `writer_versions`; `src/commands/doctor/checks/writer-version.ts` is the seven-day `writer_version` advisory. Tests: `test/persistence-writer-admin-lock.test.ts`, `test/persistence-writer-versions.test.ts`, `test/persistence-blocking-effects.test.ts`, `test/e2e/persistence-writer-{admin-lock,stamps}.test.ts`.
-- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix; a shared-origin delete: canonical-reconciliation.md. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in [Core Persistence (managed facts)](core-persistence-facts.md).
+- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry (`retryManagedAtomBatch` takes the job's signal and deadline, stops between stages on caller cancel, deadline or cycle-lock loss, shares one deadline-bound `MaintenanceWriteWait` with the model rerun, and reports a stop after admission as `write_pending` or an `AbortError` carrying the receipts, never `cancelled`; #6622), authorized multi-entity fact-fence/backstop append, local synthesize/patterns/consolidation, and the cycle's lint repairs on a managed brain (`runLintCore` publishes each fix through `maintenancePreflight` + `publishMaintenancePage`; #5180, `test/managed-lint.test.ts`). `page-prepare.ts` exports `fileMatchesSnapshot`, the canonical file-versus-page comparison `prepareFileTarget` applies, so lint can bind a repair to the revision it read; the uncoordinated-local-edit refusal carries detail `file_database_drift` and a `sources reconcile <src> <slug> --brain host --preview` fix; a shared-origin delete: canonical-reconciliation.md. In `prepareFileTarget`, a live page whose canonical file is missing refuses `source_changed` unless it is declared or derive-phase database-only, or it is a `delete_page` (`deleting`, no content) of a page with no recorded `source_path` and no captured file URI: that delete plans no file, so it publishes database-only and its receipt reports no file or Git effect (`test/persistence-captured-file-target.test.ts`, `test/persistence-never-published-delete.test.ts`). `atomOwnerTarget` is the one owner decision for an atom session and for `atomDrainOwnerRefusal`, the auto-drain dispatch pre-check; an unbound Google/GitHub source publishes atom maintenance through the `connector_database` target (its `local_path` is connector state, not a checkout) and the publication refuses with `source_changed` when the source gained an owner after preflight. `submitMaintenance` scans every content-carrying intent with `scanCanonicalFences` (the check the canonical projection runs) over the whole submitted body and timeline before a request exists (#6278): a defect no adoption clears (a second facts fence in the timeline; `replaceOrInsertFactsFence` replaces only the first) is refused with its fence reason, so `fenceManaged` reports the page in `failed_pages` and the others still adopt, while a repair whose postimage is clean passes. `prepareFactFenceAdoption` names its steps for `enterClaimStep`, compares the fence cell with the legacy fact modulo whitespace, writes the cell's parsed text back into `facts.fact` in the same `UPDATE` that sets `row_num` (so the projection keeps the fact's id), and throws the registered `fence_unrenderable` (class `server`) as its last-line defence. `maintenancePreflight` creates the job's `MaintenanceWriteWait` (optional `deadlineAtMs`) and `submitMaintenance` uses it for new and replayed requests; its owner check goes through `checkOwner` / `ownerUnavailableError` (`owner-refusal.ts`), so a missing binding, a changed incarnation, another owner host, a draining or recovering worktree and a missing local or coordination path each refuse `owner_unavailable` with their own `reason`, and nothing claims or transfers ownership to get past them. #6325: `resumeManagedAtoms` returns `run | done | held`. The drain does not replay a failed batch: it resumes the next automatic attempt, whose run key is `digest([drainKey, failedRequestId, 'automatic'])` (one stable id per failure, so a crashed attempt resumes and two runs admit the same requests), and whose completion advances the failed drain-key checkpoint by the same compare-and-set an explicit retry uses. The completion counts one strike per completed failure on that checkpoint (`attempts`); at `MAX_DETERMINISTIC_FAILURES` it sets `held`, which `MANAGED_ATOM_DISCOVERY_SQL` excludes from discovery and the backlog and `listHeldManagedAtoms` reports (doctor `extract_atoms_held_failed`, code `held_failed`). Reading a held or failed checkpoint never strikes; storage, authority and conflict errors fail the attempt without completing it, so they never strike either. A content change is a new drain key, so the count starts over. An explicit retry (`session.retry`) ignores `held`, and its failure refusal (`extraction_failed`) names the recorded failure reason (malformed output or a response stopped before the end) and carries a paid `fix` (`gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'`) with a read-only `gbrain write-request` verify; the drain raises it only for a failed batch whose checkpoint is gone. Tests: `test/managed-atoms-retry.test.ts`. Managed facts extraction (the withdrawn-candidate skip and its recovery route, the conversation facts batches, the unmanaged derived index) continues in [Core Persistence (managed facts)](core-persistence-facts.md).
- `src/core/persistence/maintenance-wait.ts` — how long a maintenance publisher waits for its accepted write to commit before the receipt reports `write_pending` (#5854). `MAINTENANCE_WRITE_WAIT_MS` is 30 s; `MaintenanceWriteWait` is one budget per job: each wait is capped by the job's remaining deadline (zero at or past it), and once one publish is still pending after its wait (`observe`) every later publish in that job waits zero and is deferred like it. A pending write keeps its request identity and commits later; it is never reported as committed. A `MaintenanceWriteWait` with no deadline also sets the replay window of a subagent tool write whose job has none (`minions/tool-write-identity.ts`). `__setMaintenanceWriteWaitForTests` replaces the base wait, those tool writes included. Tests: `test/maintenance-write-wait.test.ts`, `test/e2e/maintenance-write-wait.test.ts`.
Atom completion admits replacement and revision-pinned stale-atom deletion children together.
Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index b62bee1d4d..c7f7e6b1a2 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -246,6 +246,7 @@ test/link-reads-thin-client-5827.serial.test.ts R2 R2: mock.module(../src/core/c
test/llm-intent-hybrid-integration.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests; configureGateway changes the process-wide AI gateway
test/loops-close-fact.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/console
test/loops-extract-run.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the process
+test/managed-atom-retry-cancellation.serial.test.ts R2 R2: mock.module replaces atom storage, extraction and cycle-lock modules process-wide
test/managed-connector-routing.serial.test.ts global-state global-state: spyOn globalThis.fetch
test/managed-push-remedy.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
test/managed-unsupported-preflight.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts) replaces modules for every file in the process
diff --git a/src/core/minions/handlers/extract-atoms-drain.ts b/src/core/minions/handlers/extract-atoms-drain.ts
index 04a6bc2a38..868bc38f03 100644
--- a/src/core/minions/handlers/extract-atoms-drain.ts
+++ b/src/core/minions/handlers/extract-atoms-drain.ts
@@ -17,7 +17,8 @@ export function makeExtractAtomsDrainHandler(engine: BrainEngine): MinionHandler
if (job.data.retryRequestId !== undefined) {
if (typeof job.data.retryRequestId !== 'string' || typeof job.data.sourceId !== 'string') throw new Error('Atom retry requires sourceId and retryRequestId strings.');
const { retryManagedAtomBatch } = await import('../../persistence/atom-retry.ts');
- return retryManagedAtomBatch(engine, job.data.sourceId, job.data.retryRequestId, `job:${job.id}`);
+ return retryManagedAtomBatch(engine, job.data.sourceId, job.data.retryRequestId, `job:${job.id}`,
+ { signal: job.signal, deadlineAtMs: job.deadlineAtMs });
}
const { formatDrainProviderFailure, runExtractAtomsDrainForSource, structuralAtomRefusal } =
await import('../../cycle/extract-atoms-drain.ts');
diff --git a/src/core/persistence/atom-retry.ts b/src/core/persistence/atom-retry.ts
index 142bdf3fbc..33d42ac43d 100644
--- a/src/core/persistence/atom-retry.ts
+++ b/src/core/persistence/atom-retry.ts
@@ -4,7 +4,9 @@ import { opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
import { atomRetryInputKey, managedAtomSession, publishManagedAtoms, readAtomOrigin, resumeManagedAtoms, type AtomIntent, type ManagedAtomRetirement } from './atom-maintenance.ts';
-import { isWriteReceipt } from './types.ts';
+import { isWriteReceipt, type WriteReceipt } from './types.ts';
+import { anyAbortSignal } from '../abort-signals.ts';
+import { MaintenanceWriteWait } from './maintenance-wait.ts';
const receiptFix = (requestId: string): Action => readFix('Reads the atom request\'s durable receipt: its state, outcome and error, read-only.',
{ argv: ['gbrain', 'write-request', '--', requestId] });
@@ -15,85 +17,134 @@ const drainFix = (sourceId: string): Action => ({
const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows which page holds ${slug} in source ${sourceId} now, with its revision, read-only.`,
{ argv: ['gbrain', 'get', '--source', sourceId, '--', slug] });
-export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: string, requestId: string, retryId: string): Promise<Record<string, unknown>> {
+/** A stop after a write was admitted reports that write (pending or committed), never `cancelled`. */
+function stoppedRetry(reason: unknown, receipts: WriteReceipt[]): Error {
+ const pending = receipts.find(receipt => ['queued', 'running', 'recovering'].includes(receipt.state));
+ if (pending) {
+ const error = opError('write_pending', 'The atom retry stopped with an admitted write still pending.',
+ `The retry stopped (${reason instanceof Error ? reason.message : String(reason)}) after atom write ${pending.request_id} was admitted; it may still commit. Inspect its receipt and wait for it to settle before approving another attempt.`,
+ { fix: receiptFix(pending.request_id) });
+ error.writeRequest = pending;
+ return Object.assign(error, { write_requests: receipts });
+ }
+ if (!receipts.length && reason instanceof Error) return reason;
+ return Object.assign(new DOMException(reason instanceof Error ? reason.message : String(reason ?? 'Atom retry aborted'), 'AbortError'),
+ { write_requests: receipts });
+}
+
+/**
+ * The minion worker aborts `signal` at the job deadline; `deadlineAtMs` also
+ * bounds the shared write wait and stops the retry at the next stage boundary.
+ */
+export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: string, requestId: string, retryId: string,
+ opts: { signal?: AbortSignal; deadlineAtMs?: number | null } = {}): Promise<Record<string, unknown>> {
+ let receipts: WriteReceipt[] = [];
+ let stop: ReturnType<typeof anyAbortSignal> | undefined;
+ const check = () => {
+ if (opts.deadlineAtMs != null && Date.now() >= opts.deadlineAtMs) throw stoppedRetry(new Error('Atom retry stopped at the job deadline.'), receipts);
+ const signal = stop?.signal ?? opts.signal;
+ if (signal?.aborted) throw stoppedRetry(signal.reason, receipts);
+ };
+ check();
const { withRefreshingLock } = await import('../db-lock.ts');
const { cycleLockIdFor } = await import('../cycle.ts');
- return withRefreshingLock(engine, cycleLockIdFor(sourceId), async () => {
- const session = await managedAtomSession(engine, sourceId, { requestId, retryId });
- if (!session?.retry) throw opError('invalid_params', 'Explicit atom retry requires a managed source.',
- `Source ${sourceId} is not under managed persistence, so retained atom batch ${requestId} cannot be retried there; nothing was started. Run the ordinary atom drain for the source instead (it calls the configured LLM, so confirm the spend).`,
- { fix: drainFix(sourceId) });
- const retry = session.retry;
- const origin = retry.origin;
- const item = origin.kind === 'page'
- ? { kind: 'page' as const, slug: origin.locator, content: (await engine.readPageSnapshot(origin.locator, { sourceId }))?.page.compiled_truth ?? '', contentHash: origin.contentHash }
- : { kind: 'transcript' as const, filePath: origin.locator, content: readFileSync(origin.locator, 'utf8'), contentHash: origin.contentHash };
- const current = await readAtomOrigin(engine, session, item);
- // The retry runs against the current origin (its revision and visibility);
- // only a change to the input the run key covers refuses it.
- if (atomRetryInputKey(session, current) !== atomRetryInputKey(session, origin)) throw opError('source_changed', 'The original atom input changed; this retry cannot reuse it.',
- `The ${origin.kind} that atom request ${requestId} extracted from in source ${sourceId} has changed since, so its retained batch no longer applies; nothing was started. Run a fresh atom drain, which extracts from the current content.`,
- { fix: drainFix(sourceId) });
- if (await resumeManagedAtoms(engine, session, current) === 'done') return { status: 'completed', replayed: true, model_rerun: false };
- const checkpoint = retry.expectedCheckpoint as Array<{ failure?: string }> | null;
- if (checkpoint && !checkpoint[0]?.failure) return { status: 'completed', replayed: true, model_rerun: false };
- const saved = retry.rows.filter(row => row.intent?.kind === 'managed_atom_page');
- const deleted = retry.rows.filter(row => row.intent?.kind === 'managed_atom_delete');
- if (saved.length || deleted.length) {
- const atoms: Parameters<typeof publishManagedAtoms>[3] = [];
- for (const row of saved) {
- const p = row.intent as AtomIntent;
- const target = await engine.readPageSnapshot(row.slug, { sourceId, includeDeleted: true });
- const revision = row.state === 'committed' ? row.outcome?.revision : p.expected_revision ?? null;
- if (typeof revision !== 'string' && (row.state === 'committed' || revision !== null)) throw opError('storage_error', 'The retained atom publication revision is unavailable.',
- `The receipt of atom page ${row.slug} (request ${row.request_id}) no longer records the revision it published against, so the retry cannot republish it; nothing was published. Read the batch's receipt, then run a fresh atom drain for source ${sourceId}.`,
- { fix: receiptFix(requestId) });
- const pageId = row.state === 'committed' ? row.page_id ?? target?.page.id ?? null : row.page_id;
- if ((target?.page.id ?? null) !== pageId || (target?.revision ?? null) !== revision) {
- throw opError('page_identity_changed', 'An atom target changed independently of the failed publication.',
- `Atom page ${row.slug} in source ${sourceId} was edited, created, deleted or replaced after request ${requestId} failed, so republishing would overwrite that change; nothing was published. Read the page, then run a fresh atom drain if its atoms still need extracting.`,
- { fix: pageFix(sourceId, row.slug) });
+ try {
+ return await withRefreshingLock(engine, cycleLockIdFor(sourceId), async lockSignal => {
+ stop = anyAbortSignal(opts.signal ? [opts.signal, lockSignal] : [lockSignal]);
+ check();
+ const wait = new MaintenanceWriteWait(opts.deadlineAtMs ?? null);
+ const session = await managedAtomSession(engine, sourceId, { requestId, retryId }, wait);
+ check();
+ if (!session?.retry) throw opError('invalid_params', 'Explicit atom retry requires a managed source.',
+ `Source ${sourceId} is not under managed persistence, so retained atom batch ${requestId} cannot be retried there; nothing was started. Run the ordinary atom drain for the source instead (it calls the configured LLM, so confirm the spend).`,
+ { fix: drainFix(sourceId) });
+ const retry = session.retry;
+ const origin = retry.origin;
+ const item = origin.kind === 'page'
+ ? { kind: 'page' as const, slug: origin.locator, content: (await engine.readPageSnapshot(origin.locator, { sourceId }))?.page.compiled_truth ?? '', contentHash: origin.contentHash }
+ : { kind: 'transcript' as const, filePath: origin.locator, content: readFileSync(origin.locator, 'utf8'), contentHash: origin.contentHash };
+ check();
+ const current = await readAtomOrigin(engine, session, item);
+ check();
+ // The retry runs against the current origin (its revision and visibility);
+ // only a change to the input the run key covers refuses it.
+ if (atomRetryInputKey(session, current) !== atomRetryInputKey(session, origin)) throw opError('source_changed', 'The original atom input changed; this retry cannot reuse it.',
+ `The ${origin.kind} that atom request ${requestId} extracted from in source ${sourceId} has changed since, so its retained batch no longer applies; nothing was started. Run a fresh atom drain, which extracts from the current content.`,
+ { fix: drainFix(sourceId) });
+ const resumed = await resumeManagedAtoms(engine, session, current);
+ check();
+ if (resumed === 'done') return { status: 'completed', replayed: true, model_rerun: false };
+ const checkpoint = retry.expectedCheckpoint as Array<{ failure?: string }> | null;
+ if (checkpoint && !checkpoint[0]?.failure) return { status: 'completed', replayed: true, model_rerun: false };
+ const saved = retry.rows.filter(row => row.intent?.kind === 'managed_atom_page');
+ const deleted = retry.rows.filter(row => row.intent?.kind === 'managed_atom_delete');
+ if (saved.length || deleted.length) {
+ const atoms: Parameters<typeof publishManagedAtoms>[3] = [];
+ for (const row of saved) {
+ const p = row.intent as AtomIntent;
+ const target = await engine.readPageSnapshot(row.slug, { sourceId, includeDeleted: true });
+ check();
+ const revision = row.state === 'committed' ? row.outcome?.revision : p.expected_revision ?? null;
+ if (typeof revision !== 'string' && (row.state === 'committed' || revision !== null)) throw opError('storage_error', 'The retained atom publication revision is unavailable.',
+ `The receipt of atom page ${row.slug} (request ${row.request_id}) no longer records the revision it published against, so the retry cannot republish it; nothing was published. Read the batch's receipt, then run a fresh atom drain for source ${sourceId}.`,
+ { fix: receiptFix(requestId) });
+ const pageId = row.state === 'committed' ? row.page_id ?? target?.page.id ?? null : row.page_id;
+ if ((target?.page.id ?? null) !== pageId || (target?.revision ?? null) !== revision) {
+ throw opError('page_identity_changed', 'An atom target changed independently of the failed publication.',
+ `Atom page ${row.slug} in source ${sourceId} was edited, created, deleted or replaced after request ${requestId} failed, so republishing would overwrite that change; nothing was published. Read the page, then run a fresh atom drain if its atoms still need extracting.`,
+ { fix: pageFix(sourceId, row.slug) });
+ }
+ if (typeof p.content !== 'string') throw opError('storage_error', 'The retained atom publication content is unavailable.',
+ `The receipt of atom page ${row.slug} (request ${row.request_id}) no longer holds its content (the retained payload expired), so the retry cannot republish it; nothing was published. Read the batch's receipt, then run a fresh atom drain for source ${sourceId}.`,
+ { fix: receiptFix(requestId) });
+ atoms.push({ slug: row.slug, content: p.content, links: p.links ?? [], expectedTarget: { pageId, revision } });
}
- if (typeof p.content !== 'string') throw opError('storage_error', 'The retained atom publication content is unavailable.',
- `The receipt of atom page ${row.slug} (request ${row.request_id}) no longer holds its content (the retained payload expired), so the retry cannot republish it; nothing was published. Read the batch's receipt, then run a fresh atom drain for source ${sourceId}.`,
- { fix: receiptFix(requestId) });
- atoms.push({ slug: row.slug, content: p.content, links: p.links ?? [], expectedTarget: { pageId, revision } });
- }
- const retirements: ManagedAtomRetirement[] = [];
- for (const row of deleted) {
- const p = row.intent as AtomIntent;
- const target = await engine.readPageSnapshot(row.slug, { sourceId, includeDeleted: true });
- const revision = row.state === 'committed' ? row.outcome?.revision : p.expected_revision;
- if (typeof revision !== 'string' || row.page_id === null || !target ||
- target.page.id !== row.page_id || target.revision !== revision || Boolean(target.page.deleted_at) !== (row.state === 'committed')) {
- throw opError('page_identity_changed', 'An atom retirement target changed independently of the failed publication.',
- `Atom page ${row.slug} in source ${sourceId}, which request ${requestId} was retiring, was edited, restored or replaced after the failure, so retiring it now would discard that change; nothing was published. Read the page and decide with the user whether it should still be retired.`,
- { fix: pageFix(sourceId, row.slug) });
+ const retirements: ManagedAtomRetirement[] = [];
+ for (const row of deleted) {
+ const p = row.intent as AtomIntent;
+ const target = await engine.readPageSnapshot(row.slug, { sourceId, includeDeleted: true });
+ check();
+ const revision = row.state === 'committed' ? row.outcome?.revision : p.expected_revision;
+ if (typeof revision !== 'string' || row.page_id === null || !target ||
+ target.page.id !== row.page_id || target.revision !== revision || Boolean(target.page.deleted_at) !== (row.state === 'committed')) {
+ throw opError('page_identity_changed', 'An atom retirement target changed independently of the failed publication.',
+ `Atom page ${row.slug} in source ${sourceId}, which request ${requestId} was retiring, was edited, restored or replaced after the failure, so retiring it now would discard that change; nothing was published. Read the page and decide with the user whether it should still be retired.`,
+ { fix: pageFix(sourceId, row.slug) });
+ }
+ retirements.push({ slug: row.slug, pageId: row.page_id, revision });
}
- retirements.push({ slug: row.slug, pageId: row.page_id, revision });
+ check();
+ receipts = await publishManagedAtoms(engine, session, current, atoms, undefined, retirements);
+ check();
+ return { status: 'completed', model_rerun: false, write_requests: receipts };
+ }
+ if (!retry.rows.some(row => row.outcome?.failure)) throw opError('invalid_params', 'This failed batch has no malformed extraction to retry.',
+ `Atom batch ${requestId} in source ${sourceId} did not fail on malformed model output, so a model rerun cannot fix it; nothing was started. Read its receipt for the recorded error and fix that cause instead.`,
+ { fix: receiptFix(requestId) });
+ const { runPhaseExtractAtoms } = await import('../cycle/extract-atoms.ts');
+ check();
+ const result = await runPhaseExtractAtoms(engine, { sourceId, _managedRetry: { requestId, retryId },
+ signal: stop.signal, attempt: { writeWait: wait },
+ _pages: item.kind === 'page' ? [item] : [], _transcripts: item.kind === 'transcript' ? [item] : [] });
+ receipts = Array.isArray(result.details?.write_requests) ? result.details.write_requests.filter(isWriteReceipt) : [];
+ check();
+ if (result.status !== 'ok') {
+ const receipt = receipts.at(-1);
+ const pending = receipt && ['queued', 'running', 'recovering'].includes(receipt.state);
+ const inspected = receipt?.request_id ?? requestId;
+ const error = opError(pending ? 'write_pending' : 'extraction_failed', 'The explicit atom retry did not complete; inspect its retained receipt before approving another attempt.',
+ pending
+ ? `The retry's atom write ${inspected} in source ${sourceId} is still queued or running and may still commit. Inspect its receipt and wait for it to settle; do not approve another attempt meanwhile.`
+ : `The retry of atom batch ${requestId} in source ${sourceId} ran the model again and failed. Read the receipt for the recorded error before asking the user to approve another paid attempt.`,
+ { fix: receiptFix(inspected) });
+ if (receipt) error.writeRequest = receipt;
+ throw error;
}
- const receipts = await publishManagedAtoms(engine, session, current, atoms, undefined, retirements);
- return { status: 'completed', model_rerun: false, write_requests: receipts };
- }
- if (!retry.rows.some(row => row.outcome?.failure)) throw opError('invalid_params', 'This failed batch has no malformed extraction to retry.',
- `Atom batch ${requestId} in source ${sourceId} did not fail on malformed model output, so a model rerun cannot fix it; nothing was started. Read its receipt for the recorded error and fix that cause instead.`,
- { fix: receiptFix(requestId) });
- const { runPhaseExtractAtoms } = await import('../cycle/extract-atoms.ts');
- const result = await runPhaseExtractAtoms(engine, { sourceId, _managedRetry: { requestId, retryId },
- _pages: item.kind === 'page' ? [item] : [], _transcripts: item.kind === 'transcript' ? [item] : [] });
- if (result.status !== 'ok') {
- const receipts = Array.isArray(result.details?.write_requests) ? result.details.write_requests.filter(isWriteReceipt) : [];
- const receipt = receipts.at(-1);
- const pending = receipt && ['queued', 'running', 'recovering'].includes(receipt.state);
- const inspected = receipt?.request_id ?? requestId;
- const error = opError(pending ? 'write_pending' : 'extraction_failed', 'The explicit atom retry did not complete; inspect its retained receipt before approving another attempt.',
- pending
- ? `The retry's atom write ${inspected} in source ${sourceId} is still queued or running and may still commit. Inspect its receipt and wait for it to settle; do not approve another attempt meanwhile.`
- : `The retry of atom batch ${requestId} in source ${sourceId} ran the model again and failed. Read the receipt for the recorded error before asking the user to approve another paid attempt.`,
- { fix: receiptFix(inspected) });
- if (receipt) error.writeRequest = receipt;
- throw error;
- }
- return { ...result, model_rerun: true };
- }, { ttlMinutes: 5 });
+ return { ...result, model_rerun: true };
+ }, { ttlMinutes: 5 });
+ } catch (error) {
+ // Lease loss reported at teardown, after work returned durable receipts.
+ if (receipts.length && error instanceof Error && error.name === 'LockStolenError') throw stoppedRetry(error, receipts);
+ throw error;
+ } finally { stop?.dispose(); }
}
diff --git a/test/cycle-patterns-deadline-budget.test.ts b/test/cycle-patterns-deadline-budget.test.ts
index 9a821d8dd0..ca661e9fba 100644
--- a/test/cycle-patterns-deadline-budget.test.ts
+++ b/test/cycle-patterns-deadline-budget.test.ts
@@ -138,9 +138,10 @@ describe('deadline plumbing wiring (structural)', () => {
expect(workerSrc).toContain('job.timeout_at.getTime() - Date.now()');
});
- test('autopilot-cycle, global-maintenance AND phase-wrapper handlers thread deadlineAtMs into runCycle', () => {
+ test('cycle handlers and explicit atom retries thread the job deadline into their work', () => {
const matches = jobsSrc.match(/deadlineAtMs: job\.deadlineAtMs/g) ?? [];
- expect(matches.length).toBe(3);
+ // Three runCycle paths plus the explicit managed-atom retry (#6622).
+ expect(matches.length).toBe(4);
});
test('runCycle forwards deadlineAtMs to the patterns phase', () => {
diff --git a/test/managed-atom-retry-cancellation.serial.test.ts b/test/managed-atom-retry-cancellation.serial.test.ts
new file mode 100644
index 0000000000..05d4176828
--- /dev/null
+++ b/test/managed-atom-retry-cancellation.serial.test.ts
@@ -0,0 +1,118 @@
+/**
+ * Protects explicit atom retries from cancellation, deadline expiry and lease loss.
+ * Regression: the retry handler/early return drops controls, or a retry crosses an
+ * awaited read and starts model/publication work after cancellation. Existing
+ * managed-atoms-retry tests cover replay/holds, not these stop boundaries.
+ * No production-only seam: mocked storage/model/lease boundaries, real retry and handler.
+ */
+import { afterAll, beforeEach, expect, mock, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import type { WriteReceipt } from '../src/core/persistence/types.ts';
+
+let lock: AbortController;
+let sessions = 0, phases = 0, publications = 0;
+let read = async () => ({ page: { compiled_truth: 'Synthetic origin' } });
+let phase: (opts: any) => Promise<any>;
+let publish: () => Promise<WriteReceipt[]>;
+let saved = false;
+const origin = { kind: 'page', locator: 'notes/example', contentHash: 'same' };
+let session: any;
+mock.module('../src/core/db-lock.ts', () => ({
+ withRefreshingLock: async (_engine: unknown, _id: string, work: (signal: AbortSignal) => Promise<unknown>) => work(lock.signal),
+}));
+mock.module('../src/core/cycle.ts', () => ({ cycleLockIdFor: (source: string) => `cycle:${source}` }));
+mock.module('../src/core/persistence/atom-maintenance.ts', () => ({
+ managedAtomSession: async (_engine: unknown, _source: string, _retry: unknown, wait: unknown) => {
+ sessions++;
+ session = { wait, retry: { origin, expectedCheckpoint: [{ failure: 'malformed' }], rows: saved
+ ? [{ slug: 'atoms/example', state: 'failed', page_id: null, intent: { kind: 'managed_atom_page', content: 'Retained', expected_revision: null } }]
+ : [{ outcome: { failure: 'malformed' } }] } };
+ return session;
+ },
+ readAtomOrigin: async () => origin,
+ atomRetryInputKey: () => 'same',
+ resumeManagedAtoms: async () => 'run',
+ publishManagedAtoms: async () => { publications++; return publish(); },
+}));
+mock.module('../src/core/cycle/extract-atoms.ts', () => ({
+ runPhaseExtractAtoms: async (_engine: unknown, opts: unknown) => { phases++; return phase(opts); },
+}));
+const { retryManagedAtomBatch } = await import('../src/core/persistence/atom-retry.ts');
+const { makeExtractAtomsDrainHandler } = await import('../src/core/minions/handlers/extract-atoms-drain.ts');
+const engine = { readPageSnapshot: async (slug: string) => slug === 'atoms/example' ? null : read() } as unknown as BrainEngine;
+const job = (signal: AbortSignal, deadlineAtMs?: number) => ({ id: 42, data: { sourceId: 'default', retryRequestId: 'synthetic-retry' }, signal, deadlineAtMs }) as unknown as MinionJobContext;
+const receipt = (state: 'queued' | 'committed'): WriteReceipt => ({ request_id: '11111111-1111-4111-8111-111111111111', state, retry_after_ms: state === 'queued' ? 100 : null });
+beforeEach(() => {
+ lock = new AbortController(); sessions = phases = publications = 0; saved = false;
+ read = async () => ({ page: { compiled_truth: 'Synthetic origin' } });
+ phase = async () => ({ status: 'ok' }); publish = async () => [];
+});
+afterAll(() => mock.restore());
+
+test('handler rejects a pre-aborted explicit retry before storage/model work', async () => {
+ const stop = new AbortController(); stop.abort(new Error('caller stopped'));
+ await expect(makeExtractAtomsDrainHandler(engine)(job(stop.signal))).rejects.toThrow('caller stopped');
+ expect(sessions).toBe(0); expect(phases).toBe(0);
+});
+test('handler rejects an expired retry deadline before storage/model work', async () => {
+ await expect(makeExtractAtomsDrainHandler(engine)(job(new AbortController().signal, Date.now() - 1))).rejects.toThrow(/deadline/i);
+ expect(sessions).toBe(0); expect(phases).toBe(0);
+});
+for (const cause of ['caller', 'lease'] as const) test(`cancellation during the origin read (${cause}) prevents the model rerun`, async () => {
+ const caller = new AbortController();
+ read = async () => { (cause === 'caller' ? caller : lock).abort(new Error(`${cause} stopped`)); return { page: { compiled_truth: 'Synthetic origin' } }; };
+ await expect(makeExtractAtomsDrainHandler(engine)(job(caller.signal))).rejects.toThrow(`${cause} stopped`);
+ expect(phases).toBe(0); expect(publications).toBe(0);
+});
+test('model receives caller/lease cancellation and the deadline-bound shared wait', async () => {
+ const caller = new AbortController(); const deadline = Date.now() + 2_000;
+ phase = async opts => {
+ expect(opts.signal).toBeInstanceOf(AbortSignal);
+ expect(opts.attempt.writeWait).toBe(session.wait);
+ expect(opts.attempt.writeWait.ms()).toBeLessThanOrEqual(2_000);
+ lock.abort(new Error('lease stopped'));
+ expect(opts.signal.aborted).toBe(true);
+ return { status: 'warn', details: {} };
+ };
+ await expect(makeExtractAtomsDrainHandler(engine)(job(caller.signal, deadline))).rejects.toThrow('lease stopped');
+ expect(phases).toBe(1);
+});
+// The minion worker aborts job.signal at the deadline (worker.ts timeout timer);
+// the retry reports that stop as the deadline and never completes.
+test('the worker deadline abort stops an in-flight model and does not complete the retry', async () => {
+ const worker = new AbortController(); const deadline = Date.now() + 100;
+ const timer = setTimeout(() => worker.abort(new Error('timeout')), deadline - Date.now());
+ phase = opts => new Promise(resolve => opts.signal.addEventListener('abort', () => resolve({ status: 'warn', details: {} }), { once: true }));
+ await expect(makeExtractAtomsDrainHandler(engine)(job(worker.signal, deadline))).rejects.toThrow(/deadline/i);
+ clearTimeout(timer);
+ expect(phases).toBe(1);
+});
+test('a model that returns after the deadline does not complete the retry', async () => {
+ const deadline = Date.now() + 50;
+ phase = async () => { await new Promise(resolve => setTimeout(resolve, 100)); return { status: 'ok' }; };
+ await expect(makeExtractAtomsDrainHandler(engine)(job(new AbortController().signal, deadline))).rejects.toThrow(/deadline/i);
+ expect(phases).toBe(1);
+});
+for (const branch of ['model', 'retained'] as const) for (const state of ['queued', 'committed'] as const) test(`${branch} cancellation retains ${state} write receipts`, async () => {
+ const caller = new AbortController(); const receipts = [receipt(state)];
+ saved = branch === 'retained';
+ phase = async () => { caller.abort(new Error('caller stopped')); return { status: 'ok', details: { write_requests: receipts } }; };
+ publish = async () => { caller.abort(new Error('caller stopped')); return receipts; };
+ const error = await makeExtractAtomsDrainHandler(engine)(job(caller.signal)).catch(e => e) as Error &
+ { write_requests: WriteReceipt[]; code?: string; writeRequest?: WriteReceipt };
+ expect(error).toBeInstanceOf(Error);
+ expect(error.write_requests).toEqual(receipts);
+ if (state === 'queued') { expect(error.code).toBe('write_pending'); expect(error.writeRequest).toEqual(receipts[0]); }
+ else { expect(error.name).toBe('AbortError'); expect(error.code).not.toBe('cancelled'); }
+});
+test('four-argument retry remains compatible and removes caller listeners on success', async () => {
+ expect(await retryManagedAtomBatch(engine, 'default', 'synthetic-retry', 'job:old')).toMatchObject({ model_rerun: true });
+ const caller = new AbortController();
+ const added = mock(caller.signal.addEventListener.bind(caller.signal));
+ const removed = mock(caller.signal.removeEventListener.bind(caller.signal));
+ caller.signal.addEventListener = added; caller.signal.removeEventListener = removed;
+ expect(await makeExtractAtomsDrainHandler(engine)(job(caller.signal))).toMatchObject({ model_rerun: true });
+ expect(added.mock.calls.length).toBeGreaterThan(0);
+ expect(removed.mock.calls.length).toBe(added.mock.calls.length);
+});
diff --git a/test/managed-atoms-retry.test.ts b/test/managed-atoms-retry.test.ts
index 060ac237c7..9730415fe8 100644
--- a/test/managed-atoms-retry.test.ts
+++ b/test/managed-atoms-retry.test.ts
@@ -171,6 +171,41 @@ test('an explicit retry still runs a held page and clears it from doctor', async
});
}, 90_000);
+// #6622: existing replay/held coverage never cancelled the explicit retry.
+// Real journal, source lease and gateway; only the provider is synthetic. The
+// deadline case aborts the caller signal at the deadline, as the minion worker does.
+for (const stop of ['caller', 'deadline'] as const) test(`explicit retry ${stop} cancellation reaches the real model and leaves no new strike`, async () => {
+ await managed(async () => {
+ const page = await writePage('A careful project record.');
+ const f = fixture();
+ await runPhaseExtractAtoms(engine, { _transcripts: [],
+ _pages: [{ slug: page.slug, content: page.compiled_truth, contentHash: page.content_hash! }], _chat: f.chat });
+ await disposePersistenceConsumer(engine);
+ const [before] = await checkpoints();
+ const controller = new AbortController();
+ const deadlineAtMs = Date.now() + 500;
+ const timer = stop === 'deadline' ? setTimeout(() => controller.abort(new Error('timeout')), 500) : undefined;
+ const signals: AbortSignal[] = [];
+ __setChatTransportForTests(async opts => {
+ expect(opts.abortSignal).toBeInstanceOf(AbortSignal);
+ signals.push(opts.abortSignal!);
+ if (stop === 'caller') controller.abort(new Error('synthetic caller stop'));
+ if (!opts.abortSignal!.aborted) await new Promise<void>(resolve => opts.abortSignal!.addEventListener('abort', () => resolve(), { once: true }));
+ throw new Error('synthetic provider aborted');
+ });
+ const error = await retryManagedAtomBatch(engine, 'default', before.request_id, `job:stop-${stop}`,
+ { signal: controller.signal, deadlineAtMs }).catch(e => e);
+ clearTimeout(timer);
+ expect(error).toBeInstanceOf(Error);
+ expect(error.message).toContain(stop === 'caller' ? 'synthetic caller stop' : 'deadline');
+ expect(signals).toHaveLength(1);
+ expect(signals[0].aborted).toBe(true);
+ expect(await checkpoints()).toEqual([before]);
+ expect(await atomCount()).toBe(0);
+ expect(await engine.executeRaw("SELECT id FROM gbrain_cycle_locks WHERE id='gbrain-cycle:default'")).toEqual([]);
+ });
+}, 60_000);
+
test('a transcript origin is bounded the same way', async () => {
await managed(async (home) => {
const file = join(home, 'session.txt');