Skip to content

cron: unify stale-run recovery and preserve manual-run every anchors - #35363

Merged
Takhoffman merged 3 commits into
mainfrom
fix-cron-run-preserve-due-jobs
Mar 5, 2026
Merged

Takhoffman merged 3 commits into
mainfrom
fix-cron-run-preserve-due-jobs

Conversation

@Takhoffman

Copy link
Copy Markdown
Contributor

Summary

Describe the problem and fix in 2–5 bullets:

  • Problem: Cron recovery behavior diverged across maintenance/timer/manual-run paths, causing inconsistent handling for stale nextRunAtMs and manual every run anchor drift.
  • Why it matters: Incorrect stale recovery can silently skip due executions, while manual force runs can unintentionally shift recurring schedules.
  • What changed: Unified maintenance recovery contract with explicit recomputeExpired semantics, preserved every schedule anchor on manual force runs (including error-backoff path), and added shared coercion for legacy string-typed everyMs/anchorMs.
  • What did NOT change (scope boundary): No changes to channel delivery logic, unrelated gateway flows, or non-cron scheduling semantics.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

User-visible / Behavior Changes

  • Manual openclaw cron run <id> --force no longer shifts every schedule anchor to the manual run time.
  • Recovery paths now avoid silently advancing never-executed stale runs while still allowing already-executed stale slots to advance when explicitly recovering expired state.
  • Legacy persisted everyMs/anchorMs string values are coerced safely, preventing cron schedules from becoming non-runnable due to NaN schedule math.

Security Impact (required)

  • New permissions/capabilities? (Yes/No) No
  • Secrets/tokens handling changed? (Yes/No) No
  • New/changed network calls? (Yes/No) No
  • Command/tool execution surface changed? (Yes/No) No
  • Data access scope changed? (Yes/No) No
  • If any Yes, explain risk + mitigation:

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: Node 22+, pnpm workspace
  • Model/provider: N/A
  • Integration/channel (if any): N/A
  • Relevant config (redacted): default cron/service test harness configs

Steps

  1. Create overdue cron jobs with differing stale-state combinations (already-executed stale slot vs never-executed stale slot).
  2. Exercise maintenance/timer recovery and manual force-run paths.
  3. Verify nextRunAtMs advancement behavior and anchor preservation via cron suites.

Expected

  • Never-executed stale runs are not silently advanced.
  • Already-executed stale slots can be advanced on explicit expired recovery.
  • Manual force runs preserve recurring every anchor cadence.
  • Legacy string schedule values parse and schedule correctly.

Actual

  • Matches expected in all covered scenarios.

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Verification commands run locally:

  • pnpm check
  • pnpm test -- src/cron/
  • pnpm test:macmini

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios: maintenance stale recovery semantics, timer-path expired recovery with due-check timestamp consistency, manual every force-run anchor preservation, legacy string schedule coercion.
  • Edge cases checked: stale runningAtMs clearing, already-executed vs never-executed stale slots, error-backoff path with preserveSchedule, non-numeric string schedule values.
  • What you did not verify: live channel end-to-end runtime behavior outside test harness.

Compatibility / Migration

  • Backward compatible? (Yes/No) Yes
  • Config/env changes? (Yes/No) No
  • Migration needed? (Yes/No) No
  • If yes, exact upgrade steps:

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly: Revert this PR commit(s) to restore prior maintenance and manual-run behavior.
  • Files/config to restore: src/cron/service/jobs.ts, src/cron/service/timer.ts, src/cron/service/ops.ts, src/cron/schedule.ts, src/cron/service/store.ts.
  • Known bad symptoms reviewers should watch for: overdue jobs skipping unexpectedly, force runs shifting daily/recurring anchors, every jobs stuck due to invalid coerced schedule values.

Risks and Mitigations

List only real risks for this PR. Add/remove entries as needed. If none, write None.

  • Risk: Recovery semantics for stale runs can still be subtle around boundary timestamps.
    • Mitigation: Added explicit regression coverage for stale-running marker cleanup and consistent due-check timestamp usage.
  • Risk: Coercion path could mask malformed persisted schedule fields.
    • Mitigation: Non-finite/non-numeric values still resolve to undefined and are covered by schedule tests.

@aisle-research-bot

aisle-research-bot Bot commented Mar 5, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 1 potential security issue(s) in this PR:

# Severity Title
1 🔵 Low Cron jobs can be permanently blocked via non-finite/invalid runningAtMs values (NaN/Infinity/far-future)

1. 🔵 Cron jobs can be permanently blocked via non-finite/invalid runningAtMs values (NaN/Infinity/far-future)

Property Value
Severity Low
CWE CWE-400
Location src/cron/service/jobs.ts:465-469

Description

The scheduler treats any numeric job.state.runningAtMs value as an active run marker. With JSON5-backed persistence (which can represent NaN/Infinity) or a manipulated stored state, an attacker can set runningAtMs to a non-finite or far-future number that is never cleared, causing the job to never become runnable.

In the new maintenance recovery path (recomputeExpired), the job is also considered “running” whenever typeof runningAtMs === "number", so the scheduler will not repair expired nextRunAtMs entries for such jobs.

Impact (availability):

  • A job with runningAtMs: NaN/Infinity (or an extremely large timestamp) is never runnable because isRunnableJob/isJobDue short-circuit on typeof runningAtMs === "number".
  • The stuck-marker cleanup (nowMs - runningAtMs > STUCK_RUN_MS) does not clear NaN/Infinity because the subtraction yields NaN/-Infinity, making the comparison false.
  • With a past-due nextRunAtMs, armTimer() may wake frequently (floored to MIN_REFIRE_GAP_MS), resulting in a persistent scheduler spin and missed executions.

Vulnerable code (new logic relying on typeof):

} else if (
  recomputeExpired &&
  now >= job.state.nextRunAtMs &&
  typeof job.state.runningAtMs !== "number"
) {
  ​// ...
}

Recommendation

Treat runningAtMs as a finite timestamp, and proactively clear/ignore invalid values.

  1. Replace typeof job.state.runningAtMs !== "number" with a finiteness check:
const runningAt = job.state.runningAtMs;
const isRunning = isFiniteTimestamp(runningAt);
​// optionally: treat future timestamps as invalid
const validRunningAt = isRunning && runningAt <= nowMs + 5 * 60_000;

if (recomputeExpired && now >= job.state.nextRunAtMs && !validRunningAt) {
  ​// recovery recompute
}
  1. In normalizeJobTickState, clear invalid runningAtMs values:
const runningAt = job.state.runningAtMs;
if (!isFiniteTimestamp(runningAt) && runningAt !== undefined) {
  job.state.runningAtMs = undefined;
  changed = true;
}

This prevents crafted state (including JSON5 NaN/Infinity) from permanently blocking execution.


Analyzed PR: #35363 at commit 831feeb

Last updated on: 2026-03-05T04:43:13Z

@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Mar 5, 2026

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2144da3a6a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/cron/service/ops.ts Resolved
@greptile-apps

ghost commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR unifies the stale-run recovery contract across maintenance, timer, and manual-run paths in the cron service, and adds string-coercion safety for legacy-persisted everyMs/anchorMs schedule fields. It is a focused, well-scoped bug fix with solid regression coverage.

Key changes:

  • recomputeNextRunsForMaintenance gains a recomputeExpired flag and an explicit nowMs param; onTimer passes a consistent dueCheckNow timestamp to both collectRunnableJobs and the maintenance walk, eliminating the previously subtle timestamp gap.
  • applyJobResult gets a preserveSchedule option: when true and the schedule is every, the function temporarily restores prevLastRunAtMs during computeJobNextRunAtMs so that the next slot is computed from the historical anchor rather than the force-run time.
  • ops.ts passes preserveSchedule: mode === "force" and switches from recomputeNextRuns to recomputeNextRunsForMaintenance after manual runs, preventing unrelated due jobs from being silently advanced.
  • coerceFiniteScheduleNumber is extracted to schedule.ts and used consistently across schedule.ts, jobs.ts, and store.ts to guard against NaN/Infinity/string schedule values.
  • The duplicated try/finally mutation pattern for temporary lastRunAtMs mutation appears in both the error and success branches of applyJobResult and should be extracted into a shared helper to reduce maintainability risk.
  • A subtle edge case exists where error-backoff on a force run can still shift the every anchor: if the backoff deadline exceeds the anchor-derived next-slot time, the job's nextRunAtMs is set to the backoff deadline while lastRunAtMs remains the force-run time; on the next regular run, the anchor drifts from the historical value to the force-run time. This should be documented or handled.

Confidence Score: 4/5

  • Core logic is sound; the changes safely unify stale-run recovery and preserve recurring anchors on force runs, with solid regression testing. Two maintainability/edge-case concerns remain.
  • This PR is safe to merge; the core logic for preserving every anchors on force runs is correct and well-covered by tests. The preserveSchedule anchor swap, consistent dueCheckNow timestamp, and coerceFiniteScheduleNumber coercion path all function correctly in tested scenarios. The score is 4 rather than 5 because: (a) the duplicated try/finally mutation pattern in the error and success branches is a maintainability risk that should be refactored into a shared helper, and (b) the error-backoff path with preserveSchedule=true can still cause anchor drift when the backoff deadline exceeds the natural next-slot time; while this may be intentional, it should be explicitly documented to clarify the trade-off.
  • src/cron/service/timer.ts — specifically the duplicated try/finally pattern (lines 197–206 and 222–231) and the error-backoff branch behavior when preserveSchedule=true (lines 197–210).

Last reviewed commit: 2144da3

Comments Outside Diff (1)

  1. undefined, line undefined (link)

    When preserveSchedule is true and the force run errors, normalNext is correctly computed from prevLastRunAtMs. However job.state.nextRunAtMs is then set to:

    job.state.nextRunAtMs =
      normalNext !== undefined ? Math.max(normalNext, backoffNext) : backoffNext;

    If the backoff fires later than the anchor-derived normalNext, the job's nextRunAtMs is advanced to backoffNext. On the next successful regular run (not forced), computeJobNextRunAtMs will compute the next slot from job.state.lastRunAtMs = result.startedAt (the force-run time), so the anchor drift still occurs via the error-backoff path — exactly the drift this PR aims to eliminate.

    Whether this is an acceptable trade-off (backoff overrides anchor on error) should be explicitly documented in a comment, since the happy-path anchor-preservation code just above implies force runs never shift anchors.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/cron/service/timer.ts
    Line: 209-210
    
    Comment:
    When `preserveSchedule` is `true` and the force run **errors**, `normalNext` is correctly computed from `prevLastRunAtMs`. However `job.state.nextRunAtMs` is then set to:
    
    ```ts
    job.state.nextRunAtMs =
      normalNext !== undefined ? Math.max(normalNext, backoffNext) : backoffNext;
    ```
    
    If the backoff fires later than the anchor-derived `normalNext`, the job's `nextRunAtMs` is advanced to `backoffNext`. On the *next* successful regular run (not forced), `computeJobNextRunAtMs` will compute the next slot from `job.state.lastRunAtMs = result.startedAt` (the force-run time), so the anchor drift still occurs via the error-backoff path — exactly the drift this PR aims to eliminate.
    
    Whether this is an acceptable trade-off (backoff overrides anchor on error) should be explicitly documented in a comment, since the happy-path anchor-preservation code just above implies force runs never shift anchors.
    
    How can I resolve this? If you propose a fix, please make it concise.

Comment thread src/cron/service/timer.ts Resolved
@Takhoffman

ghost commented Mar 5, 2026

Copy link
Copy Markdown
Contributor Author

Addressed follow-up review items and pushed update 7e415843d.

What was fixed:

  • src/cron/service/ops.ts: manual cron.run post-processing now uses recomputeNextRunsForMaintenance(..., { recomputeExpired: true }) so already-executed stale slots are recovered.
  • src/cron/service/timer.ts: de-duplicated preserve-schedule lastRunAtMs swap/restore logic via shared local helper path in applyJobResult.
  • src/cron/service.issue-regressions.test.ts: expanded manual-run regression to assert both:
    • unrelated never-executed due jobs remain unchanged
    • unrelated already-executed stale slots advance to a future run

Verification rerun:

  • pnpm test -- src/cron/service.issue-regressions.test.ts src/cron/service.issue-13992-regression.test.ts src/cron/service.issue-17852-daily-skip.test.ts
  • pnpm check

All unresolved review threads are now resolved.

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

Labels

maintainer Maintainer-authored PR size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Cron jobs with expired nextRunAtMs never execute after gateway restart

1 participant