Skip to content

feat(cron): recover interrupted one-shot jobs on restart - #131473

Merged
steipete merged 5 commits into
mainfrom
steipete/oneshot-restart-recovery
Aug 28, 2026
Merged

steipete merged 5 commits into
mainfrom
steipete/oneshot-restart-recovery

Conversation

@steipete

Copy link
Copy Markdown
Contributor

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 at one-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. deleteAfterRun one-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

  • Production net -27 across the whole branch (feature +6, review repairs -33); tests net +632; no schema, config, persistence-format, or public-contract change.
  • Failing-first: all three terminal outcomes replayed twice pre-fix; the same-millisecond-orphan collision defeated the partial fix; the manual write-failure path replayed six current/retired cases — each reproduced then fixed.
  • 440 tests across 13 suites green (recovery, lifecycle 21-case matrix, batch finalization, receipt finalization, admission cleanup, timer regression); atomic-rollback test via a TEMP trigger rejecting the pending-slot UPDATE proves the recovery transaction leaves exactly one pending slot or the pre-repair state.
  • Post-rebase focused suites green; core production + services test typecheck green; two rounds of Codex autoreview clean at P0 (feature, terminal-retirement, manual-settle, write-failure).
  • Proof is real isolated SQLite scheduler/receipt/task-ledger with injected payload across fresh service restarts, not a killed production gateway; historical rows lacking canonical cron detail were not migration-tested.

@clawsweeper

clawsweeper Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: L maintainer Maintainer-authored PR labels Aug 28, 2026
@steipete
steipete marked this pull request as ready for review August 28, 2026 03:28
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 28, 2026
@clawsweeper

clawsweeper Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 27, 2026, 11:36 PM ET / August 28, 2026, 03:36 UTC.

ClawSweeper review

What this changes

The 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 provenance

Possible 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
Reviewed head: 59e260aa17c1e5f29371d81070212e672b0bb0ce

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) PR readiness rating was derived from proof quality, review findings, security review, and reviewer confidence.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): ClawSweeper live verification passed on the reviewed terminal surface.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): ClawSweeper live verification passed on the reviewed terminal surface.
Evidence reviewed 7 items Current main has the prior intentional behavior: Current main marks an interrupted one-shot as failed and disables it when no replacement schedule exists; its focused restart test expects no catch-up event or heartbeat.
Recovery path is receipt-bound: The PR checks task history using the exact receipt, atomically persists the pending one-shot catch-up marker, then retires that receipt.
Introduced terminal-status regression: The added missing-job branch calls the fallible receipt settlement before emitting the terminal task event. For queued manual runs, a settlement failure reaches the outer catch and records an error despite a completed payload.
Findings 1 actionable finding [P2] Record the removed run before settling its receipt
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs src/cron/service/run-recovery.test.ts src/cron/service/run-recovery.lifecycle.test.ts

Result: PASS (completed)

 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when rescheduled › does not replay a run that finishes as error after stopping 21m
s
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when rescheduled › does not replay a run that finishes as skipped after stopping 2
1ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual › does not replay a run that finishes as ok after stopping 18ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual › does not replay a run that finishes as error after stopping 26ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual › does not replay a run that finishes as skipped after stopping 22ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-future › does not replay a run that finishes as ok after stopping 19ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-future › does not replay a run that finishes as error after stopping 1
8ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-future › does not replay a run that finishes as skipped after stopping
 23ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-delayed-force › does not replay a run that finishes as ok after stoppi
ng 32ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-delayed-force › does not replay a run that finishes as error after sto
pping 29ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-delayed-force › does not replay a run that finishes as skipped after s
topping 27ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-replaced › does not replay a run that finishes as ok after stopping 22
ms
 ✓  cron  src/cron/
… output truncated …
oes not replay a run that finishes as error after stopping
 27ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-replaced › does not replay a run that finishes as skipped after stoppi
ng 22ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-write-failure › does not replay a run that finishes as ok after stoppi
ng 20ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-write-failure › does not replay a run that finishes as error after sto
pping 21ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-write-failure › does not replay a run that finishes as skipped after s
topping 20ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-write-failure-live › does not replay a run that finishes as ok after s
topping 20ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-write-failure-live › does not replay a run that finishes as error afte
r stopping 21ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-write-failure-live › does not replay a run that finishes as skipped af
ter stopping 24ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-removed › does not replay a run that finishes as ok after stopping 71m
s
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-removed › does not replay a run that finishes as error after stopping
66ms
 ✓  cron  src/cron/service/run-recovery.lifecycle.test.ts › one-shot recovery when manual-removed › does not replay a run that finishes as skipped after stoppin
g 69ms

 Test Files  2 passed (2)
      Tests  55 passed (55)
   Start at  03:37:35
   Duration  16.21s (transform 11.33s, setup 999ms, import 13.10s, tests 1.71s, environment 0ms)

[test] passed 1 Vitest shard in 23.46s

Assertions:

  • PASS expect_output: atomic cron run recovery
  • PASS expect_output: one-shot recovery when

How this fits together

Cron 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]
Loading

