Skip to content

fix(cron): skip deleteAfterRun and preserve counters for manual runs (#83538) - #83933

Closed
Jerry-Xin wants to merge 19 commits into
openclaw:mainfrom
Jerry-Xin:fix/cron-delete-after-run-manual-83538
Closed

Jerry-Xin wants to merge 19 commits into
openclaw:mainfrom
Jerry-Xin:fix/cron-delete-after-run-manual-83538

Conversation

@Jerry-Xin

@Jerry-Xin Jerry-Xin commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

openclaw cron run (a manual/operator run) on a deleteAfterRun one-shot ("at") job used to delete the job on success — consuming the one-shot so its scheduled fire never happened (issue #83538). Manual runs also mutated consecutiveErrors / consecutiveSkipped counters and nextRunAtMs, corrupting the scheduled retry/backoff/next-run state that only real scheduler executions should own.

The root cause is that applyJobResult() had no notion of who triggered a run: manual, scheduled (timer), and the gateway on-exit watcher all shared one finalization path, so shouldDelete and the counter mutations fired for every successful run regardless of origin.

Why This Change Was Made

The fix threads an explicit CronRunOrigin ("timer" | "watcher-terminal" | "operator") through cron finalization. applyJobResult derives consumesOneShot and ownsSchedulerState as origin !== "operator" and records lastRunWasManual = origin === "operator", so operator runs record the outcome only (never consume a deleteAfterRun one-shot, never touch scheduler counters / nextRunAtMs / enabled state), while timer and watcher-terminal runs keep consuming and owning scheduler state — preserving the merged on-exit deleteAfterRun contract from #104550.

origin is kept strictly internal. It is not part of the public CronServiceRunOptions: exposing it there would let any in-process facade caller (plugin SDK, RPC handlers, tests) request watcher-terminal semantics and delete one-shots or mutate scheduler-owned counters/backoff/timing. Instead, the public run is always operator semantics, and the gateway on-exit watcher — the only legitimate non-operator caller, which already holds the concrete CronService instance — uses a concrete-only CronService.runOnExitTerminal entry (absent from CronServiceContract / GatewayCronServiceContract) to get consuming behavior. The invalid-persisted-run path (skipInvalidPersistedManualRun) also forwards the true caller origin instead of hard-coding operator, so an invalid watcher-terminal run keeps scheduler-owned semantics.

User Impact

  • Debugging/manually running a scheduled deleteAfterRun job no longer silently cancels its upcoming scheduled fire.
  • Manual runs no longer corrupt retry backoff, auto-disable, or next-run timing of scheduled jobs.
  • Gateway on-exit watcher-terminal one-shots continue to be consumed exactly as before (no regression for the fix(cron): delete successful on-exit deleteAfterRun jobs #104550 contract).
  • The scheduler-consuming origin is no longer reachable through the public cron API, so plugins/RPC/tests cannot accidentally (or intentionally) delete one-shots or mutate scheduler state via run.

Evidence

Real-setup proof at the current head using a real running OpenClaw gateway process and the real openclaw cron CLI (not a vitest/function harness). Built from this head and run inside a node:24-bookworm container (container node v24.18.0; the repo engines floor is 24.15.0), against a real on-disk cron store (sqlite).

Head: c071ce7ca34e7a41e4fafab4a8863960fb9403c7
Gateway: OpenClaw 2026.7.2 (c071ce7)   dist/build-info.json commit = c071ce7c...

Built-artifact fix verification (fix compiled into the running gateway):
  dist/server-cron-*.js contains:
    async runOnExitTerminal(id, payload) { ... }
    run: (jobId, payload) => cron.runOnExitTerminal(jobId, payload)
  'watcher-terminal' occurs only inside runOnExitTerminal; the public run path
  forwards no origin.

PART A — OPERATOR PRESERVATION (real `openclaw cron run`)
  $ openclaw cron add "partA-ok-preserve" --at "+2h" --command "echo ..." --delete-after-run
    -> id 3c309f88..., nextRunAtMs 1784045230759
  $ openclaw cron run 3c309f88... --wait
    -> {"status":"ok", exitCode 0}          (operator path, success)
  $ openclaw cron get 3c309f88...
    -> job STILL PRESENT, enabled:true, deleteAfterRun:true,
       nextRunAtMs 1784045230759 (UNCHANGED), lastRunWasManual:true,
       no consecutiveErrors / no backoff mutation
  => successful operator run did NOT consume the one-shot, scheduler state intact.

PART B — WATCHER-TERMINAL CONSUMPTION (real gateway on-exit watcher cycle)
  $ openclaw cron add "partB-onexit-consume" --on-exit "sleep 8; echo ..." \
        --command "echo ..." --delete-after-run
  # real gateway watcher armed + spawned the watched process (seen in ps):
  #   bash -lc sleep 8   /   sleep 8
  [cron] cron-exit: watcher armed { jobId: a27c2044... }
  [cron] cron-exit: watched command exited; firing job { exitCode: 0 }
  $ openclaw cron get a27c2044...      -> "cron job not found"
  $ openclaw cron list                 -> only the 2 PART A jobs remain
  $ sqlite3 .../openclaw.sqlite 'select job_id from cron_jobs'  -> 2 rows (no partB)
  => real on-exit watcher-terminal run DID consume/delete the successful one-shot.

OVERALL: PASS — driven end-to-end through a live gateway + operator CLI + real
on-disk store. Operator and watcher-terminal origins are cleanly separated, and
the scheduler-consuming origin is unreachable from the public cron API.

Unit/regression coverage at head: the public CronServiceContract.run preserves a deleteAfterRun one-shot (operator semantics, no scheduler-state mutation) even though it can no longer request another origin, CronService.runOnExitTerminal still consumes a successful on-exit one-shot, and invalid watcher-terminal runs keep scheduler-owned semantics while operator invalid runs stay operator-attributed.

Persisted-state coverage for lastRunWasManual (timer.backoff-config-readback.test.ts, real on-disk sqlite store): a fresh store where a manual/operator error run persists lastRunWasManual: true, reloads from sqlite, and keeps the natural next-run slot (no backoff floor, consecutiveErrors untouched) so the scheduled fire still triggers on a fresh service state; and an upgraded store whose persisted job predates the field (no lastRunWasManual on disk) — on reload the absent field is treated as a scheduled run, so the error backoff window still applies and the past-due slot is correctly suppressed. This proves the new optional field degrades safely for both new and pre-existing stores.

Proof equivalence: transcript head → current head

The live-setup transcript above was captured at c071ce7c. The branch head has since been rebased onto newer main (current head c42041b0). Scoped to the cron runtime surface exercised by the transcript (src/cron/service/, src/gateway/server-cron.ts), the full non-test delta between c071ce7c and the current head is:

  • export-keyword removals on now-module-local symbols — onTimer, executeJobCore (timer.ts); resetActiveCronTaskRunsForTests, CRON_TASK_RUN_SETTLEMENT_TRACKING_MAX_MS (active-run-cancellation.ts); DEFAULT_JOB_TIMEOUT_MS, AGENT_TURN_SAFETY_TIMEOUT_MS (timeout-policy.ts). Values and in-module usage unchanged; no prod file outside each defining module imported them.
  • test-support extraction — timer.ts and active-run-cancellation.ts now expose those test-only helpers via a globalThis symbol registered inside an if (process.env.VITEST || process.env.NODE_ENV === "test") guard, imported by new *.test-support.ts modules. This block is a no-op in a production gateway.
  • four appended /* oxlint-disable max-lines */ directive comments (jobs.ts, ops.ts, timer.ts, server-cron.ts).
  • rebased-in main change fix(cron): cap trigger script tool access #104430 ("cap trigger script tool access") — mergeCronPayload and its toolsAllow helpers moved out of jobs.ts into the new src/cron/service/payload-merge.ts, with cross-payload-kind toolsAllow marker handling. This is genuine upstream behavior on the cron.update payload-merge / trigger-script tool-access surface, disjoint from scheduler counters and one-shot consumption; it arrived through the rebase and is not part of this PR's proof scope.
  • server-cron.ts toolsAllow type-guard simplification — the trigger-script call now reads job.payload.toolsAllow directly (valid once fix(cron): cap trigger script tool access #104430 lifted toolsAllow to a shared CronPayload field) instead of gating on kind === "agentTurn". This is on the trigger-script tool-access path, not the runOnExitTerminal / delete-after-run wiring.

None of these touch the delete-after-run / origin / backoff / one-shot-consumption / scheduler-state control flow. The CronRunOrigin threading, consumesOneShot / ownsSchedulerState (origin !== "operator"), lastRunWasManual (origin === "operator"), shouldDelete = wouldDelete && consumesOneShot in timer.ts, the ops.ts origin forwarding, and the runOnExitTerminal wiring in server-cron.ts are unchanged. The recorded operator-preservation and watcher-terminal-consumption behavior therefore holds on the current head. Reviewers can confirm the delta with:

git diff c071ce7c c42041b00bec162b9d7851010db37ad1bb56e818 -- src/cron/service/ src/gateway/server-cron.ts

Follow-up fix: manual ok run must not strand the one-shot slot

A further defect on the same origin-threading surface: a due deleteAfterRun one-shot at job that receives an operator (manual) ok run keeps its nextRunAtMs preserved (operator runs do not consume the one-shot), but computeJobNextRunAtMs's at-branch collapsed the pending slot to undefined whenever the last run status was ok. The next expired-slot maintenance recompute then wiped the slot, stranding the job as a zombie that never fires and never deletes. Existing coverage only exercised skipped runs, so the ok path was missed.

Fix: the ok-branch collapse in computeJobNextRunAtMs is now guarded by lastRunWasManual !== true, so only a scheduler-owned (timer) ok run retires the slot; manual/operator ok runs leave the pending scheduled fire intact. This reuses the already-persisted lastRunWasManual field, so it is restart-safe with no new state or migration (an absent field on a pre-upgrade store is treated as a scheduled run, preserving prior behavior). A regression test drives a manual ok run on a due deleteAfterRun one-shot through the maintenance recompute and a restart reload (slot preserved both times), then a real scheduled timer tick that fires and deletes it.

@openclaw-barnacle openclaw-barnacle Bot added size: S triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 19, 2026
@clawsweeper

clawsweeper Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 27, 2026, 12:36 AM ET / 04:36 UTC.

ClawSweeper review

What this changes

The PR separates operator, timer, and gateway on-exit cron execution so manual runs preserve scheduled one-shots while scheduler-owned executions retain deletion and rescheduling behavior.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 6 items remain

Keep this PR open. The origin split is a strong boundary for preventing manual runs from consuming one-shot jobs, but the current error path still lets an operator failure contribute to scheduler retry accounting; a later timer failure can therefore inherit an inflated error count. The supplied live proof also predates the final-head error-accounting change, so it does not yet demonstrate the behavior that needs to merge safely.

Likely related people: yetval is the strongest routing candidate from recent merged cron scheduling and persistence work; confidence is medium.

Priority: P1
Reviewed head: 74f2385748eac428ddf9a22cda3bb42b1d3d7e4a

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The branch has meaningful live evidence and targeted coverage, but the mixed-origin retry-state defect and stale proof prevent merge readiness.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: The PR includes credible terminal evidence from a live gateway, CLI, and SQLite store, but it is tied to c071ce7c and does not show the final-head manual-error then timer-error behavior introduced later; provide redacted final-head terminal output before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The PR includes credible terminal evidence from a live gateway, CLI, and SQLite store, but it is tied to c071ce7c and does not show the final-head manual-error then timer-error behavior introduced later; provide redacted final-head terminal output before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 5 items Origin separation is implemented in the proposed branch: The changed finalization entry accepts a run origin, treats operator runs differently from timer and watcher-terminal runs, and persists whether the last run was manual; this is the correct area for the one-shot preservation fix.
Persisted-state contract changed: The branch adds optional lastRunWasManual state to both the runtime cron type and gateway protocol schema, making later scheduler decisions depend on the origin of the prior execution.
Manual error and scheduler retry semantics conflict: The branch explicitly changed manual failures to retain consecutiveErrors while suppressing their immediate backoff. A subsequent timer-origin failure can therefore use the retained manual error as part of its scheduled retry count, contrary to the PR's stated non-consuming manual-run contract.
Findings 1 actionable finding [P1] Exclude operator failures from scheduler retry counters
Security None None.

How this fits together

OpenClaw's cron service persists scheduled jobs and their execution state, while the gateway exposes both operator-triggered runs and scheduler/on-exit triggers. Finalization updates job status, retry state, next-run timing, and deletion, which then determines what the next scheduler tick can execute.

flowchart LR
  A[Operator CLI or RPC] --> B[Cron service]
  C[Timer scheduler] --> B
  D[Gateway on-exit watcher] --> B
  B --> E[Run-origin finalization]
  E --> F[Persisted cron job state]
  F --> G[Next scheduler tick]
  E --> H[Job removal or retry outcome]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The PR includes credible terminal evidence from a live gateway, CLI, and SQLite store, but it is tied to c071ce7c and does not show the final-head manual-error then timer-error behavior introduced later; provide redacted final-head terminal output before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Exclude operator failures from scheduler retry counters (P1) - The new operator path still records consecutiveErrors, while only resolveJobErrorBackoffUntilMs ignores it when lastRunWasManual is true. Once the next timer run fails, it clears that flag and consumes the retained manual count, so a manual verification error becomes scheduled retry history and can accelerate backoff or auto-disable. Preserve the scheduler counters across operator failures, or maintain separate operator-only observability state.
  • Resolve merge risk (P1) - A failed manual verification run can still increase the retry count later consumed by a timer-origin failure, causing stronger backoff or earlier scheduler-side disablement than the scheduled history alone warrants.
  • Resolve merge risk (P1) - The available live proof predates the final error-accounting behavior, so merge would rely on source reasoning and tests rather than a demonstrated final-head operator-to-scheduler transition.
  • Improve patch quality - Preserve scheduler retry counters across manual/operator failures and add a focused mixed-origin regression.
  • Improve patch quality - Post redacted final-head terminal proof showing manual error followed by timer error, with scheduler backoff based only on timer-origin history.

Findings

  • [P1] Exclude operator failures from scheduler retry counters — src/cron/service/timer-outcomes.ts:50-80
Agent review details

Security

None.

PR surface

Source +140, Tests +1811. Total +1951 across 22 files.

View PR surface stats
Area Files Added Removed Net
Source 11 371 231 +140
Tests 11 2423 612 +1811
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 22 2794 843 +1951

Review metrics

Metric Value Why it matters
Persisted cron state 1 optional state field added lastRunWasManual becomes durable scheduler input, so fresh-store and upgraded-store behavior must remain compatible.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #83538
Summary: This PR is the active candidate fix for the reported manual-run deletion and scheduler-state corruption problem.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Restore scheduler-counter isolation (recommended)
    Keep manual failure reporting if desired, but prevent an operator run from changing the retry counter or disable threshold consumed by later timer runs, and add a regression for the mixed-origin sequence.
  2. Accept shared failure accounting
    Land the current behavior only if maintainers explicitly want manual verification failures to count toward scheduled retry and auto-disable policy.
  3. Pause for a narrower cron contract
    Pause this broad branch if the intended distinction between observable manual failures and scheduler-owned retry history cannot be settled with a focused compatibility contract.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Preserve scheduler retry counters across operator failures; add a mixed-origin regression proving a following timer failure starts from scheduler-only history.

Technical review

Best possible solution:

Keep operator outcomes observable, but preserve scheduler-owned retry counters and retry/disable thresholds across operator runs; then add final-head live proof showing a manual error followed by a timer error uses only scheduled failure history.

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

No fresh runtime reproduction was executed in this read-only review, but the affected mixed-origin path is high-confidence source-reproducible from the changed finalization and retry-state logic.

Is this the best way to solve the issue?

No. Separating origins is the right fix boundary, but the patch must also keep operator failures out of scheduler retry history rather than only suppressing their immediate backoff.

Full review comments:

  • [P1] Exclude operator failures from scheduler retry counters — src/cron/service/timer-outcomes.ts:50-80
    The new operator path still records consecutiveErrors, while only resolveJobErrorBackoffUntilMs ignores it when lastRunWasManual is true. Once the next timer run fails, it clears that flag and consumes the retained manual count, so a manual verification error becomes scheduled retry history and can accelerate backoff or auto-disable. Preserve the scheduler counters across operator failures, or maintain separate operator-only observability state.
    Confidence: 0.91

Overall correctness: patch is incorrect
Overall confidence: 0.89

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: A manual operator action can alter retry behavior of the next real scheduled execution, affecting an active cron workflow.
  • merge-risk: 🚨 compatibility: The branch changes the established meaning of manual cron run and adds persisted state that affects upgrades and later execution behavior.
  • merge-risk: 🚨 session-state: Cron execution outcome fields and retry counters are persisted job state that determine future scheduler decisions.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR includes credible terminal evidence from a live gateway, CLI, and SQLite store, but it is tied to c071ce7c and does not show the final-head manual-error then timer-error behavior introduced later; provide redacted final-head terminal output before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/cron/service/timer.regression.test.ts src/cron/service/ops.regression.origin.test.ts.
  • [P1] node scripts/run-vitest.mjs src/cron/service/timer.backoff-config-readback.test.ts.
  • [P1] node scripts/check-changed.mjs -- src/cron/service/timer-outcomes.ts src/cron/service/jobs.ts src/cron/service/timer.regression.test.ts src/cron/service/ops.regression.origin.test.ts.

What I checked:

  • Origin separation is implemented in the proposed branch: The changed finalization entry accepts a run origin, treats operator runs differently from timer and watcher-terminal runs, and persists whether the last run was manual; this is the correct area for the one-shot preservation fix. (src/cron/service/timer-outcomes.ts:50, 74f2385748ea)
  • Persisted-state contract changed: The branch adds optional lastRunWasManual state to both the runtime cron type and gateway protocol schema, making later scheduler decisions depend on the origin of the prior execution. (packages/gateway-protocol/src/schema/cron.ts:475, 74f2385748ea)
  • Manual error and scheduler retry semantics conflict: The branch explicitly changed manual failures to retain consecutiveErrors while suppressing their immediate backoff. A subsequent timer-origin failure can therefore use the retained manual error as part of its scheduled retry count, contrary to the PR's stated non-consuming manual-run contract. (src/cron/service/timer-outcomes.ts:50, 74f2385748ea)
  • Final-head proof is incomplete: The live gateway/CLI/SQLite transcript is pinned to c071ce7c, while the current head is 74f2385 and later commits materially changed manual error accounting. The previous ClawSweeper review specifically requested the manual-error then timer-error sequence, and no matching final-head transcript is present in the supplied context. (74f2385748ea)
  • Adjacent ownership history: Recent merged cron fixes established the surrounding scheduling-maintenance and persisted next-run invariants, including the add/remove and update fixes. (src/cron/service/jobs.ts:624, e38d64c5f88b)

Likely related people:

  • yetval: Authored merged cron scheduling-maintenance fixes that established the nearby due-slot and persisted next-run invariants this change extends. (role: recent area contributor; confidence: medium; commits: c854e4e93f06, e38d64c5f88b; files: src/cron/service/jobs.ts, src/cron/service/ops.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.

History

Review history (75 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-20T07:10:08.043Z sha 5e7feef92cf80bfec420553b550ec9248edee635 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-20T08:28:11.726Z sha 5e7feef92cf80bfec420553b550ec9248edee635 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-20T10:12:55.686Z sha 1d7593908564c0d620a124efbd9a680a3801cf80 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-25T10:18:48.725Z sha 598188a0623d2aa825bafaf1f01a4fd71d762dee :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-26T04:35:08.542Z sha 31b1173201aca304acebb9c8f66e6d72771480b0 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-26T07:55:44.109Z sha d8ac00735e2ef68735d2476cf964c2c498b39a6c :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-26T13:31:49.271Z sha c42988697a7e3c1d3217db6ccde1dabfbb79e402 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-26T19:21:52.227Z sha bcb2c29ece4f50008e46c54f2fe2250727c918af :: needs real behavior proof before merge. :: [P1] Keep manual errors out of scheduler retry counters

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels May 19, 2026
@Jerry-Xin
Jerry-Xin force-pushed the fix/cron-delete-after-run-manual-83538 branch from c0a3f5e to 6c8fdf9 Compare May 19, 2026 04:27
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Addressed the P1 finding in 6c8fdf9 — the manual-run guard now covers error outcomes too.

Changes:

  • Wrapped the one-shot at-job error branch with an isManual guard so manual runs no longer rewrite nextRunAtMs (transient error) or disable the job (permanent error)
  • When isManual is true and the result is error, the consecutiveErrors increment is reversed to avoid polluting the scheduled fire's error tracking
  • Added two regression tests: manual transient error preserves nextRunAtMs, manual permanent error preserves enabled state

Also rebased on latest upstream/main (d60ab48, clean rebase, no conflicts).

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels May 19, 2026
@Jerry-Xin
Jerry-Xin force-pushed the fix/cron-delete-after-run-manual-83538 branch 2 times, most recently from cf72fb7 to d8f7ed5 Compare May 19, 2026 10:06
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased on latest upstream/main (5e0850f, clean rebase, no conflicts).

@Jerry-Xin
Jerry-Xin force-pushed the fix/cron-delete-after-run-manual-83538 branch 2 times, most recently from 4eb14e6 to 3155142 Compare May 19, 2026 14:06
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased on latest upstream/main (b7ba7c3, clean rebase, no conflicts).

@Jerry-Xin
Jerry-Xin force-pushed the fix/cron-delete-after-run-manual-83538 branch from 3155142 to ebf32fe Compare May 19, 2026 16:07
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased on latest upstream/main (48acdd3, clean rebase, no conflicts).

@Jerry-Xin
Jerry-Xin force-pushed the fix/cron-delete-after-run-manual-83538 branch from ebf32fe to 37d24fb Compare May 19, 2026 18:05
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased on latest upstream/main (94d8391, clean rebase, no conflicts).

@Jerry-Xin
Jerry-Xin force-pushed the fix/cron-delete-after-run-manual-83538 branch 3 times, most recently from d505c29 to 734f827 Compare May 20, 2026 00:05
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased on latest upstream/main (79197b3, clean rebase, no conflicts).

@clawsweeper

clawsweeper Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg: 🔥 warming; proof passed, review follow-up or readiness checks remain. Hatch with @clawsweeper hatch when eligible.

Rules and details

Hatchability:

  • Merged PRs are hatchable.
  • Open PRs are hatchable when they are status: 👀 ready for maintainer look, status: 🚀 automerge armed, or labeled clawsweeper:automerge.
  • Closed unmerged PRs are hatchable only when one of those hatchable labels is still present in the durable record.

About:

  • Eggs appear after real-behavior proof passes. They are collectible flavor only.
  • Review momentum changes the shell state: follow-up work warms it, re-review makes it wobble, and a clean final review lets it hatch.
  • The hatch is seeded from this repository and PR number, so the same PR keeps the same creature; the reviewed head SHA can only change safe visual details.
  • Rarity is just collectible sparkle: 🥚 common, 🌱 uncommon, 💎 rare, ✨ glimmer, and 🌈 legendary.

@Jerry-Xin
Jerry-Xin force-pushed the fix/cron-delete-after-run-manual-83538 branch from 734f827 to 16e917a Compare May 20, 2026 02:06
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased on latest upstream/main (a002c41, clean rebase, no conflicts).

@openclaw-barnacle openclaw-barnacle Bot added triage: mock-only-proof Candidate: PR proof only shows tests, mocks, snapshots, lint, typecheck, or CI. and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 20, 2026
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased onto latest upstream/main (clean, no conflicts); the prior retry-config typing fix rebased in cleanly and src/cron lint/typecheck is green. @clawsweeper re-review

@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased onto latest upstream/main (clean, no conflicts); src/cron lint/typecheck stays green. @clawsweeper re-review

1 similar comment
@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased onto latest upstream/main (clean, no conflicts); src/cron lint/typecheck stays green. @clawsweeper re-review

@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased on latest upstream/main (bb657ee). Upstream split src/cron/service/timer.ts into per-concern modules (timer-execution / timer-scheduler / timer-outcomes / timer-catchup); relocated the manual-run preservation logic into timer-outcomes.ts (applyJobResult) accordingly, keeping the origin-threaded behavior intact. Clean local lint on src/cron (no new errors). @clawsweeper re-review

@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased on latest upstream/main (9d2d5d1), clean rebase, no conflicts. @clawsweeper re-review

@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Fixed CI (check-lint / check-test-types / node-compact-small shards) that went red after rebasing onto upstream's removal of the configurable cron.retry and maxConcurrentRuns knobs. resolveRetryConfig() and resolveRunConcurrency() now use built-in defaults, so the tests still referencing cronConfig.retry / cronConfig.maxConcurrentRuns no longer type-checked. Removed the test cases whose sole purpose was asserting the removed knobs (their default behavior is already covered by the sibling retry-hint and one-shot-disable tests) and dropped the now-invalid config fields from the remaining tests whose assertions still hold under the defaults. oxfmt --check clean; node scripts/run-lint.mjs src/cron reports 0 src/cron errors; targeted vitest on both touched files: 111 passed / 0 failed. @clawsweeper re-review

@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased onto latest upstream/main. The rebase surfaced a regression from the upstream cron refactor: the manual-run origin gate had become too broad and was suppressing error accounting (consecutiveErrors, lastRunStatus=error, failure alerts) for manual runs. Narrowed the gate so only scheduler-consuming success/lifecycle state (deleteAfterRun, one-shot disable-on-success, next-run advance, retry-backoff scheduling) stays non-consuming for manual runs, while error counters, failure-alert emission, and evaluated trigger gate state are recorded for all origins. Full cron suite green (1666/1666). @clawsweeper re-review

@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Rebased on latest upstream/main (ec06118). Upstream split src/cron/service/ops.ts into a facade re-exporting from ops-lifecycle.ts / ops-read.ts / ops-mutations.ts / ops-run.ts / ops-run-preparation.ts, removed the configurable cron.retry knob (now built-in defaults), and reshaped the failure-alert path. Reconciled the origin-threaded manual-run changes into the new split modules: threaded CronRunOrigin and preserveExpiredPacedSlot through ops-run-preparation.ts/ops-run.ts, kept operator-run paced-slot preservation aligned with upstream's origin-based applyJobResult, and adopted the zero-arg resolveRetryConfig(). One test (service.failure-alert.test.ts owned-destination skip-alert case) was updated to drive its skip through the scheduler path so it exercises the intended scheduler-owned invariant rather than an operator run. New head 31b1173201. tsgo:core, tsgo:test:src, and the full src/cron suite (1693 tests) all pass locally.

@Jerry-Xin

Copy link
Copy Markdown
Contributor Author

Fixed CI failures on the rebased head (test-only changes, no source behavior change):

  • check-lint (max-lines): src/cron/service.failure-alert.test.ts exceeded the 1000-line test-file cap. Split the cohesive delivery-routing group into a new sibling src/cron/service.failure-alert.delivery.test.ts (following the existing ops.regression.origin.test.ts split convention); no coverage removed.
  • type-suppression-inventory: replaced an unchecked (cron as any).state in a test helper with the explicit typed (cron as unknown as { state: CronServiceState }).state form already used elsewhere in the cron tests.
  • server-cron.test.ts (3 cases): these terminal command-run cases invoked cron.run(..., "force"/"due"), which resolves to operator origin and (by design) cannot request scheduler-consuming semantics via the public facade. Drove them through the real scheduler tick (cron.start() → timer origin), the actual production path for scheduled command jobs; assertions unchanged.

New head d8ac00735e. tsgo:core, tsgo:test:src, the full src/cron suite (1693 tests), src/gateway/server-cron.test.ts (57), type-suppression-inventory (2), and lint/format all pass locally.

忻役 and others added 19 commits July 27, 2026 12:30
Manual `cron run` invocations are verification/debugging tools and
should not consume the one-shot guarantee. Previously, a manual run
on a `deleteAfterRun: true` job would both delete the job and disable
it, silently destroying the scheduled future fire.

Add an `isManual` flag to `applyJobResult()` opts. When set:
- `deleteAfterRun` is skipped (job preserved in store)
- One-shot disable logic is skipped (job stays enabled with its
  original `nextRunAtMs`)
- An info log is emitted so operators can see the job was preserved

Both manual run paths (`finishPreparedManualRun` and
`skipInvalidPersistedManualRun`) now pass `isManual: true`.
Timer-driven paths remain unchanged.

Closes openclaw#83538
…cheduled timer path

The disabled-heartbeat one-shot retry and exhaustion tests asserted scheduled
retry state (consecutiveSkipped, backoff nextRunAtMs, eventual disable) but
drove execution via cron.run(job.id, "due"). Manual cron runs no longer mutate
scheduled retry/disable state, so these assertions belong on the scheduled
timer path. Rewrite both cases to seed the store and advance through onTimer
ticks, and add a manual-run regression proving cron.run("due") records the run
outcome (lastRunWasManual) without advancing retry/disable state.
The UTF-16 code-point boundary truncation test drove the failure alert
through the manual cron.run("force") path, but manual runs intentionally
no longer emit failure alerts (they are non-consuming verification runs).
Route the test through simulateScheduledRun so it exercises the scheduled
execution path that actually emits the alert, matching the other
alert-text formatting tests in this file.
… test

The previous change routed the UTF-16 truncation test through
simulateScheduledRun but also dropped the runIsolatedAgentJob mock, which
createFailureAlertCron requires, causing a check-test-types failure
(TS2741: Property 'runIsolatedAgentJob' is missing). Restore the mock so
the helper type-checks while still driving the alert through the
scheduled execution path.
…cess

The recurring-job success/skipped branch in applyJobResult recomputed
nextRunAtMs unconditionally, so a manual ok/skipped run on an enabled
every/cron job would overwrite a pending scheduled error-backoff window
with the natural next fire. That let a manual verification run clear the
scheduled backoff, breaking the non-consuming manual-run contract.

Guard the recompute behind !isManual, mirroring the already-guarded error
branch, so manual runs leave nextRunAtMs untouched. Disabled jobs still
reset nextRunAtMs to undefined regardless of manual. Adds a regression
test covering manual success during a pending recurring error-backoff.
… misclassification

Replace the triggerEvalOnly/isManual boolean inference in the cron service
with an explicit CronRunOrigin enum ("timer" | "watcher-terminal" | "operator")
threaded from every entry point, so scheduler-state consumption and
deleteAfterRun deletion are decided by the caller's origin rather than
inferred from run mode + trigger outcome.

- operator (manual RPC/CLI run): non-consuming; never mutates scheduled
  counters/backoff/nextRunAtMs and never deletes deleteAfterRun jobs.
- timer (scheduled tick, incl. quiet trigger-eval and evaluator errors):
  consuming; errors increment consecutiveErrors and route through execution
  backoff, quiet ticks keep counters at zero with stagger-aware reschedule,
  and scheduled one-shot deleteAfterRun runs delete and emit the removed
  snapshot.
- watcher-terminal (gateway on-exit force): consuming for deleteAfterRun so a
  pre-disabled on-exit success is deleted, preserving the base contracts.

This removes the two regressions the previous inference caused: operator due
checks whose evaluator errored or did not fire were misread as scheduled and
mutated scheduler state, and every force run was treated as manual so
watcher-terminal on-exit deletions were skipped.

The RPC handler enqueues runs without an origin parameter, so external clients
cannot inject a consuming origin; only the in-process gateway watcher sets
watcher-terminal.
skipInvalidPersistedManualRun hard-coded origin "operator" when
finalizing a persisted job that fails spec validation at preflight.
The gateway on-exit watcher reaches this path with origin
"watcher-terminal", so invalid watcher-terminal runs were mis-attributed
as operator, causing scheduler-owned counters, alerts, and terminal
state to diverge from other watcher executions.

Thread the resolved CronRunOrigin from run() through
inspectManualRunPreflight into skipInvalidPersistedManualRun and pass it
to applyJobResult, defaulting to "operator" only for genuinely
origin-less callers. Add a regression test asserting watcher-terminal
invalid runs keep scheduled/consuming scheduler-state semantics while
operator invalid runs stay operator-attributed.
The explicit CronRunOrigin was exposed through the public
CronServiceRunOptions, so any in-process facade caller (plugin SDK, RPC
handlers, tests) could pass origin "watcher-terminal" and gain
scheduler-owned consuming semantics — deleting deleteAfterRun one-shots
or mutating scheduler counters, backoff, and nextRunAtMs. That widened
an internal seam into public API.

Remove origin from the public run options so the public run is always
operator semantics, and give the gateway on-exit watcher a concrete-only
CronService.runOnExitTerminal entry (absent from CronServiceContract and
GatewayCronServiceContract) that keeps watcher-terminal consuming
behavior. The watcher already holds the concrete CronService instance,
so no plumbing is needed. The internal ManualRunOptions.origin seam and
the timer/operator paths are unchanged.

Add invariant coverage: the public facade run preserves a deleteAfterRun
one-shot (operator semantics, no scheduler-state mutation) even though
it can no longer request another origin, while runOnExitTerminal still
consumes a successful on-exit one-shot.
Upstream moved onTimer and executeJobCore out of timer.ts into the
timer.test-support.ts helper module, so the leftover imports from
timer.js broke tsgo type checking (TS2459). Point the three affected
cron test files at ./timer.test-support.js to match the new layout.
A due deleteAfterRun one-shot 'at' job that receives an operator (manual)
ok run keeps its nextRunAtMs preserved because an operator run does not
consume the one-shot. But computeJobNextRunAtMs collapsed the pending slot
whenever the last run status was ok, so the next expired-slot maintenance
recompute wiped nextRunAtMs and stranded the job as a zombie that never
fires and never deletes.

Guard the ok-branch collapse with lastRunWasManual !== true so only a
scheduler-owned (timer) ok run retires the slot; manual/operator ok runs
leave the pending scheduled fire intact. Reuses the already-persisted
lastRunWasManual field, so it is restart-safe with no new state or
migration. Add a regression test covering the manual ok run surviving
maintenance recompute and a restart reload, then firing and deleting on a
real scheduled timer tick (existing coverage only exercised skipped runs).
…ance recompute

After rebasing onto upstream's scheduleMode-based maintenance recompute,
the origin-threaded manual run path referenced an out-of-scope mode flag
and applyTriggerNoFireResult still read a removed opts.scheduleMode field.

- finishPreparedManualRun runs with operator origin, so it repairs expired
  slots via a plain maintenance recompute instead of the scheduler-only
  force-preserve pin.
- applyTriggerNoFireResult drops the dead scheduleMode preserve branch:
  operator runs already return before schedule advancement, and scheduler
  quiet ticks advance normally, matching the origin model.
…ode removal

Upstream replaced the applyJobResult scheduleMode enum with built-in
defaults and added coverage asserting a forced operator run on a paced
job keeps its pending slot. The origin refactor no longer passed
scheduleMode, so the preserve branch went dead and operator runs on
paced jobs advanced the slot.

- applyJobResult now preserves the scheduled slot for a non-owning
  (operator) run on a paced job, matching upstream's forced-run pacing
  coverage while leaving non-paced due runs and scheduler-owned timer/
  watcher paths free to advance.
- finishPreparedManualRun pins its own expired paced slot for forced
  runs during post-run maintenance recompute so an expired pending fire
  is preserved rather than recomputed.
- Refresh the pacing regression to drive the forced-run case through the
  origin option instead of the removed scheduleMode field.
Upstream removed the configurable cron.retry knob (CronRetryOn export and
CronConfig.retry) in favor of built-in defaults. Adopt the current
resolveRetryConfig() zero-arg shape and import CronRetryOn from retry-hint,
thread the required run origin through the invalid-persisted-manual skip
paths, and split the oversized ops regression suite so it stays under the
max-lines ratchet.
Upstream removed the configurable cron.retry and maxConcurrentRuns knobs
from CronConfig; resolveRetryConfig() and resolveRunConcurrency() now use
built-in defaults. Delete the test cases whose sole purpose was asserting
the removed knobs (their default behavior is covered by sibling retry-hint
and one-shot-disable tests), and drop the now-invalid config fields from
the remaining tests whose real assertions still hold under the defaults.
…uler-consuming success state

Manual run origin must remain non-consuming only for scheduler-owned
success/lifecycle state (deleteAfterRun, one-shot disable-on-success,
next-run advance, retry-backoff scheduling). It must NOT suppress error
accounting: a failed manual run still increments consecutiveErrors,
records lastRunStatus=error, and emits failure alerts like a scheduled
run. Narrow the origin gate in applyJobResult/applyTriggerNoFireResult
so error counters, failure-alert emission, and evaluated trigger gate
state are recorded for all origins, while pending-slot and next-run
advance stay scheduler-owned. Align the affected regression tests.
…path

The "preserves global skipped alerts alongside an owned failure
destination" case triggered its skip via cron.run(job.id, "force"),
which defaults to origin=operator. Under the run-origin model a manual
operator run is non-consuming: it records the outcome but leaves
scheduler-owned state untouched, so consecutiveSkipped is not bumped and
the opt-in skip alert never fires (see the openclaw#83933 origin regression that
asserts an operator skip keeps consecutiveSkipped undefined). Error
alerts are origin-independent by design, which is why the sibling error
cases still pass through a force run.

Skip alerting runs off the scheduler-owned skip counter, so this case
belongs on the scheduled path like every other skip-alert test in the
file. Drive it through simulateScheduledRun (origin=timer) so it actually
exercises what it means to: a scheduled skip must still emit the global
skip alert even when the job declares an owned failure destination, since
that destination suppresses error alerts only. The assertions are
unchanged.
The failure-alert suite grew past the 1000-line max-lines cap for test
files after a scheduler-driven skip-alert case was added. Move the
delivery-routing group (global vs per-job destinations, owned failure
destinations, and mode/accountId threading) into a focused sibling,
service.failure-alert.delivery.test.ts, leaving threshold/text/
classification cases in place. Both files now sit well under the cap.

Also replace the unchecked `(cron as any).state` access in the
simulateScheduledRun helper with the explicit
`(cron as unknown as { state: CronServiceState }).state` form already
used elsewhere, so the type-suppression inventory stays at zero
unchecked any casts.
The three command delete/retain/backoff cases invoked the run via
cron.run(job.id, "force"/"due"), which now resolves to operator origin
and is deliberately non-consuming: it records the outcome but never
deletes a deleteAfterRun one-shot, applies error backoff, or otherwise
mutates scheduler-owned state (openclaw#83538/openclaw#83933). The public facade cannot
request watcher-terminal/timer semantics by design, so these cases were
asserting scheduler-owning outcomes against a non-owning run.

Drive them through the real scheduler tick instead (cron.start() +
onTimer, origin=timer) — the actual production path for scheduled
command jobs. The successful one-shot is deleted even when announce
delivery fails, the required-delivery failure retains the one-shot with
backoff, and the recurring command error applies backoff. Assertions are
unchanged.
@steipete

Copy link
Copy Markdown
Contributor

Thank you, @Jerry-Xin, for investigating and proposing the original repair. The maintainer-selected, narrower ownership fix has landed in #114491 and closes #83538; your contribution is credited with a Co-authored-by trailer on the merged commit. The landed fix additionally preserves queued manual runs that cross the scheduled deadline, keeps already-due and on-exit behavior unchanged, and is proven with live packaged-Gateway/Docker output plus the full cron suite. Closing this now that the underlying issue is fixed on main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants