Repository navigation
fix(cron): scheduled jobs stay stopped after a native worker exits - #194048
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesReconnects cron scheduling after native worker loss and retries failed replacement starts with bounded backoff. Example: The SQLite worker exits after the 04:36 scheduled run while the Gateway remains running.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR fixes a current scheduler recovery defect, and the new retry loop resolves the previous finding; no additional actionable defect was found. Priority: P1 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe Gateway cron connection submits scheduling operations to the shared-state SQLite worker and launches its committed run requests through the existing durable queue. flowchart TD
A[Native worker loss] --> B[Shared state lease]
B --> C[Cron connection owner]
C --> D[Lifecycle and database checks]
D --> E[Scheduler restart with backoff]
E --> F[Existing durable run queue]
Technical reviewBest possible solution: Land scheduler-owned reconnection with retry while preserving the existing lifecycle, database-admission, and durable-run owners. Do we have a high-confidence way to reproduce the issue? Current-main source retains a permanently closed scheduler lease, and the supplied built-Gateway comparisons demonstrate stopped scheduling after worker exit or OOM; no target code was executed during this review. Is this the best way to solve the issue? The change uses the existing connection and lease owners, joins old work, and restarts through durable scheduling rather than replaying failed mutations; each added production hunk serves that repair. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 082ed658f463. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +89. Total +89 across 3 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReviewed November 11, 2026, 11:46 PM ET / November 12, 2026, 04:46 UTC (Revision 3). |
# Conflicts: # src/cron/service/scheduler-actor.ts
|
Maintainer proof for the merged head (main Setup. Built Gateway ( The fault. The shared-state SQLite worker is a worker thread inside the Gateway process, so it can't be killed as a separate OS process. Instead we stopped it from outside with no OpenClaw code change and no preload.
Run history ( Controls
Worker kill client (proof only, runs outside the Gateway)const [port, mode] = process.argv.slice(2);
// node kill-worker.mjs <inspectorPort> <exit|oom|list>
const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
const ws = new WebSocket(targets[0].webSocketDebuggerUrl);
// NodeWorker.enable -> attachedToWorker for every worker thread
// per worker: Debugger.enable, collect scriptParsed URLs
// shared-state carrier = the thread whose scripts include "openclaw-state.worker"
// then Runtime.evaluate in that thread:
// exit: process.exit(1)
// oom: for (;;) fill.push(new Array(1e6).fill(Math.random()))PR changes on top of the contributor's commit: merged current main, resolving the |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Follow-up for the ClawSweeper P1 (a single reconnect attempt that fails is never retried), at head Change. Recovery is now a single retry loop per cron service. If the replacement scheduler fails to start, because the dead store is still held or its worker dies during startup, the lost slot is put back. The loop waits 250 ms, doubling up to 30 s, and tries again. It stops when a scheduler is running, or when cron is paused, stopped or changes generation. Pause, stop and admission checks are the same as before. Waits end early on shutdown. A replacement that loses its worker during startup no longer starts a second, competing recovery. Proof (same container and harness as before). The new "storm" fault ends the shared-state worker. It then ends each replacement worker as soon as that worker loads the shared-state module, which is while cron's reconnect is still starting. The faults come from outside through the Node inspector; no OpenClaw code is changed.
The single-kill case still works on this head (cand2-1: kill at 04:39:17, reconnect at 04:39:19, run at 04:40:00). A busy-worker variant ran on the previous head: six |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Thanks @obviyus for updating this against current main, resolving the borrowed-lease conflict, and exercising the real Gateway lifecycle controls and replacement-worker storm. The important follow-up is the failed-start retry at The original concurrent-borrower incident timing remains unforced; the demonstrated recovery from repeated replacement-start failures should not be presented as reproducing that exact incident. Your code updates and the Gateway matrix replacing the earlier recovery unit suite are preserved. No new execution or merge is claimed by this acknowledgement. |
…penclaw#194048) fix(cron): recover the scheduler after the shared-state worker is lost When the shared SQLite worker hosting cron exited while the Gateway kept running, for example when it ran out of its 512 MiB heap, cron kept its closed connection. Every refresh then failed with "Shared-state worker lease is closed", status still reported cron enabled with a wake time in the past, and nothing ran until a restart. Cron now reacts to the existing worker-lost signal on its persistent lease: it closes the dead connection and starts a replacement scheduler, retrying with a capped backoff if the replacement fails to start, and stops retrying when a scheduler is running or cron is paused, stopped or changes generation. Paused scheduling, intentional shutdown, database retirement and a moved state folder do not trigger recovery. Stored formats are unchanged. Recovery adds two operator log lines. Evidence: a built Gateway in a secretless node:24.22.1 container with a one-minute command automation, the shared-state worker thread ended from outside through the Node inspector by exit or by exhausting its heap, with the Gateway process staying up, two runs each. On main, every refresh after the loss failed with "lease is closed", no later slot ran and the next wake stayed in the past; with this change cron reconnected once and the next slots ran once each, matching run history with no duplicates. Ending each replacement worker during startup left main's previous recovery stuck, and this head retried and recovered. Paused scheduling, SIGTERM shutdown, an in-process restart and a moved state folder behave as intended. Details: openclaw#194048 (comment) and openclaw#194048 (comment). Closes openclaw#194032. Thanks @indra622. Co-authored-by: Ayaan Zaidi <[email protected]>
Backport #194048 with an abortable-timer adaptation for the stable baseline. Retain one recovery owner and prove native replacement loss and delivery. Co-authored-by: Ayaan Zaidi <[email protected]> Co-authored-by: RomneyDa <[email protected]>
Port the stable native-loss regression from a77c494 and add the accepted bounded failure-only transport trace. Main contains the production recovery from #194048 but not this regression, so the main delta is 156 test lines (85 original plus 71 diagnostic lines). Keep original faults, assertions, deadlines and cleanup. Observe scalar open/start replies, native exits and existing recovery logs only; transport success is not lease readiness. No production changes or claim that the unresolved release scheduler failure is fixed. Parent reviewed the complete candidate and accepted diagnostic patch e416e0c441ed9fb5e2f2f802a8e9d791150157a84be25274e40914eda3adde34. Co-authored-by: Hosung Park <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]> Co-authored-by: vincentkoc <[email protected]> Co-authored-by: RomneyDa <[email protected]>
Port the stable native-loss regression from a77c494 and add the accepted bounded failure-only transport trace. Main contains the production recovery from #194048 but not this regression, so the main delta is 156 test lines (85 original plus 71 diagnostic lines). Keep original faults, assertions, deadlines and cleanup. Observe scalar open/start replies, native exits and existing recovery logs only; transport success is not lease readiness. No production changes or claim that the unresolved release scheduler failure is fixed. Parent reviewed the complete candidate and accepted diagnostic patch e416e0c441ed9fb5e2f2f802a8e9d791150157a84be25274e40914eda3adde34. Co-authored-by: Hosung Park <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]> Co-authored-by: vincentkoc <[email protected]> Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit 112ba9e) Adaptation: candidate already contains the original 85-line test; retain it and apply only the reviewed 71-line diagnostic delta. Co-authored-by: vincentkoc <[email protected]> Co-authored-by: RomneyDa <[email protected]>
…203104) Port the stable native-loss regression from a77c494 and add the accepted bounded failure-only transport trace. Main contains the production recovery from openclaw#194048 but not this regression, so the main delta is 156 test lines (85 original plus 71 diagnostic lines). Keep original faults, assertions, deadlines and cleanup. Observe scalar open/start replies, native exits and existing recovery logs only; transport success is not lease readiness. No production changes or claim that the unresolved release scheduler failure is fixed. Parent reviewed the complete candidate and accepted diagnostic patch e416e0c441ed9fb5e2f2f802a8e9d791150157a84be25274e40914eda3adde34. Co-authored-by: Hosung Park <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]> Co-authored-by: vincentkoc <[email protected]> Co-authored-by: RomneyDa <[email protected]>
Fixes #194032
What Problem This Solves
Fixes scheduled jobs staying stopped after their shared-state native worker exits while the Gateway keeps running.
User Impact
Eligible jobs resume on the same running service after recoverable worker loss. Paused scheduling stays paused; intentional shutdown or database retirement does not restart it. The original incident's trigger is unknown, so this does not attribute it to OOM.
Why This Change Was Made
Forward the existing native-loss fact to cron's connection owner. Drain the old work and native custody, recheck the original database admission and current service lifecycle, then use the existing scheduler/receipt path to reconnect. No new schema, persistence contract, permissions, configuration, timer framework, or failed-mutation replay.
Evidence
/usr/bin/printfcommand jobs with delivery disabled. After real native worker termination, the second job executes autonomously exactly once, the first complete run-history entry is unchanged, and the Gateway PID stays the same. Owned Gateway and port-helper exits are both 0. No model or external delivery is used.cliStartupbuild and bootstrap guard pass; a full release/UI/declaration build and hosted CI are not claimed.f7a46e85d26ad28de5eba194a386731ed28a518f..fd186b2b53d0aaee0f2d5dd4ee44259bfabe333bfound no actionable issue. Source/test hashes match the precommit review. Local autoreview/ClawSweeper was not run.The original production trigger and an active-SQL-write fault are not reproduced. The base red is the real-worker service boundary; the Gateway scenario covers the fixed candidate. Setup attempts rejected before startup or waiting on obsolete readiness wording are not counted as product reds. A separate terminal-upload temp-root warning was unrelated to this no-upload scenario.
Maintainer update: merged current main (conflict with #196387 resolved; the native-loss callback attaches only to the persistent lease that exists while cron is enabled). The worker-recovery unit suite and its test-lines allocation were removed; the built-Gateway matrix below replaces it (main twice, candidate twice, plus pause, shutdown, in-process restart and moved-state-folder controls): #194048 (comment). Recovery now retries with backoff until a live store answers (ClawSweeper P1); proof: #194048 (comment). Production delta against main +97/-8; tests 0.
Portable reproduction and actual CLI/Gateway evidence
Real cron worker-loss proof: issue #194032
Fixed source commit:
fd186b2b53d0aaee0f2d5dd4ee44259bfabe333b. Base:f7a46e85d26ad28de5eba194a386731ed28a518f. Node v24.22.1, pnpm 12.15.0, macOS arm64. The isolated Gateway reported OpenClaw 2026.11.1.What ran
The real OpenClaw launcher (
node openclaw.mjs gateway run) started an isolated, loopback-only Gateway. Public CLIcron add,cron runs, andcron statuscommands communicated with it. Two admin-authored command jobs invoked/usr/bin/printf, with delivery disabled, and used the real cron store, shared-state native worker, scheduler, command executor, and durable run history. No model request or external delivery was needed.A proof-only Node preload observed the worker's existing
postMessageboundary without changing messages. It selected the actual worker receivingcron.scheduler*commands and called that Worker's realterminate()on a test signal. The Gateway process stayed alive and kept the same PID. This is real native worker loss, not a mocked lease rejection. The test signal was SIGWINCH, not OpenClaw's SIGUSR2 restart signal.Before/after evidence
Before production editing, the real
CronServiceintegration scenario at the base completed its first scheduled no-op, recorded its durable result, terminated the native shared-state worker, and then stalled waiting for the second scheduled no-op. The milestone trace was:This red reached the actual defect rather than failing setup. Production code was still at the base. The committed table-driven regression retains that recovery scenario and adds pause/resume, stop, and intentional database-retirement controls.
The fixed isolated Gateway/CLI run observed:
The runner's phrase “prior receipt unchanged” refers to exact equality of the full durable run-history entry returned by the public CLI. Private run IDs encode the isolated store path and are intentionally omitted here.
Sanitized projection of the actual CLI results:
{ "outcome": "passed", "gatewayPidUnchanged": true, "nativeWorkerExited": true, "beforeRun": { "jobName": "proof-before-loss", "status": "ok", "completionStatus": "succeeded", "summary": "proof-before-loss", "durationMs": 9, "deliveryStatus": "not-requested" }, "afterRun": { "jobName": "proof-after-loss", "status": "ok", "completionStatus": "succeeded", "summary": "proof-after-loss", "durationMs": 8, "deliveryStatus": "not-requested" }, "beforeRunHistoryUnchanged": true, "eachJobRunCount": 1, "schedulerEnabled": true, "gatewayExit": 0, "portClaimExit": 0 }There was no manual run, job edit, cron-service replacement, or Gateway restart after the native fault. The second job had already been created before fault injection. Polling
cron runsonly observed completion. Each job had exactly one successful history entry, with deliverynot-requested; the first entry was unchanged after recovery.Build and focused validation
The repository runtime/CLI build profile ran before the Gateway scenario:
Exit 0; 44.2 seconds; CLI bootstrap import guard passed. It builds runtime JavaScript and startup metadata; this is not a full release/declaration/UI build. Build metadata still named the base because the local commit was created afterward. The built recovery algorithm/source snapshot is the one subsequently committed; the only later source adjustments were a callback-local rename and erased test generic typing, with no recovery behavior change. Parent-reviewed source hashes match the final commit.
The new file's final standalone wall time was 30.65 seconds including 23 seconds of compilation; the four actual tests took about 4.48 seconds total (1.56, 1.26, 0.84, 0.82 seconds). CI seconds are not yet available. The real native timer is exercised because injecting only a host wake would bypass the stalled worker-owned timer. No new test-only production hook was added.
Targeted typecheck, lint and formatting passed, as did the exact 120-line test allocation ratchet and
git diff --check. The state/queue suites retain the existing accepted-write, native-cleanup, receipt and uncertain-settlement checks; no failed mutation is explicitly replayed by this repair.Portable reproduction
Use a disposable local directory on a sufficiently large safe filesystem, a checkout containing the fixed commit, Node v24.22.1 and pnpm 12.15.0. Install dependencies physically in that checkout with a local store. Never point this scenario at operator state or an existing Gateway.
cliStartupcommand above.gateway.mode: local, loopback binding, a claimed free port, a fresh local token,agents.ownership: explicit,agents.entries.main: {},cron.enabled: true, and disabled plugins/browser/Control UI. The successful scenario used no ambient credentials. Keep the token private.OPENCLAW_HOME,OPENCLAW_STATE_DIR,OPENCLAW_CONFIG_PATH,TMPDIR,NODE_COMPILE_CACHEandNODE_OPTIONS=--import=<fault-worker.mjs>. Wait for[gateway] ready; retain the port claim through shutdown. The repository'sacquireTestPortBlockfromsrc/test-utils/port-claims.tssupplied the claim in the recorded run.okresult per job, full equality of the first history entry before/after, and unchanged Gateway PID. Stop only this owned Gateway with SIGTERM, await exit, and release the port claim. Both owned process exits were 0 in the successful run.Exact proof-only preload (
fault-worker.mjs):This fixture belongs only to the disposable Gateway. It forwards every original worker message unchanged and terminates only the worker selected by actual cron scheduler commands. Do not preload it into a production Gateway or send its signal to any unrelated process.
Limits and setup history
The original production trigger remains unknown; this proves recovery from deliberately induced idle native loss and does not establish OOM or reproduce the reported nine-hour incident. The real Gateway scenario covers the fixed path; the exact base red is the real-worker service boundary, not a second base Gateway build. Existing state/queue tests support settlement safety; there is no new claim to have faulted an active SQL write in the Gateway scenario.
A first fixture used the retired
agents.listconfig and failed before startup. A second Gateway was healthy but the orchestration waited for an obsolete listening-log format; that setup attempt was intentionally canceled and drained. Neither is counted as a product red. The successful third attempt used the observed[gateway] readysignal. The Gateway also logged an unrelated terminal-upload temp-root warning for the validation volume's ancestor permissions; no upload was used, and the command jobs/receipts completed successfully. No mount permissions or global settings were changed.No live accounts, external sends, user Gateway changes, or publication occurred. Parent source review is separate from publication. All task-owned runtime/test/build processes were joined and stopped; requested evidence was retained.