Skip to content

fix(cron): failing automations get a second repair turn when the error changes, or a repair instead of the final alert - #162702

Merged
obviyus merged 3 commits into
mainfrom
fix/cron-repair-streak
Oct 1, 2026
Merged

obviyus merged 3 commits into
mainfrom
fix/cron-repair-streak

Conversation

@obviyus

@obviyus obviyus commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

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 feat(cron): let a failing automation's owner conversation repair it before alerting #161007 is unchanged: the repair still takes the alert and cooldown slot, and the fallback still fires once. A persisted marker from feat(cron): let a failing automation's owner conversation repair it before alerting #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 (feat(cron): recover interrupted one-shot jobs on restart #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.

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 feat(cron): let a failing automation's owner conversation repair it before alerting #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.

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S labels Oct 1, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 1, 2026
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 1, 2026
@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 1, 2026, 10:23 AM ET / 14:23 UTC (Revision 3).

ClawSweeper review

What this changes

The cron scheduler limits automatic repair to one request per failure streak and sends failure alerts for jobs that will not run again, including during restart recovery.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary: current main retains both defects. No blocking patch findings remain, the recorded behavior and compatibility proof cover the changes, and the previous draft blocker is resolved.

Priority: P2
Reviewed head: f064aed485d39cf8b91f5a8a64c6e1d18ea86b3a

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused owner-level repair with matching before/after live observations, existing-state proof, and meaningful regressions.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The recorded Telegram Test Server run exercises the cron notification owner through a real isolated Gateway and live model: changed-cause failures produce alerts without another repair, and terminal one-shots alert directly. Separate real SQLite reopen evidence verifies older repair markers and the optional fallback field.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The recorded Telegram Test Server run exercises the cron notification owner through a real isolated Gateway and live model: changed-cause failures produce alerts without another repair, and terminal one-shots alert directly. Separate real SQLite reopen evidence verifies older repair markers and the optional fallback field.
Evidence reviewed 10 items Pinned introduced patch: Reviewed the merge-base-to-head patch. It retains the repair marker through alert cycles, adds an optional fallback marker, gates repair on enabled state, and moves existing one-shot retirement before notification selection.
Current main still needs the fix: The affected production files are unchanged between the pinned merge base and fetched main. The original alert-cycle implementation drops repair state, and repair eligibility does not exclude disabled terminal jobs.
Scheduling settles before notification selection: Normal completion finalizes notifications after retry or disable decisions. Startup recovery now likewise disables retired one-shots first while preserving replayable one-shots and operator replacements.
Findings None None.
Security None None.

How this fits together

OpenClaw's cron scheduler turns automation outcomes into persisted failure incidents and notifications. It chooses between asking the owning conversation for a repair and sending the configured failure alert.

flowchart TD
  A[Automation outcome] --> B[Scheduling and restart recovery]
  B --> C[Persisted failure incident]
  C --> D{Eligible for first repair?}
  D -->|Yes| E[Owner conversation repair]
  D -->|No| F[Failure alert policy]
  F --> G[Configured notification destination]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +8, Tests +97, Docs 0. Total +105 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 31 23 +8
Tests 1 98 1 +97
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 130 25 +105

Review metrics

Metric Value Why it matters
Persisted-state extension 1 optional fallback marker; 0 SQL migrations Recorded SQLite reopen proof covers both the older marker and the extended state.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/cron/service/failure-alerts.ts, migration/backfill/repair: src/cron/types.ts. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Technical review

Best possible solution:

Keep repair bookkeeping in the existing failure-incident owner, preserve one pending fallback for older state, and select notifications after scheduling decisions settle.

Do we have a high-confidence way to reproduce the issue?

Yes: current-main source establishes both failure paths, and the recorded before/after run exercises changed-cause failures and terminal one-shots. This reviewer did not execute target code.

Is this the best way to solve the issue?

Yes: the patch repairs the existing incident lifecycle and notification ordering without adding a competing policy owner or configuration surface.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 83a974025cbb.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: This repairs bounded automation notification defects without changing configuration or general scheduling policy.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The recorded Telegram Test Server run exercises the cron notification owner through a real isolated Gateway and live model: changed-cause failures produce alerts without another repair, and terminal one-shots alert directly. Separate real SQLite reopen evidence verifies older repair markers and the optional fallback field.
  • proof: sufficient: Contributor real behavior proof is sufficient. The recorded Telegram Test Server run exercises the cron notification owner through a real isolated Gateway and live model: changed-cause failures produce alerts without another repair, and terminal one-shots alert directly. Separate real SQLite reopen evidence verifies older repair markers and the optional fallback field.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. The change alters visible repair replies and failure alerts; the recorded Telegram Test Server evidence covers those outcomes.

Evidence

What I checked:

  • Pinned introduced patch: Reviewed the merge-base-to-head patch. It retains the repair marker through alert cycles, adds an optional fallback marker, gates repair on enabled state, and moves existing one-shot retirement before notification selection. (src/cron/service/failure-alerts.ts:254, f064aed485d3)
  • Current main still needs the fix: The affected production files are unchanged between the pinned merge base and fetched main. The original alert-cycle implementation drops repair state, and repair eligibility does not exclude disabled terminal jobs. (src/cron/service/failure-alerts.ts:253, 83a974025cbb)
  • Scheduling settles before notification selection: Normal completion finalizes notifications after retry or disable decisions. Startup recovery now likewise disables retired one-shots first while preserving replayable one-shots and operator replacements. (src/cron/service/startup-run-repair.ts:90, f064aed485d3)
  • Recorded real behavior proof: The captured PR body records an isolated Gateway with a live model and Telegram Test Server owner chat. After A failures, the fallback alert, and a changed B failure beyond cooldown, the PR head sends an alert without another repair turn; a terminal one-shot also alerts without repair. The before-fix run records both wrong behaviors. These are copied live observations, not reviewer-executed tests. (f064aed485d3)
  • Existing-state compatibility: The captured body records reopening a real SQLite store containing the older repair:{atMs} shape, delivering its pending fallback, persisting alerted:true, and reopening again with dedupe and cooldown intact. The inspected row codec serializes runtime state without a schema change; the new field is optional. (src/cron/types.ts:293, f064aed485d3)
  • Meaningful regression coverage: The changed tests exercise the real CronService through changed-cause failures, successful streak reset, and scheduled one-shot retry exhaustion. The startup matrix separately protects notification ordering for recurring, replayable, and retired jobs. The body reports 15 tests in 30.7 seconds total, approximately 16 seconds of test execution. Tests were inspected but not executed during this read-only review. (src/cron/service.failure-repair.test.ts:94, f064aed485d3)

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-01T13:12:32.589Z sha f064aed :: blocked before merge. :: none
  • reviewed 2026-10-01T14:13:29.752Z sha f064aed :: needs changes before merge. :: none

@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Oct 1, 2026
@obviyus
obviyus marked this pull request as ready for review October 1, 2026 14:18
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 1, 2026
@obviyus
obviyus merged commit e35e859 into main Oct 1, 2026
224 of 225 checks passed
@obviyus
obviyus deleted the fix/cron-repair-streak branch October 1, 2026 15:45
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Landed after the full landing checklist on the exact head: adversarial review LAND, ClawSweeper ready, live Telegram before/after proof in the PR body (one repair per failure streak; a terminal one-shot keeps its alert), full CI green, bounded cost, and no new user-visible messages.

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]>
obviyus added a commit that referenced this pull request Oct 9, 2026
…ry is pending (#167957)

Related: #161007, #162702, #162772

## Problem

A recurring automation that hits a short provider outage (DNS failure, refused connection, 5xx, overload, rate limit) spends its one owner-conversation repair request, or sends a failure alert, at failure 2, while the scheduler's quick retry is still pending and the provider is still down. The next failure then sends the normal alert even if the outage has already ended.

## Solution

`applyJobResult` (`src/cron/service/timer-outcomes.ts`) already decides whether a transient error gets another run. It now records that decision as `pendingTransientRetry` and passes it to `finalizeCronFailureNotifications` (`src/cron/service/failure-alerts.ts`), which skips the alert and the owner repair for that cycle. Incident and unresolved-failure bookkeeping still run, so a success during the hold clears the incident silently.

The hold is bounded:

- Only while the transient retry budget remains (`DEFAULT_MAX_TRANSIENT_RETRIES`, 3), whichever path schedules the next run: the dedicated quick retry, or ordinary backoff on short-interval jobs (for example every minute) whose next slot comes first. Schedule length never extends it.
- Never when no next run exists: a disabled job, a one-shot retired after its retries, or a schedule with no future slot (`nextRunAtMs` undefined).
- Never for failures the job causes itself: cron's own execution watchdog timeout (`isCronTimeoutErrorText`), script failures (including script timeouts), and command-job timeouts. This keeps the #161007 case: a slow helper script is still repaired at failure 2.

Provider transport failures have no `network` failover reason: `ECONNREFUSED`, `EAI_AGAIN`, `fetch failed` and similar classify as `timeout` (`src/agents/failover/message-patterns.ts:180` and `:204`), and that structured reason is authoritative for the cron retry category (`src/cron/retry-hint.ts:62`). So the predicate (`holdsFailureNotificationForRetry`, `src/cron/service/timer-trigger.ts`) cannot exclude the `timeout` category wholesale; it excludes the job-owned cases above.

Docs: `docs/automation/cron-jobs/delivery.md` and `docs/cli/cron.md` describe the hold and its bounds.

## Impact

- During a provider outage the scheduler runs its quick retries (30s, 1m, 5m) first. If one succeeds, nothing is sent. If all fail, the owned job gets one repair request (unowned: one alert) with the full failure count.
- Upgrade behavior: notifications for provider outages arrive after the retry budget is used up, about 6.5 minutes after the first failure (failure 4), instead of at failure 2. No config key, schema, or stored-state change.
- Job-caused failures (watchdog timeout, script failures, command timeouts) keep their current timing.

No overlap with Pash/Sarah changes.

## Evidence

Unit (`src/cron/service.failure-repair.test.ts`):

- Owned hourly, unowned hourly, and owned every-minute jobs with a DNS failure: 0 repairs and 0 alerts through failure 3; failure 4 sends one repair (owned, brief says "failed 4") or one alert (unowned).
- A success during the hold clears the incident and sends nothing.
- Provider `ECONNREFUSED` (`lastErrorReason: timeout`) is held; cron watchdog timeout and helper-script timeout still repair at failure 2.
- Bounds: a weekly job past the budget repairs; a one-shot retired after the budget alerts; a disabled job and a cron schedule with no future slot (both within the budget, `nextRunAtMs` undefined) are not held.
- The hold rows fail on origin/main; the every-minute row also fails on this PR's first revision.
- `pnpm test src/cron`: 238 files, 2318 tests passed. `node scripts/check-changed.mjs`: green.

Real Gateway (QA lab, mock provider dropping the TCP connection for the job's model requests, owned `every 1h` job, `fallbacks: []`, scheduled runs only):

| Build | Failures (from job creation) | After failure 3 | After failure 4 |
| --- | --- | --- | --- |
| This PR | +96s, +206s, +350s, +739s | 0 repairs, 0 alerts | 1 repair ("failed 4 consecutive runs"), 0 alerts |
| origin/main | same ladder | 1 repair + 1 alert | n/a |

Telegram Test Server (Convex-leased credential, isolated Gateway built from each tree, `scripts/e2e/mock-openai-server.mjs` behind a front that drops the TCP connection for the job's model requests; no live model). Each run created its own forum supergroup and topic, ran the owner turn in the topic, added an owned `every 1h` job whose owner is that topic session and whose delivery and alerts target it (`failureAlert: { after: 2, cooldownMs: 0 }`, `fallbacks: []`), then deleted the forum. Times are seconds after job creation; message IDs are the observer's IDs in that run's topic.

| Build | Job failures | SUT messages in the topic after job creation |
| --- | --- | --- |
| This PR (d6cd8ee) | +81s, +190s, +320s, +689s | none through failure 3 and up to failure 4 (about 11.5 min); then msg 6 at +700s, the owner repair turn's reply. No alert. |
| origin/main (ea6022c) | +68s, +185s, +316s | msg 6 at +228s (repair turn's reply after failure 2), msg 7 at +355s (failure alert after failure 3: `Automation "tg-cron-outage-proof" failed 3 times ... An automatic repair was requested in its owner conversation; it is still failing.`) |

In both runs the only earlier SUT message is msg 5, the reply to the topic owner turn, and the mock saw the same repair-turn request shape (one repair turn). Dropped connections: 30 (this PR, 4 runs), 22 (origin/main, 3 runs).

Merge danger: two-way door. It only changes when notifications are sent, writes no new state, and a revert restores the old timing. Blast radius: cron failure alerts and owner repair requests for transient provider failures. If the classification is wrong, those notifications are delayed by up to about 6.5 minutes; they are not lost.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
…ry is pending (openclaw#167957)

Related: openclaw#161007, openclaw#162702, openclaw#162772

## Problem

A recurring automation that hits a short provider outage (DNS failure, refused connection, 5xx, overload, rate limit) spends its one owner-conversation repair request, or sends a failure alert, at failure 2, while the scheduler's quick retry is still pending and the provider is still down. The next failure then sends the normal alert even if the outage has already ended.

## Solution

`applyJobResult` (`src/cron/service/timer-outcomes.ts`) already decides whether a transient error gets another run. It now records that decision as `pendingTransientRetry` and passes it to `finalizeCronFailureNotifications` (`src/cron/service/failure-alerts.ts`), which skips the alert and the owner repair for that cycle. Incident and unresolved-failure bookkeeping still run, so a success during the hold clears the incident silently.

The hold is bounded:

- Only while the transient retry budget remains (`DEFAULT_MAX_TRANSIENT_RETRIES`, 3), whichever path schedules the next run: the dedicated quick retry, or ordinary backoff on short-interval jobs (for example every minute) whose next slot comes first. Schedule length never extends it.
- Never when no next run exists: a disabled job, a one-shot retired after its retries, or a schedule with no future slot (`nextRunAtMs` undefined).
- Never for failures the job causes itself: cron's own execution watchdog timeout (`isCronTimeoutErrorText`), script failures (including script timeouts), and command-job timeouts. This keeps the openclaw#161007 case: a slow helper script is still repaired at failure 2.

Provider transport failures have no `network` failover reason: `ECONNREFUSED`, `EAI_AGAIN`, `fetch failed` and similar classify as `timeout` (`src/agents/failover/message-patterns.ts:180` and `:204`), and that structured reason is authoritative for the cron retry category (`src/cron/retry-hint.ts:62`). So the predicate (`holdsFailureNotificationForRetry`, `src/cron/service/timer-trigger.ts`) cannot exclude the `timeout` category wholesale; it excludes the job-owned cases above.

Docs: `docs/automation/cron-jobs/delivery.md` and `docs/cli/cron.md` describe the hold and its bounds.

## Impact

- During a provider outage the scheduler runs its quick retries (30s, 1m, 5m) first. If one succeeds, nothing is sent. If all fail, the owned job gets one repair request (unowned: one alert) with the full failure count.
- Upgrade behavior: notifications for provider outages arrive after the retry budget is used up, about 6.5 minutes after the first failure (failure 4), instead of at failure 2. No config key, schema, or stored-state change.
- Job-caused failures (watchdog timeout, script failures, command timeouts) keep their current timing.

No overlap with Pash/Sarah changes.

## Evidence

Unit (`src/cron/service.failure-repair.test.ts`):

- Owned hourly, unowned hourly, and owned every-minute jobs with a DNS failure: 0 repairs and 0 alerts through failure 3; failure 4 sends one repair (owned, brief says "failed 4") or one alert (unowned).
- A success during the hold clears the incident and sends nothing.
- Provider `ECONNREFUSED` (`lastErrorReason: timeout`) is held; cron watchdog timeout and helper-script timeout still repair at failure 2.
- Bounds: a weekly job past the budget repairs; a one-shot retired after the budget alerts; a disabled job and a cron schedule with no future slot (both within the budget, `nextRunAtMs` undefined) are not held.
- The hold rows fail on origin/main; the every-minute row also fails on this PR's first revision.
- `pnpm test src/cron`: 238 files, 2318 tests passed. `node scripts/check-changed.mjs`: green.

Real Gateway (QA lab, mock provider dropping the TCP connection for the job's model requests, owned `every 1h` job, `fallbacks: []`, scheduled runs only):

| Build | Failures (from job creation) | After failure 3 | After failure 4 |
| --- | --- | --- | --- |
| This PR | +96s, +206s, +350s, +739s | 0 repairs, 0 alerts | 1 repair ("failed 4 consecutive runs"), 0 alerts |
| origin/main | same ladder | 1 repair + 1 alert | n/a |

Telegram Test Server (Convex-leased credential, isolated Gateway built from each tree, `scripts/e2e/mock-openai-server.mjs` behind a front that drops the TCP connection for the job's model requests; no live model). Each run created its own forum supergroup and topic, ran the owner turn in the topic, added an owned `every 1h` job whose owner is that topic session and whose delivery and alerts target it (`failureAlert: { after: 2, cooldownMs: 0 }`, `fallbacks: []`), then deleted the forum. Times are seconds after job creation; message IDs are the observer's IDs in that run's topic.

| Build | Job failures | SUT messages in the topic after job creation |
| --- | --- | --- |
| This PR (d6cd8ee) | +81s, +190s, +320s, +689s | none through failure 3 and up to failure 4 (about 11.5 min); then msg 6 at +700s, the owner repair turn's reply. No alert. |
| origin/main (4752147) | +68s, +185s, +316s | msg 6 at +228s (repair turn's reply after failure 2), msg 7 at +355s (failure alert after failure 3: `Automation "tg-cron-outage-proof" failed 3 times ... An automatic repair was requested in its owner conversation; it is still failing.`) |

In both runs the only earlier SUT message is msg 5, the reply to the topic owner turn, and the mock saw the same repair-turn request shape (one repair turn). Dropped connections: 30 (this PR, 4 runs), 22 (origin/main, 3 runs).

Merge danger: two-way door. It only changes when notifications are sent, writes no new state, and a revert restores the old timing. Blast radius: cron failure alerts and owner repair requests for transient provider failures. If the classification is wrong, those notifications are delayed by up to about 6.5 minutes; they are not lost.

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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant