Skip to content

fix(cron): stop replaying old schedule slots after a cron job is edited - #115779

Merged
vincentkoc merged 2 commits into
openclaw:mainfrom
OmerZeyveli:fix/cron-restart-catchup-activation
Jul 30, 2026
Merged

vincentkoc merged 2 commits into
openclaw:mainfrom
OmerZeyveli:fix/cron-restart-catchup-activation

Conversation

@OmerZeyveli

@OmerZeyveli OmerZeyveli commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Closes #91944

What Problem This Solves

Fixes an issue where users who edit a recurring cron job's schedule would see that job fire immediately the next time the gateway restarts, instead of only at its new time. A daily job moved from 19:00 to 21:00 fires right after the restart, and then again at 21:00. For scheduled outbound messaging jobs this delivers a message at the wrong time, which is what the linked report describes.

Why This Change Was Made

Startup catch-up decided a slot was "missed" by computing the previous slot of the current schedule and comparing it against lastRunAtMs, which still belongs to the schedule that was just replaced. A slot that never existed under the old schedule therefore looked overdue forever.

The scheduler now records when scheduling inputs take effect (state.scheduleActivatedAtMs) and replays a missed slot only when that slot is newer than the boundary. The stamp is written in the existing schedulingInputsChanged branch of finalizeUpdatedJob, the same place that already releases startupCatchupAtMs, pacedNextRunAtMs, and forcePreservedNextRunAtMs, so no new notion of "the schedule changed" was introduced. Jobs with no stamp keep replaying every computed slot, so catch-up behaviour is completely unchanged for jobs whose schedule was never edited.

The missed-slot predicate was duplicated in the runnable check and in the backoff-deferral pass, so both now share one helper and the bound cannot drift between them.

No SQLite schema change and no migration are involved: cron job state persists as JSON in state_json and stateFromRow already preserves unknown runtime fields, exactly like the existing startupCatchupAtMs and pacedNextRunAtMs fields.

Legacy rows are intentionally left alone. An earlier revision of this PR also backfilled the boundary during openclaw doctor --fix, using updatedAtMs as the stamp. ClawSweeper correctly rejected that: updatedAtMs advances for renames, payload edits, and delivery edits, so a legacy job that genuinely missed a slot and was later edited would have had that real catch-up suppressed after upgrade. Per the review's recommended resolution, that commit is dropped and legacy catch-up semantics are preserved exactly as they are today. The residual gap is narrow and self-healing: a job whose schedule was edited before upgrading can still replay once on the first restart after upgrade, after which its lastRunAtMs advances and the boundary applies normally. Closing that gap needs a trustworthy activation record rather than an inferred one, so it is deliberately out of scope here.

Prior art. This is a port of the approach in #92398 by @amersheeny, which built on #92305 by @fsdwen. #92398 was closed by the stale bot after 27 days of inactivity rather than on technical grounds, and ClawSweeper's review of #91944 asks for a scheduler-owned activation boundary. One deliberate divergence: #92398 also read ?? updatedAtMs as a runtime fallback for legacy jobs. This PR has no such fallback in the runtime path, for the same reason the doctor backfill was dropped — and concretely, the existing case at src/cron/service.restart-catchup.test.ts:612 has updatedAtMs equal to the missed slot itself, so a runtime fallback would suppress a legitimate catch-up there.

Scope. This fixes the restart-replay mechanism that ClawSweeper identified as the canonical root cause for #91944. It does not address that report's separate suggestion about doctor preflight re-reading jobs.json.migrated and overwriting SQLite; I could not reproduce that on current main.

User Impact

Editing a cron job's schedule no longer causes a spurious run on the next gateway restart. Jobs whose schedule is never edited behave exactly as before, and nothing rewrites existing persisted job state on upgrade.

Evidence

Real gateway restart, before and after

Both runs use the same script against a real gateway on an isolated OPENCLAW_STATE_DIR and a free port, driven entirely through the CLI (cron add, cron edit --cron), with a real command job appending to a file each time it fires. The job really runs on schedule A, schedule B's slot then passes while A is still active, the schedule is edited A→B, and the gateway is stopped and restarted.

Before — clean upstream/main at c193ffd554:

  schedule A : '47 16 * * *'   fires at 16:47
  schedule B : '48 16 * * *'   its slot 16:48 passes while A is still active
  edit A->B  : 16:49
  restart    : 16:50

=== RESULT ===
  fires before restart : 1
  fires after restart  : 2
  fired.log:
    2026-07-29T16:47:00+03:00
    2026-07-29T16:50:18+03:00      <-- restart moment, not a scheduled slot
  lastRunAtMs = 2026-07-29T13:50:18.625Z
  FAIL: restart replayed a slot from before the schedule edit

After — this branch:

  schedule A : '37 16 * * *'   fires at 16:37
  schedule B : '38 16 * * *'   its slot 16:38 passes while A is still active
  edit A->B  : 16:39
  restart    : 16:40

=== RESULT ===
  fires before restart : 1
  fires after restart  : 1
  fired.log:
    2026-07-29T16:37:00+03:00
  lastRunAtMs = 2026-07-29T13:37:00.023Z
  nextRunAtMs = 2026-07-30T13:38:00.000Z
  PASS: restart did not replay the pre-edit slot

The 16:50:18 line is the reported symptom: the job fires at the moment of the restart rather than at any slot of either schedule.

Focused tests and checks

src/cron/service.restart-catchup-schedule-change.test.ts reproduces the same flow in-process: it seeds the job on the old schedule, starts the service, edits the schedule through cron.update(), stops the service, advances the clock, and starts a second service against the same store. It fails on current main and passes with this change.

Verified locally on Node 24.18.0:

  • node scripts/run-vitest.mjs src/cron src/commands/doctor/cron — 168 files, 2056 tests passed
  • pnpm build — succeeded, no INEFFECTIVE_DYNAMIC_IMPORT warnings
  • pnpm check — 21 of 22 steps green, including the max-lines suppression ratchet, the database-first legacy-store guard, and all three typecheck projects. The one failure is format, on scripts/code-mode-model-matrix.ts, which this branch does not touch; that file is already unformatted on main (git show upstream/main:scripts/code-mode-model-matrix.ts fails oxfmt --check on its own).

About the red checks on this PR

The failing shards are src/tui/tui-pty-local.e2e.test.ts and src/cli/help-exit.process.test.ts, plus openclaw/ci-gate, which only aggregates them. Neither test file imports anything under src/cron/**, which is the entire surface this branch touches, and checking out clean upstream/main at c193ffd554 and running node scripts/run-vitest.mjs src/cli/help-exit.process.test.ts reproduces the identical result there: 4 failed, 48 passed. I left them alone rather than folding unrelated fixes into this PR, but I am happy to rebase onto a greener main if a maintainer prefers.

Editing a recurring job's schedule made the gateway fire it immediately on
the next restart. Startup catch-up compares the new schedule's previous slot
against lastRunAtMs, which still belongs to the retired schedule, so a slot
that never existed under the old schedule counted as missed.

Record when scheduling inputs take effect and replay a missed slot only when
it is newer than that. Jobs whose schedule never changed carry no stamp and
keep replaying every computed slot, so catch-up is unchanged for them.

The missed-slot predicate was duplicated in the runnable check and the
backoff-deferral pass; both now share one helper so the bound cannot drift.

Fixes openclaw#91944
@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: M labels Jul 29, 2026
@OmerZeyveli
OmerZeyveli marked this pull request as ready for review July 29, 2026 08:39
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. 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. labels Jul 29, 2026
@clawsweeper

clawsweeper Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 29, 2026, 9:43 PM ET / July 30, 2026, 01:43 UTC.

ClawSweeper review

What this changes

The PR adds a scheduler-owned schedule-activation timestamp so cron restart catch-up skips a prior slot that belongs only to the schedule replaced by an edit.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

This is a focused, proof-backed fix for a real restart-delivery bug. The final revision retains legacy catch-up behavior instead of inferring an activation boundary from unrelated update timestamps, while making the scheduler—not API callers—the owner of the new boundary; it is ready for the assigned maintainer’s normal merge review.

Priority: P1
Reviewed head: fd267b20124caf2593da533311620f7ea9c0836c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong real behavior proof, focused coverage, and a bounded scheduler-owned implementation support a normal mergeable-quality rating.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The contributor supplied a before-and-after real Gateway restart transcript using the CLI and a command job that appends observable output, demonstrating that the spurious restart-time run disappears after the change.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The contributor supplied a before-and-after real Gateway restart transcript using the CLI and a command job that appends observable output, demonstrating that the spurious restart-time run disappears after the change.
Evidence reviewed 5 items Scheduler-owned activation boundary: The proposed mutation finalizer stamps scheduleActivatedAtMs only when scheduling inputs change, before releasing existing catch-up and pacing reservations; the runnable predicate then rejects a computed previous slot at or before that boundary.
Symmetric restart and backoff behavior: The PR factors the prior-slot comparison into hasMissedCronSlotSinceLastRun, then uses that helper for both normal runnable-job catch-up and pending-backoff deferral so the two replay paths share the activation rule.
Caller ownership is protected: The protocol schema exposes the runtime state field for reporting, while cron create and patch inputs reject caller-supplied activation values; focused tests cover both creation and updates.
Findings None None.
Security None None.

How this fits together

Cron jobs are persisted with their scheduling and run state, then reevaluated when the Gateway starts. The restart catch-up path may run a missed cron slot, including scheduled outbound work, so it must distinguish a genuinely missed current-schedule slot from one synthesized by a later schedule edit.

flowchart LR
  A[Cron job update] --> B[Scheduler records activation]
  B --> C[Persisted cron state]
  C --> D[Gateway restart]
  D --> E[Missed-slot evaluation]
  E --> F[Replay genuine missed slot]
  E --> G[Keep future edited schedule]
Loading

Before merge

  • Resolve merge risk (P1) - This deliberately changes restart delivery semantics for an edited recurring job: a slot computed from the retired schedule is no longer replayed. The provided tests and live transcript support that tradeoff, but the assigned reviewer should retain the message-delivery check when reviewing the current-main merge result.
  • Resolve merge risk (P1) - The branch is behind current main; GitHub reports it cleanly mergeable, but the final merge or queue result should retain the focused cron regression coverage.
  • Complete next step (P2) - No mechanical repair remains: the PR has real behavior proof and no actionable correctness finding, so the remaining action is normal assigned-maintainer review of the current-main merge result.
Agent review details

Security

None.

PR surface

Source +33, Tests +245. Total +278 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 6 67 34 +33
Tests 3 247 2 +245
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 314 36 +278

Review metrics

Metric Value Why it matters
Scheduler state surface 1 added persisted runtime field; 0 new public create/update inputs The new boundary changes upgrade-sensitive restart behavior while explicit input filtering keeps its ownership inside the scheduler.

Merge-risk options

Maintainer options:

  1. Verify the current-main merge result (recommended)
    Refresh the branch or merge queue result and retain the focused cron restart tests, confirming that edited jobs suppress retired-schedule slots while genuine later missed slots still replay.
  2. Accept the documented delivery tradeoff
    Maintain the existing legacy-row behavior and accept that only schedule edits performed after this version records an activation boundary receive the new protection.

Technical review

Best possible solution:

Land the scheduler-owned activation boundary after a current-main merge refresh confirms that pre-activation slots are skipped while genuine post-edit missed slots and all unstamped legacy-job behavior remain unchanged.

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

Yes. The added focused test supplies a clear current-main failing path—old schedule run, schedule edit, restart, then a pre-edit current-expression slot—and the PR body independently shows the same behavior with a real Gateway and CLI-driven command job.

Is this the best way to solve the issue?

Yes. Recording a fact at the scheduler mutation boundary and consuming it in both missed-slot decisions is narrower and safer than inferring schedule activation from updatedAtMs or rewriting legacy rows during upgrade.

AGENTS.md: unclear because the file could not be read completely.

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

Labels

Label justifications:

  • P1: A restart can execute an edited cron job at an unintended time, including scheduled outbound work.
  • merge-risk: 🚨 compatibility: The patch adds persisted cron state and changes restart behavior for previously configured recurring jobs.
  • merge-risk: 🚨 message-delivery: The changed missed-slot predicate determines whether a scheduled job is delivered immediately after Gateway restart.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The contributor supplied a before-and-after real Gateway restart transcript using the CLI and a command job that appends observable output, demonstrating that the spurious restart-time run disappears after the change.
  • proof: sufficient: Contributor real behavior proof is sufficient. The contributor supplied a before-and-after real Gateway restart transcript using the CLI and a command job that appends observable output, demonstrating that the spurious restart-time run disappears after the change.

Evidence

What I checked:

  • Scheduler-owned activation boundary: The proposed mutation finalizer stamps scheduleActivatedAtMs only when scheduling inputs change, before releasing existing catch-up and pacing reservations; the runnable predicate then rejects a computed previous slot at or before that boundary. (src/cron/service/ops-mutations.ts, fd267b20124c)
  • Symmetric restart and backoff behavior: The PR factors the prior-slot comparison into hasMissedCronSlotSinceLastRun, then uses that helper for both normal runnable-job catch-up and pending-backoff deferral so the two replay paths share the activation rule. (src/cron/service/timer-runnable.ts, fd267b20124c)
  • Caller ownership is protected: The protocol schema exposes the runtime state field for reporting, while cron create and patch inputs reject caller-supplied activation values; focused tests cover both creation and updates. (src/cron/service/jobs.apply-patch.test.ts, fd267b20124c)
  • Regression coverage and real behavior proof: The added restart regression test models old schedule run → schedule edit → service restart, and the PR body provides before/after real Gateway CLI output with a command job: the pre-edit-slot replay occurs before the patch and does not occur after it. (src/cron/service.restart-catchup-schedule-change.test.ts, fd267b20124c)
  • Prior review concern resolved: The prior ClawSweeper cycle objected to inferring a schedule edit from every legacy update. The final head adds ownership guards and deliberately preserves legacy rows without using updatedAtMs as a runtime or doctor fallback. (src/cron/types.ts, fd267b20124c)

Likely related people:

  • vincentkoc: Assigned this PR, requested review, and authored the final ownership-hardening commit that prevents create/update callers from setting the scheduler boundary. (role: recent area contributor; confidence: high; commits: fd267b20124c; files: src/cron/service/jobs.ts, src/cron/service/jobs.apply-patch.test.ts, src/cron/service/ops-mutations.ts)
  • fsdwen: Authored the earlier scheduler-boundary proposal that identified both the runnable and backoff replay decisions as requiring the same guard. (role: prior implementation contributor; confidence: medium; commits: 35d3839e65bd; files: src/cron/service/timer-runnable.ts, src/cron/service/timer-catchup.ts, src/cron/types.ts)
  • amersheeny: Authored the later schedule-activation approach whose useful scheduler-owned boundary is ported here, while its unsafe legacy activation fallback is intentionally not retained. (role: prior implementation contributor; confidence: medium; commits: 6a00c36e6667; files: src/cron/service/ops-mutations.ts, src/cron/service/timer-runnable.ts, src/cron/types.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Refresh the clean-but-behind branch against current main and retain the focused cron regression result in the merge validation.

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-07-29T13:03:29.078Z sha dc33e0c15c35f8b2f08c50d18226277ed038e468 :: needs real behavior proof before merge. :: [P1] Do not infer a schedule edit from every legacy update
  • reviewed 2026-07-29T13:57:36.219Z sha 03200c9 :: needs maintainer review before merge. :: none

@OmerZeyveli
OmerZeyveli force-pushed the fix/cron-restart-catchup-activation branch from dc33e0c to 03200c9 Compare July 29, 2026 13:52
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 29, 2026
@vincentkoc vincentkoc self-assigned this Jul 30, 2026
@vincentkoc
vincentkoc requested a review from a team as a code owner July 30, 2026 01:39
@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime and removed commands Command implementations labels Jul 30, 2026
@vincentkoc

Copy link
Copy Markdown
Member

Maintainer decision: accept the scheduler-owned activation boundary and its compatibility tradeoff. Edited recurring jobs must not replay a slot from the retired schedule after restart. Pre-upgrade rows without scheduleActivatedAtMs retain the existing one-time ambiguous catch-up behavior; the first execution stamps normal run state, and the second restart does not replay it.

The exact merge-result proof retained the focused restart/backoff regressions, and current main has no touched-path overlap.

@vincentkoc
vincentkoc merged commit 82af1bf into openclaw:main Jul 30, 2026
125 of 127 checks passed
vincentkoc added a commit to zhangguiping-xydt/openclaw that referenced this pull request Jul 30, 2026
* origin/main:
  fix(macos): stop canceled voice wake timers (openclaw#116189)
  fix(macos): coalesce location permission requests (openclaw#116183)
  fix(macos): guard remote tunnel restart ownership (openclaw#116172)
  fix(agents): throw CompactionError when summarization fails (openclaw#115500)
  fix(test): isolate ACP startup output stream (openclaw#116076)
  fix(agents): deny all tools when scheduled authority names a removed account (openclaw#115932)
  fix(test): stop collecting Vydra test helpers (openclaw#116139)
  fix(discord): preserve webhook deadline errors (openclaw#116155)
  fix(test): isolate Google embedding batch timeout (openclaw#116161)
  fix(cron): stop replaying old schedule slots after a cron job is edited (openclaw#115779)
  fix(plugins): report request timeouts for stalled response bodies (openclaw#116166)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 30, 2026
…ed (openclaw#115779)

* fix(cron): bound restart catch-up to the active schedule

Editing a recurring job's schedule made the gateway fire it immediately on
the next restart. Startup catch-up compares the new schedule's previous slot
against lastRunAtMs, which still belongs to the retired schedule, so a slot
that never existed under the old schedule counted as missed.

Record when scheduling inputs take effect and replay a missed slot only when
it is newer than that. Jobs whose schedule never changed carry no stamp and
keep replaying every computed slot, so catch-up is unchanged for them.

The missed-slot predicate was duplicated in the runnable check and the
backoff-deferral pass; both now share one helper so the bound cannot drift.

Fixes openclaw#91944

* fix(cron): protect schedule activation ownership

---------

Co-authored-by: Vincent Koc <[email protected]>
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: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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.

v2026.6.5: Cron doctor preflight overwrites API-updated schedules with stale legacy JSON data

2 participants