Before merge

  • Record the removed run before settling its receipt (P2) - The new missing-job branch settles the receipt before emitMissingTerminal(true). finishCronRunReceipt queues a retry and throws on a database failure, so queued manual execution reaches enqueueRun’s outer catch and records an error even when the payload completed successfully. Emit the exact terminal task result first, then add the combined removal and receipt-write-failure regression.
  • Resolve merge risk (P1) - A concurrent cross-service removal plus a receipt-write failure can report a completed queued manual run as an error; this corrupts the task ledger’s terminal outcome.
  • Resolve merge risk (P1) - The captured context has no independently inspectable exact-head test output; the PR-body validation claims remain supplemental until fresh checks complete.
  • Complete next step (P2) - This maintainer-labeled PR needs a narrow P2 lifecycle correction and fresh exact-head validation rather than repair-lane dispatch.
  • Improve patch quality - Address the highest-priority review finding and re-run the changed-surface validation.

Findings

  • [P2] Record the removed run before settling its receipt — src/cron/service/ops-run.ts:268-270
Agent review details

Security

None.

PR surface

Source -27, Tests +632, Docs 0. Total +605 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 7 94 121 -27
Tests 6 658 26 +632
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 753 148 +605

Review metrics

Metric Value Why it matters
Production versus test delta production -27, tests +632 The behavior change is net-negative in production code and has substantial targeted lifecycle coverage.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/cron/service/startup-run-repair.ts, unknown-data-model-change: src/cron/service/startup-run-repair.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Preserve the removed run’s terminal outcome (recommended)
    Write the terminal task event before settling its receipt and add the combined removal-plus-write-failure regression before merge.

Technical review

Best 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:

  • [P2] Record the removed run before settling its receipt — src/cron/service/ops-run.ts:268-270
    The new missing-job branch settles the receipt before emitMissingTerminal(true). finishCronRunReceipt queues a retry and throws on a database failure, so queued manual execution reaches enqueueRun’s outer catch and records an error even when the payload completed successfully. Emit the exact terminal task result first, then add the combined removal and receipt-write-failure regression.
    Confidence: 0.9

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 5c8db67a3b89.

Labels

Label changes:

  • add P2: This is a bounded scheduler and task-history correctness defect in a proposed feature.
  • add merge-risk: 🚨 session-state: The introduced error path can persist an incorrect terminal task outcome for a completed queued cron run.
  • add proof: sufficient: Contributor real behavior proof is sufficient. ClawSweeper live verification passed on the reviewed terminal surface.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦞 diamond lobster and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): ClawSweeper live verification passed on the reviewed terminal surface.

Label justifications:

  • P2: This is a bounded scheduler and task-history correctness defect in a proposed feature.
  • merge-risk: 🚨 session-state: The introduced error path can persist an incorrect terminal task outcome for a completed queued cron run.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦞 diamond lobster and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): ClawSweeper live verification passed on the reviewed terminal surface.
  • proof: sufficient: Contributor real behavior proof is sufficient. ClawSweeper live verification passed on the reviewed terminal surface.

Evidence

What I checked:

  • Current main has the prior intentional behavior: Current main marks an interrupted one-shot as failed and disables it when no replacement schedule exists; its focused restart test expects no catch-up event or heartbeat. (src/cron/service/startup-run-repair.ts:78, 5c8db67a3b89)
  • Recovery path is receipt-bound: The PR checks task history using the exact receipt, atomically persists the pending one-shot catch-up marker, then retires that receipt. (src/cron/service/run-recovery.ts:141, 59e260aa17c1)
  • Introduced terminal-status regression: The added missing-job branch calls the fallible receipt settlement before emitting the terminal task event. For queued manual runs, a settlement failure reaches the outer catch and records an error despite a completed payload. (src/cron/service/ops-run.ts:268, 59e260aa17c1)
  • Receipt settlement can throw after scheduling a retry: A failed receipt write queues a retry and rethrows, so code after the settlement call is skipped on the first attempt. (src/cron/store/run-receipt-store.ts:695, 59e260aa17c1)
  • Existing tests cover the adjacent cases separately: The lifecycle matrix covers removal and write failures, but not a removal race combined with a receipt settlement failure; the broader recovery tests cover atomic rollback and repeated restarts. (src/cron/service/run-recovery.lifecycle.test.ts:118, 59e260aa17c1)
  • Prior behavior provenance: Blame attributes the interrupted-one-shot disable boundary on current main to the earlier recovery implementation, confirming the PR is an intentional policy reversal rather than an already-fixed bug. (src/cron/service/startup-run-repair.ts:107, 9c2b86362030)

Likely related people:

  • steipete: Authored all four commits in this PR and has the largest relevant local history sample across recovery, finalization, manual-run, and repair owners. (role: recent cron recovery owner; confidence: high; commits: f35874638196, dc13a02f13d9, c0d5c66b6d0a; files: src/cron/service/ops-run.ts, src/cron/service/run-recovery.ts, src/cron/service/timer-outcome-finalization.ts)
  • Qiong: Current-main blame attributes the original interrupted-one-shot recovery and disable boundary to this contributor. (role: prior recovery implementation contributor; confidence: medium; commits: 9c2b86362030; files: src/cron/service/startup-run-repair.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

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.
@steipete
steipete force-pushed the steipete/oneshot-restart-recovery branch from 59e260a to 72f0c1b Compare August 28, 2026 04:22
@steipete
steipete merged commit 593c7ed into main Aug 28, 2026
234 checks passed
@steipete
steipete deleted the steipete/oneshot-restart-recovery branch August 28, 2026 04:38
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 28, 2026
…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.
obviyus added a commit that referenced this pull request Oct 1, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant