Skip to content

fix(cron): arm the scheduler when startup catch-up fails - #144144

Closed
yetval wants to merge 1 commit into
openclaw:mainfrom
yetval:fix/cron-start-arm-after-catchup-failure
Closed

yetval wants to merge 1 commit into
openclaw:mainfrom
yetval:fix/cron-start-arm-after-catchup-failure

Conversation

@yetval

@yetval yetval commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Summary

One transient store failure during restart catch-up permanently disables the cron scheduler for the life of the Gateway process.

CronService.start() runs startup catch-up before it arms the scheduling timer. runMissedJobs deliberately rejects when a startup outcome's terminal store write fails (a locked or failing SQLite write, a disk error, a finalization error). That rejection escapes start() before armTimer is ever reached, so state.timer stays null while state.stopped and state.schedulingPaused are both false. The Gateway catches the rejection, logs cron: failed to start: ... and does not retry, and it also skips reconcileExitWatchers / reconcileStreamWatchers. The Gateway then comes up looking healthy while no scheduled job ever fires again. cron list and cron status still show the jobs and their next run times. Only a cron mutation that happens to call armTimer (add, update, enable, a manual run) or a full Gateway restart brings scheduling back.

Reachability on main: Gateway boot -> src/gateway/server-runtime-services.ts:68 params.cronState.cron.start() -> src/gateway/server-cron-lazy.ts:162 -> src/cron/service.ts:68 lifecycleOps.start(this.state) -> src/cron/service/ops-lifecycle.ts:187.

The sibling scheduled-tick path already guarantees the opposite: onAdmittedTimer in src/cron/service/timer-scheduler.ts:589 re-arms inside a finally, so a tick that throws still leaves the scheduler armed. resumeScheduling cannot heal the startup case either, because it early-returns on !state.schedulerStarted (src/cron/service/ops-lifecycle.ts:238).

Related prior attempt: #68112 described the same root cause and was closed by ClawSweeper as stalled without real behavior proof. That patch was much wider (86 changed lines in the old ops.ts plus 78 in timer.ts, including an unrelated zombie-marker detector). This one is confined to the arm boundary and carries the proof.

Root cause

src/cron/service/ops-lifecycle.ts:187-212 (before):

  await runMissedJobs(state, {
    skipJobIds: skipJobIds.size > 0 ? skipJobIds : undefined,
    deferAgentTurnJobs: true,
  });

  await locked(state, async () => {
    await ensureLoaded(state, { forceReload: true, skipRecompute: true });
    if (state.stopped) {
      return;
    }
    if (listForeignReceipts(state).length === 0) {
      const maintenance = recomputeUnownedCronSchedules(state, { recomputeExpired: true });
      runPostPersistCronNotifications(state, maintenance.notifications);
      applyCronRuntimeRowsToState(state, maintenance.jobs);
    }
    armTimer(state);
    resumeForeignReceiptMonitor(state);
    state.deps.log.info(
      {
        enabled: true,
        jobs: state.store?.jobs.length ?? 0,
        nextWakeAtMs: nextWakeAtMs(state) ?? null,
      },
      "cron: started",
    );
  });

runMissedJobs throws from src/cron/service/timer-catchup.ts:290 and :296 when a startup outcome cannot be finalized; the maintainers' own src/cron/service/timer.batch-finalization.test.ts:815 pins that reject contract. Because the call is unfenced, the entire recompute plus armTimer plus resumeForeignReceiptMonitor block is skipped. Startup catch-up already cleared state.startupCatchup in its own finally, so nothing else is holding the timer down: the scheduler is simply never armed.

Fix

src/cron/service/ops-lifecycle.ts (after):

  let catchupFailure: { err: unknown } | undefined;
  try {
    await runMissedJobs(state, {
      skipJobIds: skipJobIds.size > 0 ? skipJobIds : undefined,
      deferAgentTurnJobs: true,
    });
  } catch (err) {
    catchupFailure = { err };
  }

  try {
    await locked(state, async () => {
      await ensureLoaded(state, { forceReload: true, skipRecompute: true });
      if (state.stopped) {
        return;
      }
      if (listForeignReceipts(state).length === 0) {
        const maintenance = recomputeUnownedCronSchedules(state, { recomputeExpired: true });
        runPostPersistCronNotifications(state, maintenance.notifications);
        applyCronRuntimeRowsToState(state, maintenance.jobs);
      }
      armTimer(state);
      resumeForeignReceiptMonitor(state);
      const startupDetails = {
        enabled: true,
        jobs: state.store?.jobs.length ?? 0,
        nextWakeAtMs: nextWakeAtMs(state) ?? null,
      };
      if (catchupFailure) {
        state.deps.log.warn(
          { ...startupDetails, err: String(catchupFailure.err) },
          "cron: armed the scheduler after startup catch-up failed",
        );
        return;
      }
      state.deps.log.info(startupDetails, "cron: started");
    });
  } catch (err) {
    if (!catchupFailure) {
      throw err;
    }
    state.deps.log.warn(
      { err: String(err) },
      "cron: failed to arm the scheduler after startup catch-up failed",
    );
  }

  if (catchupFailure) {
    throw catchupFailure.err;
  }

A failed catch-up is held, the existing arm block runs unchanged, and the original catch-up error is then rethrown so the caller still sees the failure. The arm block keeps its own state.stopped guard, and armTimer independently refuses to arm when state.stopped, state.schedulingPaused, or state.startupCatchup is set, so a start that was superseded by stop() still arms nothing. A secondary arm failure is logged and never masks the catch-up error, and the success path keeps propagating an arm error as before. The startup log line is downgraded to a warning when the arm happened after a failed catch-up, so cron: started never claims a clean start.

Why this is the right boundary

  • start() in ops-lifecycle.ts is the owner of "the scheduler is armed after startup". runMissedJobs owns catch-up execution and its reject contract, and it is unchanged: it still releases reservations, still preserves overflow wake times, and still throws. Fixing this inside timer-catchup.ts would mean swallowing a real store failure at the wrong layer.
  • This mirrors the sibling scheduled-tick path exactly. onAdmittedTimer (src/cron/service/timer-scheduler.ts:586-592) already re-arms in a finally after a throwing tick. Startup was the only entry point that could leave the timer down, and it is now the same shape.
  • The recompute that now also runs on the failure path is not new policy: it is the same recomputeUnownedCronSchedules(state, { recomputeExpired: true }) the success path performs, and the same maintenance onAdmittedTimer performs on its next tick. It makes the failure path converge one tick sooner instead of relying on the minute watchdog.
  • schedulerStarted is deliberately left alone. CronService.startOnce (src/cron/service.ts:66-73) owns that flag and only sets it after start() resolves; the catch-up error still propagates, so a failed start is still recorded as a failed start and server-cron-lazy.ts still sets underlyingStarted = false. Setting it to true from inside a rejected start would tell ensureLoadedForRead (src/cron/service/ops-shared.ts:64) to stop doing read repair and would contradict the caller's own failure record. Timer-armed-while-schedulerStarted-is-false is already a state main produces: reconcileForeignRunReceipts calls armTimer at ops-lifecycle.ts:115 from the foreign-receipt monitor during start.
  • resumeScheduling still early-returns on !schedulerStarted, unchanged. A suspension cycle after a failed start therefore still needs the Gateway's own retry, which server-cron-lazy.ts performs (it calls resumeScheduling() and then start() again on the next resolve). Changing that gate is a separate lifecycle decision and is out of scope here.
  • Generation fencing is unaffected. stop() is the only writer of lifecycleGeneration and it sets state.stopped = true in the same call, so a superseded start cannot arm a live timer, and the timer callback keeps its own generation check at timer-scheduler.ts:148-162.
  • Behavior on a successful start is byte-for-byte the same ordering and the same cron: started info line.

Verification

  • node scripts/run-vitest.mjs src/cron/service/ops-lifecycle.start-arm.test.ts - 2 passed with the patch. The first case drives the real start() over a real SQLite cron store with a one-shot AFTER UPDATE ON cron_jobs trigger that rejects the terminal write (the technique the maintainers use in timer.batch-finalization.test.ts), and asserts that start() still rejects while state.timer is armed. The second case pins the sibling contract on the scheduled-tick path.
  • The same scenario run on pristine origin/main (17f74b9976) before the patch existed FAILS at expect(state.timer).not.toBeNull() with AssertionError: expected null not to be null, and passes with the patch applied.
  • Not run locally: the adjacent suites src/cron/service/timer.batch-finalization.test.ts, src/cron/service/ops.regression.test.ts, src/cron/service/run-recovery.lifecycle.test.ts and src/cron/service/timer.regression.test.ts were started but could not complete on this host, which ran out of memory and disk during the runs. CI covers them. The change does not touch runMissedJobs, armTimer, or any store/recovery helper, and the success path keeps the same call order and the same cron: started log line.
  • No source or test comments were added. Formatting (oxfmt) and typechecking (tsgo) are delegated to CI.

Real behavior proof

Behavior addressed: after a single transient cron store write failure during restart catch-up, the Gateway comes up healthy but no scheduled cron job ever fires again for the life of the process.
Real environment tested: the real production CronService from src/cron/service.ts driven through cron.start() (the exact call the Gateway makes at src/gateway/server-cron-lazy.ts:162), over a real on-disk SQLite state database and a real cron job store, with real wall-clock timers, on pristine main 17f74b9976 and on the patched tree with identical inputs. Nothing in the scheduler, store, or timer was stubbed; the one external seam forced was the SQLite write itself, via a one-shot AFTER UPDATE ON cron_jobs trigger that raises disk I/O error while writing cron_jobs on the first terminal write, standing in for a real failing or locked disk.
Exact steps or command run after this patch: seed two enabled jobs into a fresh store (one already overdue by 30s, one becoming due 30s later), install the one-shot failing trigger on the overdue job's terminal write, call await cron.start(), then observe the live scheduler for 70s and record every wake the service actually delivered.
Evidence after fix:

# BEFORE (pristine main 17f74b9976)
gateway log line          : cron: failed to start: Error: disk I/O error while writing cron_jobs
state.timer after start   : null (UNARMED)
state.stopped             : false
state.schedulingPaused    : false
start() settled           : 673 ms after seeding
upcoming-job became due   : 30000 ms after seeding
upcoming-job ran during startup catch-up: NO
upcoming-job ran within 70s of seeding: NO - never ran
all wakes delivered       : ["overdue-startup-job"]

# AFTER (this patch, identical inputs)
gateway log line          : cron: failed to start: Error: disk I/O error while writing cron_jobs
state.timer after start   : set (ARMED)
state.stopped             : false
state.schedulingPaused    : false
start() settled           : 920 ms after seeding
upcoming-job became due   : 30000 ms after seeding
upcoming-job ran during startup catch-up: NO
upcoming-job ran within 70s of seeding: YES (30169 ms after seeding)
all wakes delivered       : ["overdue-startup-job","upcoming-job"]

Observed result after fix: the scheduling timer that was left null on main is now armed after the same failed catch-up, and the job scheduled for 30s later actually fired at 30169 ms instead of never firing, while the caller still receives the identical cron: failed to start failure.
What was not tested: this drives CronService.start() directly rather than booting a full Gateway process, so the surrounding server-runtime-services.ts error logging and the skipped reconcileExitWatchers / reconcileStreamWatchers calls were read from source rather than observed live. The forced failure is a SQLite trigger raising on the terminal write rather than genuinely exhausted disk or a genuinely locked database file, and only the startup catch-up finalization failure was exercised, not every error runMissedJobs can surface.

A failed startup catch-up left the cron scheduler permanently unarmed:
start() called runMissedJobs before the block that recomputes schedules
and calls armTimer, so a rejected catch-up skipped the arm entirely and
state.timer stayed null with stopped and schedulingPaused both false. The
Gateway logged the failure, did not retry, and no scheduled job ran again
for the life of the process.

Fence the catch-up call so the existing recompute and armTimer block
still runs, then rethrow the original catch-up error so the caller still
records a failed start. A secondary arm failure is logged and never masks
the catch-up error, and the startup log line reports a warning instead of
cron: started when the arm followed a failed catch-up. This matches the
scheduled-tick path, which already re-arms in a finally.
@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 10, 2026
@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 12, 2026, 11:03 AM ET / 15:03 UTC (Revision 2).

ClawSweeper review

What this changes

The PR lets cron arm its scheduling timer after startup catch-up fails, preserves the original error, and adds regression coverage.

Merge readiness

✅ Ready for maintainer review

This remains a useful, focused fix: current main and the latest release retain the failure path, and the supplied production-scheduler trace demonstrates recovery. No blocking patch defects were found.

Priority: P1
Reviewed head: 23a107d998bb759e0d42333d7ced40ffb399d6c8

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, maintainable repair with direct before/after scheduler proof and no blocking findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The inspected, hash-matched PR body shows the real CronService startup owner using on-disk SQLite and wall-clock timers: after an injected terminal-write failure, a future job fires at 30169 ms with the patch while the original startup error remains observable.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The inspected, hash-matched PR body shows the real CronService startup owner using on-disk SQLite and wall-clock timers: after an injected terminal-write failure, a future job fires at 30169 ms with the patch while the original startup error remains observable.
Evidence reviewed 8 items Current main still needs the fix: Current main awaits runMissedJobs before entering the scheduling arm block; a rejected catch-up skips that block.
Latest release retains the same ordering: Inspection of v2026.9.4 shows the unfenced catch-up call before timer arming; the tag resolves to the supplied release commit.
Introduced change preserves lifecycle checks: The verified merge-base-to-head patch captures catch-up rejection, runs the existing reload/recompute/arm block, and rethrows the original failure. Stop and pause guards remain in their existing owners.
Findings None None.
Security None None.

How this fits together

OpenClaw's cron service loads persisted jobs when the Gateway starts, catches up missed runs, and arms timers for future work. Those timers dispatch scheduled jobs through the existing execution and persistence owners.

flowchart TD
  A[Gateway startup] --> B[Load persisted jobs]
  B --> C[Catch up missed runs]
  C --> D[Success or captured failure]
  D --> E[Check lifecycle and arm timer]
  E --> F[Future scheduled jobs]
  D --> G[Return original startup error]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +24, Tests +106. Total +130 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 45 21 +24
Tests 1 106 0 +106
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 151 21 +130

Review metrics

Metric Value Why it matters
Production versus regression coverage Production net +24 lines; tests +106 lines Production growth is justified by preserving the original failure while separately attempting and reporting scheduler recovery.

Technical review

Best possible solution:

Keep scheduler liveness independent of catch-up success within the existing lifecycle owner, while preserving failure reporting and stop/pause safeguards.

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

Yes: current source exposes the failure by rejecting a startup catch-up terminal write before timer arming. The contributor supplies a matching before/after runtime trace; this review did not execute it.

Is this the best way to solve the issue?

Yes: the patch repairs the startup lifecycle owner and reuses existing scheduling operations without swallowing storage errors or adding competing recovery policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 81a4c771eff6.

Labels

Label justifications:

  • P1: A transient startup write failure can silently stop future scheduled work for the lifetime of an otherwise running Gateway.
  • 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 inspected, hash-matched PR body shows the real CronService startup owner using on-disk SQLite and wall-clock timers: after an injected terminal-write failure, a future job fires at 30169 ms with the patch while the original startup error remains observable.
  • proof: sufficient: Contributor real behavior proof is sufficient. The inspected, hash-matched PR body shows the real CronService startup owner using on-disk SQLite and wall-clock timers: after an injected terminal-write failure, a future job fires at 30169 ms with the patch while the original startup error remains observable.

Evidence

What I checked:

  • Current main still needs the fix: Current main awaits runMissedJobs before entering the scheduling arm block; a rejected catch-up skips that block. (src/cron/service/ops-lifecycle.ts:188, 81a4c771eff6)
  • Latest release retains the same ordering: Inspection of v2026.9.4 shows the unfenced catch-up call before timer arming; the tag resolves to the supplied release commit. (src/cron/service/ops-lifecycle.ts:187, 3a9d69db306c)
  • Introduced change preserves lifecycle checks: The verified merge-base-to-head patch captures catch-up rejection, runs the existing reload/recompute/arm block, and rethrows the original failure. Stop and pause guards remain in their existing owners. (src/cron/service/ops-lifecycle.ts:187, 23a107d998bb)
  • Catch-up and scheduled-tick contracts: Catch-up propagates finalization failures and releases its startup fence in finally. The sibling scheduled-tick owner already re-arms after failures, while armTimer checks stopped, paused, and catch-up state. (src/cron/service/timer-scheduler.ts:55, 23a107d998bb)
  • Production recovery proof and complete body coverage: The full fetched PR body matches captured SHA-256 c0546e55baccedf900e399426f6601e5e9fbe9af89942b68096caf068ab51d5e. Its before/after trace uses CronService.start(), on-disk SQLite, real timers, and an injected terminal-write failure: the later job never fires before the patch and fires at 30169 ms afterward. Full Gateway boot and genuine disk exhaustion were expressly outside this proof. The omitted verification section was inspected; it reports two focused tests passing and adjacent suites interrupted by resource exhaustion. (src/cron/service.ts:68, 23a107d998bb)
  • Prior attempt is not a replacement: fix(cron): prevent scheduler death when startup catch-up fails #68112 describes the same startup arming failure alongside additional stale-marker recovery changes. GitHub confirms it is closed and unmerged.

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Shakker: 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 (1 earlier review cycle)
  • reviewed 2026-09-10T15:44:13.038Z sha 23a107d :: needs maintainer review before merge. :: none

@yetval

yetval commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Closing this implementation PR at the author's request and moving the unresolved defect to #158969: #158969

The follow-up report records a fresh check on main b7cf7d9098538044d2e65fbde916458f013c7b73, current reproduction evidence, related work, and explicit proof limits. This closure does not claim the bug is fixed or reject the proposed repair.

The candidate at 23a107d998bb759e0d42333d7ced40ffb399d6c8, its review discussion, and earlier before/after evidence remain available here for maintainers or a future implementation. Please use the linked issue as the canonical open report.

@yetval yetval closed this Sep 26, 2026
obviyus added a commit that referenced this pull request Sep 26, 2026
…9086)

Closes #158969. Related: #144144.

## What Problem This Solves

Fixes future cron jobs never firing after a startup catch-up job encounters a transient store write failure.

## User Impact

Once the write fault clears, future scheduled jobs can run without restarting the Gateway or editing a job. The startup failure remains visible. No configuration, schema, or default changes.

## Why This Change Was Made

The startup lifecycle owner now arms scheduling when catch-up rejects, then rethrows the original failure, reporting any secondary arming error separately. Failed-start scheduling stays resumable through Gateway suspension; the lazy proxy delegates readiness to the service after any start attempt. Existing stop, pause, and lifecycle-generation fences remain in force. Normal startup ordering is unchanged; existing run-recovery logic settles the completed catch-up job without replaying it.

## Evidence

- Real `CronService.start()` with SQLite persistence: a trigger rejects the overdue job's terminal write, startup rejects, and the trigger is removed before a later job becomes due. On the baseline the later event never arrives; with the fix both jobs deliver exactly once. The normal-start control passes on both versions.
- Wall-clock candidate probe: overdue event at 1536 ms, startup rejects with `injected terminal write failure`, fault removed, upcoming event at 12018 ms; delivered events are exactly `["overdue", "upcoming"]`.
- Focused startup/suspension, lazy Gateway, interval firing, and batch-finalization suites: 62 tests passed. The new three-case regression took 1.38 seconds of test time. Normal startup, terminal-write failure, and a second arming failure all deliver each event once after pause/resume. The suspension regression failed on the first candidate before the lifecycle repair.
- Scoped Oxlint and touched-file TypeScript language-server diagnostics passed.
- Fresh `pnpm build` passed; an isolated Gateway boot reached ready on a non-default loopback port. Full Gateway fault injection was not proven: a preinstalled trigger was correctly rejected by schema admission, and a post-admission preload did not reach the worker-owned write. The discriminating failure/recovery proof above uses the real CronService entry point, not a complete faulted Gateway boot.
- Final wall-clock suspension probe: startup reports the injected write error, the fault is removed, scheduling is paused/resumed, and the future event arrives at 12026 ms without replaying the overdue event.
- [Required CI](https://github.com/openclaw/openclaw/actions/runs/36262060415) passed at `3fef502f8eae6604bbc19a398a91e6a8da917bec` with no reruns. The three new regression cases took 1.211 seconds total in the hosted cron shard.

### Published-updater compatibility

[Package Acceptance run 36262657810](https://github.com/openclaw/openclaw/actions/runs/36262657810) passed the existing `published-upgrade-survivor` / `legacy-operator-state` cell: published `[email protected]` updated to the candidate built from `3fef502f8eae6604bbc19a398a91e6a8da917bec` (tarball SHA-256 `8b82f19f0bb40525dd512691d12c0bbf71ef1df8c371323fe271e466a973b57f`). It retained two CLI-authored cron jobs and their history, verified the original owners after migration, and passed Gateway startup, health, readiness, status, and clean Doctor checks. A second update was already-current with no package mutations or repair.

This cell proves upgrade compatibility with retained cron state. Its jobs are deliberately disabled; it does not inject the startup write fault or prove later scheduled delivery. Faulted-startup/future-fire behavior is proved separately by the real CronService wall-clock runs and the real CronService plus Gateway-proxy regression above. The existing published-driver upgrade harness has no startup write-fault injection hook.

Co-authored-by: yetval <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 27, 2026
…nclaw#159086)

Closes openclaw#158969. Related: openclaw#144144.

## What Problem This Solves

Fixes future cron jobs never firing after a startup catch-up job encounters a transient store write failure.

## User Impact

Once the write fault clears, future scheduled jobs can run without restarting the Gateway or editing a job. The startup failure remains visible. No configuration, schema, or default changes.

## Why This Change Was Made

The startup lifecycle owner now arms scheduling when catch-up rejects, then rethrows the original failure, reporting any secondary arming error separately. Failed-start scheduling stays resumable through Gateway suspension; the lazy proxy delegates readiness to the service after any start attempt. Existing stop, pause, and lifecycle-generation fences remain in force. Normal startup ordering is unchanged; existing run-recovery logic settles the completed catch-up job without replaying it.

## Evidence

- Real `CronService.start()` with SQLite persistence: a trigger rejects the overdue job's terminal write, startup rejects, and the trigger is removed before a later job becomes due. On the baseline the later event never arrives; with the fix both jobs deliver exactly once. The normal-start control passes on both versions.
- Wall-clock candidate probe: overdue event at 1536 ms, startup rejects with `injected terminal write failure`, fault removed, upcoming event at 12018 ms; delivered events are exactly `["overdue", "upcoming"]`.
- Focused startup/suspension, lazy Gateway, interval firing, and batch-finalization suites: 62 tests passed. The new three-case regression took 1.38 seconds of test time. Normal startup, terminal-write failure, and a second arming failure all deliver each event once after pause/resume. The suspension regression failed on the first candidate before the lifecycle repair.
- Scoped Oxlint and touched-file TypeScript language-server diagnostics passed.
- Fresh `pnpm build` passed; an isolated Gateway boot reached ready on a non-default loopback port. Full Gateway fault injection was not proven: a preinstalled trigger was correctly rejected by schema admission, and a post-admission preload did not reach the worker-owned write. The discriminating failure/recovery proof above uses the real CronService entry point, not a complete faulted Gateway boot.
- Final wall-clock suspension probe: startup reports the injected write error, the fault is removed, scheduling is paused/resumed, and the future event arrives at 12026 ms without replaying the overdue event.
- [Required CI](https://github.com/openclaw/openclaw/actions/runs/36262060415) passed at `3fef502f8eae6604bbc19a398a91e6a8da917bec` with no reruns. The three new regression cases took 1.211 seconds total in the hosted cron shard.

### Published-updater compatibility

[Package Acceptance run 36262657810](https://github.com/openclaw/openclaw/actions/runs/36262657810) passed the existing `published-upgrade-survivor` / `legacy-operator-state` cell: published `[email protected]` updated to the candidate built from `3fef502f8eae6604bbc19a398a91e6a8da917bec` (tarball SHA-256 `8b82f19f0bb40525dd512691d12c0bbf71ef1df8c371323fe271e466a973b57f`). It retained two CLI-authored cron jobs and their history, verified the original owners after migration, and passed Gateway startup, health, readiness, status, and clean Doctor checks. A second update was already-current with no package mutations or repair.

This cell proves upgrade compatibility with retained cron state. Its jobs are deliberately disabled; it does not inject the startup write fault or prove later scheduled delivery. Faulted-startup/future-fire behavior is proved separately by the real CronService wall-clock runs and the real CronService plus Gateway-proxy regression above. The existing published-driver upgrade harness has no startup write-fault injection hook.

Co-authored-by: yetval <[email protected]>
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

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

2 participants