Repository navigation
feat(cron): recover interrupted one-shot jobs on restart - #131473
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: found issues before merge. Reviewed August 27, 2026, 11:36 PM ET / August 28, 2026, 03:36 UTC. ClawSweeper reviewWhat this changesThe PR changes restart recovery so interrupted enabled one-shot cron jobs are admitted through missed-job catch-up while terminal attempts remain protected by exact run receipts. Regression provenancePossible regression — probable (reviewed change; failure trace). No predecessor PR is attributed. Merge readiness⛔ Blocked by patch quality or review findings - 5 items remain Keep open: the intentional one-shot recovery change is not on current main, but the new removed-job finalization branch can turn a completed queued manual run into an error when receipt persistence fails. Priority: P2 Review scores
Verification
Live VerificationCommand: Result: PASS (completed) Assertions:
How this fits togetherCron stores schedules, execution receipts, and task history in SQLite. Gateway startup repairs interrupted work, then the scheduler admits any due catch-up occurrence and records its terminal outcome. flowchart LR
A[Stored cron job] --> B[Gateway restart]
B --> C[Receipt and task-history recovery]
C --> D[Pending catch-up or terminal repair]
D --> E[Scheduler admission]
E --> F[Job execution]
F --> G[Receipt and task outcome]
Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource -27, Tests +632, Docs 0. Total +605 across 14 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Record the completed removed-run task outcome before fallible receipt settlement, then add a regression that combines cross-service removal with a forced receipt-write failure and verifies the original terminal status. Do we have a high-confidence way to reproduce the issue? Yes, from source: queue a manual run, remove its row from another service after completion begins, and force the receipt UPDATE to fail; the outer queued-run catch then records an error terminal result. Is this the best way to solve the issue? No; the one-shot catch-up design is coherent, but the removed-job branch must publish the exact completed task result before its fallible receipt settlement. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 5c8db67a3b89. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
|
Record completed task facts before settling current or retired runs, and keep retired receipts through canonical recovery. This prevents completed one-shots from replaying when an older unfinished task shares their start millisecond. Reload repaired rows before publishing sibling outcomes and preserve schedules changed by another service. Cover terminal shutdown and generation outcomes, replacement receipts, transaction rollback, and repeated restart deferrals.
Keep completed direct runs in the existing manual outcome transaction after scheduler generation retirement. Preserve reservation-time force scheduling, dispatch committed failure notifications, and suppress retired publication. Do not let retired receipt conflicts clear a same-millisecond successor's reservation. Extend lifecycle coverage to due runs, future and delayed force runs, receipt replacement, and terminal failure notification delivery.
Do not terminalize a receipt from generic exception cleanup after its terminal task fact is durable. Keep exact identity available for recovery when the runtime-row transaction rolls back, while releasing local admission ownership. Share explicit removed-run finalization before and after lock acquisition so concurrent removal cannot orphan a receipt. Cover current and retired write failures, repeated restart recovery, and removal while finalization waits.
Scope interrupted one-shot replay to startup while preserving live dead-owner reclamation. Settle current and retired timer outcomes through the exact receipt transaction, and finalize quiet timer/manual tasks only after cron state commits. Keep exact receipts after rolled-back manual writes and preserve separate receipt-only retry coverage. Verify all cron unit groups and the explicit changed-file gate. Refs #131473.
59e260a to
72f0c1b
Compare
|
Merged via squash.
|
…1473) * feat(cron): recover interrupted one-shot jobs on restart * fix(cron): preserve terminal outcomes through scheduler retirement Record completed task facts before settling current or retired runs, and keep retired receipts through canonical recovery. This prevents completed one-shots from replaying when an older unfinished task shares their start millisecond. Reload repaired rows before publishing sibling outcomes and preserve schedules changed by another service. Cover terminal shutdown and generation outcomes, replacement receipts, transaction rollback, and repeated restart deferrals. * fix(cron): settle retired manual runs with exact receipts Keep completed direct runs in the existing manual outcome transaction after scheduler generation retirement. Preserve reservation-time force scheduling, dispatch committed failure notifications, and suppress retired publication. Do not let retired receipt conflicts clear a same-millisecond successor's reservation. Extend lifecycle coverage to due runs, future and delayed force runs, receipt replacement, and terminal failure notification delivery. * fix(cron): retain receipts after failed manual outcome writes Do not terminalize a receipt from generic exception cleanup after its terminal task fact is durable. Keep exact identity available for recovery when the runtime-row transaction rolls back, while releasing local admission ownership. Share explicit removed-run finalization before and after lock acquisition so concurrent removal cannot orphan a receipt. Cover current and retired write failures, repeated restart recovery, and removal while finalization waits. * fix(cron): reconcile recovery and finalization invariants Scope interrupted one-shot replay to startup while preserving live dead-owner reclamation. Settle current and retired timer outcomes through the exact receipt transaction, and finalize quiet timer/manual tasks only after cron state commits. Keep exact receipts after rolled-back manual writes and preserve separate receipt-only retry coverage. Verify all cron unit groups and the explicit changed-file gate. Refs openclaw#131473.
…r changes, or a repair instead of the final alert (#162702) ## What Problem This Solves Fixes two gaps in the owner-conversation repair from #161007: a job that keeps failing can get a second repair turn when its error changes, and a one-shot job that has used up its retries gets a repair request instead of its alert. ## User Impact - Each failure streak gets one repair request, even if its cause changes later. The next failure sends the normal alert once, naming the repair, as before. Later alerts in the streak follow the usual dedupe and cooldown. Only a successful run starts a new streak, which can be repaired again. - A job that will not run again keeps the existing failure alert and gets no repair request. This covers a disabled job and an `at` job with no retry scheduled, for example one whose retries ran out or whose error is permanent. ## Why This Change Was Made **Provenance.** #161007 (fb2052a) added `failureAlertIncident.repair`. The repair request takes the incident's alert and cooldown slot, and the next failure skips dedupe and cooldown once to send the fallback alert. That fallback goes through `startFailureAlertCycle` (#146582, 5c81503), which rebuilds the incident from the new signature and so dropped `repair`. After that, a later failure with a different cause, once the cooldown had passed, looked like a new streak and got a second repair turn, which #161007 meant to prevent ("the streak is never repaired twice"). Separately, the one-shot retry policy (#24355) disables an `at` job when its retries run out. With `failureAlert.after` equal to that attempt, the repair replaced the job's final alert, and no later run could send the fallback. **Fix (`failure-alerts.ts`, `startup-run-repair.ts`):** - `startFailureAlertCycle` keeps `repair` and marks it `alerted: true`. Any alert after a repair request is its fallback. The marker lasts until `resolveFailureIncident` (success) deletes the incident. A repair is only requested when the incident has no `repair`, and the fallback bypass only runs while `alerted` is unset. Everything else from #161007 is unchanged: the repair still takes the alert and cooldown slot, and the fallback still fires once. A persisted marker from #161007 without `alerted` gets its pending fallback. - Repair also requires `isJobEnabled(job)`, checked after scheduling settles. `applyJobResult` already finalizes notifications after a one-shot is disabled or a retry is scheduled. On restart, `markInterruptedStartupRun` disabled a retired one-shot only after finalizing notifications. It now does that first (#131473 logic, unchanged otherwise), so an interrupted one-shot that will be replayed is still repaired and a retired one alerts. Recurring jobs whose next run is recomputed later in recovery also stay eligible. Persisted state: `repair: { atMs }` gains an optional `alerted: true`, and its lifetime becomes the streak. **Bounded cost.** At most one repair turn per failure streak. The number of messages does not increase: a repair turn replaces an alert, the fallback is the single alert it was before, and terminal one-shots send the same single alert as before #161007. No new config, warnings, or message types. Hermes check: Hermes kanban's `failure_limit` auto-block also keeps streak-scoped state that only a success resets. This PR follows the same approach. ## Evidence - `src/cron/service.failure-repair.test.ts` (real `CronService`): - error A ×2 → repair; A → alert; cooldown passes; error B → alert, not a second repair; success; A ×2 → repair again. On origin/main, B started a second repair. - an `at` job with `failureAlert.after: 4`, run on schedule (`due`) until its retries are exhausted → disabled, one alert, no repair. On origin/main: one repair, no alert. - restart-interrupted owned jobs at the threshold (real `markInterruptedStartupRun`): recurring → repair; replayed one-shot → repair; retired one-shot → alert. It fails without the reorder (the retired one-shot is repaired) and with a `nextRunAtMs` gate (the replayed one-shot alerts). - Related suites pass: failure-repair, failure-alert, failure-alerts persistence/recovery, startup-run-repair, run-recovery, Gateway `server.cron-failure-repair`. - **Live Telegram Test Server, live model (`openai/gpt-6-astra`), DM owner conversation.** Each run uses an isolated source Gateway with a fresh state dir. A proxy in front of the real OpenAI API injects provider rejections only into the automation's own model calls: cause A is a 400 `invalid_value` (classified `format`), and cause B is a 404 `model_not_found`. The owner chat and the repair turns go to the live model. Scenario: owned hourly job, `failureAlert {after: 2, cooldownMs: 60s}`. Runs A, A, A; wait 65s; B. Then an owned `at` job (`after: 1`) whose single scheduled run fails with A. | Step | origin/main cron files (unchanged since `b2fc927`) | PR head `f064aed` | |---|---|---| | A ×2 | repair turn → *"Inbox sync is failing because the provider rejects its request format… Please provide the provider's detailed invalid_value error…"* | same repair turn and reply | | A (3rd) | alert *"failed 3 times / An automatic repair was requested…"* | same alert | | B after cooldown | **second repair turn** (model saw a brief for failure 4) → *"Inbox sync now fails because the provider cannot find openai/gpt-6-astra. Which available provider/model should I use…?"* and no alert | alert *"Automation "Inbox sync" failed 4 times / An automatic repair was requested… / Cause: model_not_found…"* and no repair turn | | terminal one-shot (disabled after the run) | **repair turn** → *"Report export failed because the provider rejected the request format. Please provide…"* for a job that will never run again | alert *"Automation "Report export" failed 1 times / Cause: format"* and no repair turn | Repair briefs the live model received: origin/main `[1, 2, 4]` (failure counts), PR head `[2]`. The runner completed on the PR head (lease released, scratch removed, no listeners left). The origin/main run hit the scenario command's 540s timeout at the very end, after it had recorded every step. - **Store reopen (throwaway, real SQLite cron store, not committed).** A seeded #161007-shape incident `{signature, repair: {atMs}}` reloads as-is. The next failure sends the pending fallback (alerts 1, repairs 0) and persists `repair: {atMs, alerted: true}`. After a second `CronService` reopens the store, the marker still has `alerted: true`. A same-cause failure and a new-cause failure within the cooldown send nothing. A new cause after the cooldown sends one alert and no repair. - Changed suite runtime: `pnpm vitest run src/cron/service.failure-repair.test.ts --maxWorkers=1` → 15 tests, 30.7s total (about 16s of it test time, the rest transform and import warmup). - Throwaway real-Gateway smoke over WS (`cron.add`/`cron.run`, real cron service and `agent` dispatch, mocked isolated run; not committed): A,A → repair (`agent` dispatch 1); A → alert; A → deduped; B after cooldown → alert `delivered`, dispatch still 1; ok, then A,A → repair (dispatch 2); terminal `at` job with a permanent error → `enabled:false`, alert `delivered`, dispatch still 2. On origin/main, B after cooldown dispatched a second repair. LOC vs origin/main: prod +31/−23 (`failure-alerts.ts`, `startup-run-repair.ts`, `types.ts`), test +98/−1, docs +1/−1. Co-authored-by: Ayaan Zaidi <[email protected]>
…r changes, or a repair instead of the final alert (openclaw#162702) ## What Problem This Solves Fixes two gaps in the owner-conversation repair from openclaw#161007: a job that keeps failing can get a second repair turn when its error changes, and a one-shot job that has used up its retries gets a repair request instead of its alert. ## User Impact - Each failure streak gets one repair request, even if its cause changes later. The next failure sends the normal alert once, naming the repair, as before. Later alerts in the streak follow the usual dedupe and cooldown. Only a successful run starts a new streak, which can be repaired again. - A job that will not run again keeps the existing failure alert and gets no repair request. This covers a disabled job and an `at` job with no retry scheduled, for example one whose retries ran out or whose error is permanent. ## Why This Change Was Made **Provenance.** openclaw#161007 (fc14fc8) added `failureAlertIncident.repair`. The repair request takes the incident's alert and cooldown slot, and the next failure skips dedupe and cooldown once to send the fallback alert. That fallback goes through `startFailureAlertCycle` (openclaw#146582, e80c552), which rebuilds the incident from the new signature and so dropped `repair`. After that, a later failure with a different cause, once the cooldown had passed, looked like a new streak and got a second repair turn, which openclaw#161007 meant to prevent ("the streak is never repaired twice"). Separately, the one-shot retry policy (openclaw#24355) disables an `at` job when its retries run out. With `failureAlert.after` equal to that attempt, the repair replaced the job's final alert, and no later run could send the fallback. **Fix (`failure-alerts.ts`, `startup-run-repair.ts`):** - `startFailureAlertCycle` keeps `repair` and marks it `alerted: true`. Any alert after a repair request is its fallback. The marker lasts until `resolveFailureIncident` (success) deletes the incident. A repair is only requested when the incident has no `repair`, and the fallback bypass only runs while `alerted` is unset. Everything else from openclaw#161007 is unchanged: the repair still takes the alert and cooldown slot, and the fallback still fires once. A persisted marker from openclaw#161007 without `alerted` gets its pending fallback. - Repair also requires `isJobEnabled(job)`, checked after scheduling settles. `applyJobResult` already finalizes notifications after a one-shot is disabled or a retry is scheduled. On restart, `markInterruptedStartupRun` disabled a retired one-shot only after finalizing notifications. It now does that first (openclaw#131473 logic, unchanged otherwise), so an interrupted one-shot that will be replayed is still repaired and a retired one alerts. Recurring jobs whose next run is recomputed later in recovery also stay eligible. Persisted state: `repair: { atMs }` gains an optional `alerted: true`, and its lifetime becomes the streak. **Bounded cost.** At most one repair turn per failure streak. The number of messages does not increase: a repair turn replaces an alert, the fallback is the single alert it was before, and terminal one-shots send the same single alert as before openclaw#161007. No new config, warnings, or message types. Hermes check: Hermes kanban's `failure_limit` auto-block also keeps streak-scoped state that only a success resets. This PR follows the same approach. ## Evidence - `src/cron/service.failure-repair.test.ts` (real `CronService`): - error A ×2 → repair; A → alert; cooldown passes; error B → alert, not a second repair; success; A ×2 → repair again. On origin/main, B started a second repair. - an `at` job with `failureAlert.after: 4`, run on schedule (`due`) until its retries are exhausted → disabled, one alert, no repair. On origin/main: one repair, no alert. - restart-interrupted owned jobs at the threshold (real `markInterruptedStartupRun`): recurring → repair; replayed one-shot → repair; retired one-shot → alert. It fails without the reorder (the retired one-shot is repaired) and with a `nextRunAtMs` gate (the replayed one-shot alerts). - Related suites pass: failure-repair, failure-alert, failure-alerts persistence/recovery, startup-run-repair, run-recovery, Gateway `server.cron-failure-repair`. - **Live Telegram Test Server, live model (`openai/gpt-6-astra`), DM owner conversation.** Each run uses an isolated source Gateway with a fresh state dir. A proxy in front of the real OpenAI API injects provider rejections only into the automation's own model calls: cause A is a 400 `invalid_value` (classified `format`), and cause B is a 404 `model_not_found`. The owner chat and the repair turns go to the live model. Scenario: owned hourly job, `failureAlert {after: 2, cooldownMs: 60s}`. Runs A, A, A; wait 65s; B. Then an owned `at` job (`after: 1`) whose single scheduled run fails with A. | Step | origin/main cron files (unchanged since `e95c66b`) | PR head `f064aed` | |---|---|---| | A ×2 | repair turn → *"Inbox sync is failing because the provider rejects its request format… Please provide the provider's detailed invalid_value error…"* | same repair turn and reply | | A (3rd) | alert *"failed 3 times / An automatic repair was requested…"* | same alert | | B after cooldown | **second repair turn** (model saw a brief for failure 4) → *"Inbox sync now fails because the provider cannot find openai/gpt-6-astra. Which available provider/model should I use…?"* and no alert | alert *"Automation "Inbox sync" failed 4 times / An automatic repair was requested… / Cause: model_not_found…"* and no repair turn | | terminal one-shot (disabled after the run) | **repair turn** → *"Report export failed because the provider rejected the request format. Please provide…"* for a job that will never run again | alert *"Automation "Report export" failed 1 times / Cause: format"* and no repair turn | Repair briefs the live model received: origin/main `[1, 2, 4]` (failure counts), PR head `[2]`. The runner completed on the PR head (lease released, scratch removed, no listeners left). The origin/main run hit the scenario command's 540s timeout at the very end, after it had recorded every step. - **Store reopen (throwaway, real SQLite cron store, not committed).** A seeded openclaw#161007-shape incident `{signature, repair: {atMs}}` reloads as-is. The next failure sends the pending fallback (alerts 1, repairs 0) and persists `repair: {atMs, alerted: true}`. After a second `CronService` reopens the store, the marker still has `alerted: true`. A same-cause failure and a new-cause failure within the cooldown send nothing. A new cause after the cooldown sends one alert and no repair. - Changed suite runtime: `pnpm vitest run src/cron/service.failure-repair.test.ts --maxWorkers=1` → 15 tests, 30.7s total (about 16s of it test time, the rest transform and import warmup). - Throwaway real-Gateway smoke over WS (`cron.add`/`cron.run`, real cron service and `agent` dispatch, mocked isolated run; not committed): A,A → repair (`agent` dispatch 1); A → alert; A → deduped; B after cooldown → alert `delivered`, dispatch still 1; ok, then A,A → repair (dispatch 2); terminal `at` job with a permanent error → `enabled:false`, alert `delivered`, dispatch still 2. On origin/main, B after cooldown dispatched a second repair. LOC vs origin/main: prod +31/−23 (`failure-alerts.ts`, `startup-run-repair.ts`, `types.ts`), test +98/−1, docs +1/−1. Co-authored-by: Ayaan Zaidi <[email protected]>
Important
review-required: product behavior change (operator-directed). Prepared and landed under explicit operator direction to reverse a previously-asserted design; not counted as an autonomous root-cause fix.
What Problem This Solves
An interrupted
atone-shot job (admitted, but the gateway restarted before it finished) was disabled forever — a missed one-shot moment could never recover. This was deliberate design (asserted in code, docs, and a test, corroborated at stable v2026.7.1), but the operator decided a missed one-shot should recover on restart like any other missed occurrence.Why This Change Was Made
Interrupted one-shots now recover unconditionally through the existing missed-slot admission and pacing machinery (the same path recurring jobs use for overdue slots) — no new expiry window, config option, replay executor, or persistence field. The old disable-forever assignment and its asserted-design test/docs are deleted; recovery reuses the recovery, catch-up, scheduling, admission, and completion owners, with the pending catch-up marker committed atomically in the existing SQLite recovery transaction so a crash between repair and re-admission neither loses nor double-creates the slot.
The safety-critical invariant is no double-fire, and a deep-context review found the original commit did not hold it: stopped or generation-retired runs during shutdown superseded their receipt and wrote a generic task terminal record without the cron outcome detail recovery reads, so on restart the stale running marker was treated as interrupted and the payload executed again — for success, permanent error, and skipped outcomes alike. A same-millisecond orphan task defeated a naive full-detail fix by letting receipt-less lookup choose the wrong task. Three follow-up commits repair it: every terminal task fact is recorded before finalization/retirement, retired runs retain their exact receipt through the recovery transaction (never consuming a same-millisecond replacement), the finalizer reloads authoritative state before computing terminal scheduling facts, and the manual-run write-failure path keeps the exact receipt instead of a generic fallback. A terminal attempt is now provably distinct from an interrupted one on receipt identity, not timestamps or error strings.
User Impact
A one-shot that was interrupted by a restart runs once when the gateway comes back (subject to normal missed-job pacing); a one-shot that already reached any terminal state never re-runs.
deleteAfterRunone-shots delete only after a successful recovered completion; failed/skipped recovery retains the disabled row. External side effects that occurred before any durable terminal fact still cannot be deduplicated — the existing docs warning remains.Evidence