Skip to content

refactor(cron): move scheduling into the worker actor - #169766

Merged
steipete merged 9 commits into
mainfrom
upd/upd-l1560
Oct 12, 2026
Merged

steipete merged 9 commits into
mainfrom
upd/upd-l1560

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Cron scheduling and job edits still split decisions between the Gateway host and SQLite worker after the worker-owned run-queue cutover. This moves scheduling into the worker and repairs the CI failures that exposed incomplete timing, import-boundary, and session-authority cutovers.

Refs #168072.

Current head: 210b8139c7e2229fd77d76e1072d4bf1102c0e82.

User Impact

Preserves cron timing, catch-up, pacing, retries, and job-edit behavior across Gateway restarts. Scheduled runs retain the creator’s stored workspace authority, including managed-worktree ownership and file containment. No schema/DDL, dependency declaration, public configuration, or CLI change. Doctor still backs up and preserves historical ownership before repair; ordinary startup clears obsolete disabled-job deadlines without rewriting owners.

The accepted crash semantics remain: a crash after activation but before dispatch may miss one occurrence, and one launch can race an operator disable. Transient event payloads lost across restart are recorded as skipped rather than reconstructed.

Why This Change Was Made

One retained worker actor owns timers, due-slot selection, bounded catch-up, durable deferral, and CRUD/declarative schedule decisions. The host pushes versioned configuration snapshots between commands and launches committed requests. The existing shared-state worker lease retains the actor and joins shutdown. Removed the host timer, catch-up, scheduler-mutation, and startup-plan paths.

The CI repairs keep mutation preparation independent of delivery routing, preserve pending deadlines during ordinary refresh, repair stale future slots on active ticks, and defer overflow until the initial catch-up receipts settle. Settlement clears an obsolete catch-up marker after a manual completion without changing its cadence. Configuration capture resolves a default owner only when needed and no longer replaces the service's accepted cron settings with unrelated global snapshots.

The latest authority repair keeps the complete session comparison and normalizes only absent optional fields. The initial worker read omitted owner, participants, and participantCount; the newer creation-receipt cache returned the same absent values as explicit undefined fields. Strict object comparison rejected that representation change before task execution. All defined creator, owner, workspace, and lifecycle fields remain compared. The existing end-to-end permission assertions are unchanged; the status assertion now includes the recorded run error. A focused regression models both reader representations and proves that an actual persisted workspace change still rejects admission.

Tests that depended on removed host timer internals now drive the real worker notification listener or assert the worker's committed wake deadline. This applies to timer.test.ts, service.timer-maintenance.test.ts, service.cross-tick-admission.test.ts, and the deferred one-shot in doctor-config-flow.cron-owners.test.ts. Timing, persistence, execution count, and admission assertions remain. Recovery tests now fail immediately if the run settles before its expected payload starts, instead of hanging for 120 seconds. The import-boundary test is unchanged. The additional lifecycle fixture now seeds valid disabled rows, and its spy cleanup runs even when a pending tick rejects; no responsiveness or reply-loss assertion was removed.

Against base ac5432479226a46259c303ad3a8907fc8ad310fe: production +1,949 / −1,847 (net +102; 3,796 changed lines); tests/support +1,548 / −717; docs/config +9 / −1. The only baseline change is deletion of the retired timer assertion. The campaign's net-negative production requirement is not met. Further removal of obsolete reservation and host-finalization machinery needs a separate, behavior-proven cutover; this repair does not claim that gate is complete.

Evidence

  • Latest CI run 38237124225 tested merge ff28a956c7feeb7e9d9fb8f449b087a88037bc80 (tree 6acbc8ba30e8b0f4a90ca6d0801a9704f92e87c0). The branch alone passed, so reproduced that exact merge in a disposable source fixture inside the assigned worktree, using Node 24.19.0. It reproduced both original workspace failures: 2 failed / 5 passed. Diagnostics showed identical stored values but three extra undefined properties in the cached entry. After the cron-only repair, 12/12 focused tests passed in 52.14s (55.88s wrapper), including all seven original workspace-authority cases. The disposable fixture was removed; no main integration or unrelated tracked edit was needed.

  • New regression negative control: before the repair, identical authority presented with absent-versus-undefined fields fails admission; a real persisted workspace change also rejects. After repair, the identical-authority case passes and the changed-workspace case still rejects. Creator provenance, foreign-session denials, archived sessions, managed ownership, and file containment assertions remain intact. No permission was broadened and no assertion was weakened.

  • Final local proof: 52 isolated-agent files / 540 tests passed, plus the importing Gateway usage owner-attribution file 9/9 passed. Combined 53 files / 549 tests, 391.15s wall; cron Vitest duration 326.79s, Gateway duration 56.47s. The new regression owner file spent 19.421s in its five cases; the largest individual test in the complete run was 9.380s. An earlier eight-file CI-subset replay passed 153/153. Targeted cron types passed (8.6s), exact changed-file lint and format passed, final Madge reports 0 cycles, and a fresh isolated Codex repair review found no actionable P0/P1 findings.

  • The wrapper inventory failure is inherited: the full log names src/config/sessions/transcript-entry-anchor.ts, newly imported by session-accessor.sqlite-transcript-anchor.ts on the tested main base. Main commit 777e85c9eece introduced that runtime edge; main already fixes the inventory in 9e4f18346b8d. This lane changes neither module nor the inventory.

  • Latest check:changed --base HEAD passed all preceding guards, production types, and all 28 core-test graphs (259.33s), then stopped at the same inherited dead exports: resolveEffectivePromptTokens and renderPublicSessionCardSvg. Both files are unchanged by this lane. All nine trailing checks were run separately and passed, including exact changed-file lint, schema, storage, media, sidecar, runtime-cycle, and webhook/pairing checks. No baseline or unrelated owner was edited.

  • Original CI run 38228289309, head c0038e5e618dfd8ce918da002501d73392f84c79: fetched the three failed job logs once; 18 failed cases across small-3, small-7, and small-11. Reproduced the owner failures locally before fixing them.

  • Focused repair proof: 62 passed across eight cron files and the Doctor cron-owner file. Cron duration 43.17s; Doctor 149.25s. Recovery cases now take 92ms–1.35s instead of four 120-second CI timeouts. The unchanged Doctor delivery/maintenance path took 32.8s in one case on this shared Mac (the same case took 4.5s in the saved CI log). An unchanged heartbeat-routing sibling waits for the production 30-second minimum-spacing policy with fake timers disabled (30.8s); recorded for its owner without editing outside cron. No timeout increases, retries, or weakened assertions.

  • Negative controls: restoring the delivery runtime import fails with “Startup commands must not load delivery resolution”; restoring expired-slot recomputation during ordinary refresh fails because the pending run settles as not-due before its payload starts.

  • Full saved cron replay: 30 files / 238 tests passed (219.46s wall); the service replay reported 105/106 files passing, 784 passed / 2 fixture failures (459.25s wall). Those failures came from recreating invalid disabled-job deadlines and leaking a worker spy during failed cleanup. Corrected that idle fixture and guaranteed cleanup without changing its assertions. The final three-file proof passed 19/19 cases (18.77s wall, 15.90s Vitest duration), including both failures. Also replaced the obsolete host wake in service.list-past-due.test.ts: 61.849s → 1.136s with every assertion retained. No full service replay was repeated after these test-only corrections; unchanged passing source is retained evidence. All 122 importing sibling files / 1,882 tests passed (1,809.38s wall). All four E2E files / 19 tests passed (290.30s wall including runtime build; 65.79s Vitest duration).

  • Targeted type graphs core-test-services-cron, core-test-commands, and core-test-commands-doctor passed in 2.0s / 9.8s / 8.6s. Madge reports 0 cycles. check:changed passed production, all core-test and root-test types, formatting, boundaries, and preceding guards, then stopped at two inherited dead exports: resolveEffectivePromptTokens and renderPublicSessionCardSvg. Every trailing check was run separately: scripts lint, schema, database ownership, media, sidecar, runtime cycles, webhook/pairing boundaries, and root helper lint passed. Full-core lint found one cron test shadowing error (now corrected and checked separately) plus 13 inherited errors in unchanged files. Final targeted lint passed for all three corrected cron files. Final cron types passed again in 2.6s; line-cap ratchet passed with no growth; git diff --check passed. The aggregate gate remains red; no unrelated owner or lint baseline was changed.

  • Fresh candidate recovery from consistent copies created by released [email protected] (e178c39): both retained integrity_check: ok and schema version 20. The pending copy's eight active receipts became interrupted; unrecoverable queued work was skipped. At the current clock, five (clean copy) and two (pending copy) due synthetic jobs executed. Both retain 11 jobs after the existing loader retires one obsolete system job. No operator state was used.

  • Prior isolated real timer/notification/launcher proof executed two one-shots and removed both (remainingJobs: 0). This proves transport and rearming, not latency on the shared host.

  • Publication: the repair is pushed at 210b8139c7e2229fd77d76e1072d4bf1102c0e82. The PR remains ready; final exact-head CI is left to run. No CI completion or merge is claimed.

  • A fresh isolated Codex review of the repair diff completed with no actionable P0/P1 findings. The complete redesign still needs maintainer review; the earlier whole-lane review attempt was unavailable. No merge was attempted.

Inherited full-core lint findings (all files unchanged from the pinned base)
Path Rule
ui/src/e2e/model-providers.e2e.test.ts eslint(max-lines)
src/plugins/registry-runtime-session-ownership.ts eslint(max-lines)
ui/src/pages/chat/components/chat-detail-panel.tsx eslint(max-lines)
ui/src/pages/chat/components/chat-message-images-solid.tsx eslint(max-lines)
src/cli/update-cli/update-command-post-update.ts eslint(max-lines)
src/agents/isolated-completion.ts eslint(max-lines)
src/auto-reply/reply/dispatch-from-config.choose-route.ts eslint(max-lines)
src/gateway/server-methods/chat-abort-runtime.ts eslint(max-lines)
src/agents/worktrees/checkout.ts eslint(max-lines)
src/gateway/session-worktree-preparation.ts eslint(max-lines)
src/agents/tools/sessions-send-tool.ts eslint(max-lines)
src/plugin-state/plugin-state-store.ts eslint(max-lines)
ui/src/components/session-group-defaults-dialog.tsx typescript(no-misused-promises)

Retain the shared state worker for cron timers and push versioned configuration between commands. Keep due selection, bounded catch-up, durable deferral, and CRUD schedule decisions with worker-owned rows; remove the host scheduling paths.

Preserve completion-owned cadence and existing receipt recovery without a schema or public-option change. Refs #168072.
@clawsweeper

clawsweeper Bot commented Oct 12, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: XL labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR moves cron timers, catch-up planning, configuration snapshots, and job-edit decisions into the existing SQLite worker.

Example: The Gateway starts with seven overdue command jobs.

  • Before: The host selects five immediate jobs and coordinates staggered overflow.
  • After: The worker selects those jobs and persists the deferred deadlines.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful approved consolidation with meaningful boundary coverage, but the unresolved startup-recovery defect prevents merge.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its body reports real timer/notification/launcher execution and released-copy recovery, and the inspected authority harness exercises allowed and forbidden file access through production owners.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: Split scheduling ownership makes cron reliability and Gateway writer contention harder to maintain.
Reason: The maintainer-authored change implements the approved scheduling stage and removes its superseded host paths.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Needs changes before merge - 3 items remain

Keep this PR open: the approved worker consolidation is useful, but the previously reported startup-recovery regression remains unresolved.

Priority: P2
Reviewed head: e7dcd08f8caf0caf2905dce8489f6e5ea7716b22

Before merge

  • Retain a recovery wake when initial actor startup fails (P2) - With an overdue command job and a future job loaded, a transient failure in boundedCatchup or requestCronRunsInWorker rejects cron.schedulerStart before started becomes true. This catch closes the connection and releases the actor before armActor installs its timer, so future jobs never resume after the fault clears. Current main rearms scheduling after the corresponding failure. Preserve automatic recovery in the scheduler lifecycle and extend the public-start regression to inject an initial write failure. This finding remains unresolved from the previous review.
  • Complete next step - Resolve GitHub's reported merge conflicts against main and validate the affected paths on the resulting head.
  • Explain or restore the original intent of Failed-start scheduling recovery - 0f5c39b: Future jobs must resume automatically after startup catch-up fails while the original error remains visible.

Findings

  • [P2] Retain a recovery wake when initial actor startup fails — src/cron/service/scheduler-actor.ts:156-159

Provenance

  • Failed-start scheduling recovery changes intended behavior without addressing why it exists (0f5c39b: Future jobs must resume automatically after startup catch-up fails while the original error remains visible.)

Tests

  • Missing end-to-end proof: The startup regression does not exercise an initial catch-up or receipt-insert write failure followed by automatic execution of a future job.
Agent review details

How this fits together

Cron receives Gateway commands and configuration, persists jobs and run receipts in SQLite, and sends committed requests to the host launcher.

flowchart LR
A[Gateway commands and configuration] --> B[Cron worker actor]
B --> C[SQLite jobs and receipts]
B --> D[Wake notification]
D --> E[Admitted host tick]
E --> B
B --> F[Host launcher]
F --> G[Task executor]
Loading

Technical review

Best possible solution:

Keep the worker as the sole scheduler while preserving automatic recovery after its initial startup write fails.

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

Source establishes the failure path with an overdue command job, a future job, and a rejected initial catch-up or receipt write; this read-only review ran no reproducer.

Is this the best way to solve the issue?

Consolidating scheduling in the existing worker follows the approved design, provided initialization preserves the established failed-start recovery contract.

Full review comments:

  • [P2] Retain a recovery wake when initial actor startup fails — src/cron/service/scheduler-actor.ts:156-159
    With an overdue command job and a future job loaded, a transient failure in boundedCatchup or requestCronRunsInWorker rejects cron.schedulerStart before started becomes true. This catch closes the connection and releases the actor before armActor installs its timer, so future jobs never resume after the fault clears. Current main rearms scheduling after the corresponding failure. Preserve automatic recovery in the scheduler lifecycle and extend the public-start regression to inject an initial write failure. This finding remains unresolved from the previous review.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 70885c1bbbda.

Provenance checked

  • Timer and catch-up ownership changes intended behavior with a stated reason (06776e7: Separate timer responsibilities while preserving scheduling, retry, timeout, and delivery behavior.)
  • Guarded job mutations keeps the original intent (2ef0b10: Move guarded writes into the worker while preserving authority facts and atomic job/receipt updates.)
  • Run queue and launcher keeps the original intent (0973bef: Centralize durable requests, queue order, capacity, and activation while retaining final launch checks and accepted crash semantics.)
  • Session ownership comparison keeps the original intent (80a4407: Reduce isolated-session database work while preserving existing effect-authority checks.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/cron/service/ops-lifecycle.start-arm.test.ts --maxWorkers=1
  • pnpm test src/cron/store/scheduler-actor.worker.test.ts --maxWorkers=1
  • pnpm test src/cron/service.armtimer-tight-loop.test.ts --maxWorkers=1
  • pnpm test src/gateway/server-cron.drain.test.ts --maxWorkers=1
  • Verify the initial-write-failure regression fails before the repair and passes afterward.

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 0973bef adds src/cron/service/ops-lifecycle.ts:21 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0973bef32bcc; files: src/cron/service/ops-lifecycle.ts)
  • Ayaan Zaidi: Raw commit 0f5c39b adds src/cron/service/ops-lifecycle.start-arm.test.ts:40 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0f5c39b9e0a5; files: src/cron/service/ops-lifecycle.start-arm.test.ts)
  • Vincent Koc: Raw commit ca90c24 adds src/cron/service/jobs-scheduling.ts:648 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: ca90c2488899; files: src/cron/service/jobs-scheduling.ts)

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
Production versus test/support LOC Production +1,949 / −1,847; tests/support +1,548 / −717 The verified introduced diff removes the superseded host scheduler but adds 102 net production lines; the broader deletion stage remains separate.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A transient initial cron write failure can strand future scheduling; widespread current user incidence is not established.
  • merge-risk: 🚨 availability: Initial-startup cleanup can leave automatic cron scheduling inactive after the underlying fault clears.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-12T08:54:34.565Z sha cea4c09 :: needs changes before merge. :: [P2] Retain a recovery wake when initial actor startup fails
  • reviewed 2026-10-12T09:20:01.202Z sha c0038e5 :: needs changes before merge. :: [P2] Retain a recovery wake when initial actor startup fails
  • reviewed 2026-10-12T10:43:28.144Z sha 9ae899d :: needs changes before merge. :: [P2] Retain a recovery wake when initial actor startup fails
  • reviewed 2026-10-12T11:21:16.181Z sha 210b813 :: needs changes before merge. :: [P2] Retain a recovery wake when initial actor startup fails

Reviewed October 12, 2026, 7:38 AM ET / 11:38 UTC (Revision 5).

@steipete
steipete marked this pull request as ready for review October 12, 2026 09:11
@openclaw-barnacle openclaw-barnacle Bot added the commands Command implementations label Oct 12, 2026
Compare the same defined ownership facts across SQL rows and cached session snapshots. Preserve creator, workspace, and lifecycle checks while avoiding false admission conflicts from undefined optional metadata.
Merge main at 70885c1 while preserving
worker-owned scheduling and main's prepared-session reuse optimization.
Move completion maintenance coverage into the existing batch fixture.
Keep runtime selection consistent with reported harness provenance and
request the lifecycle facts used by real cron preparation in dispatch tests.
All existing expected values and refusal assertions remain intact.

Evidence: 189 cron files exercised (1568 tests); four fixture failures were
reproduced and corrected. All four affected files then passed, 41 tests in
45.02s (51.54s wrapper). The other 187 files passed unchanged. Cron test
types, focused lint, Madge (zero cycles), and isolated P0/P1 review pass.
Manual edits remain in four cron test files; no production or UI repair.

Refs #168072.
@steipete
steipete merged commit b943945 into main Oct 12, 2026
128 of 129 checks passed
@steipete
steipete deleted the upd/upd-l1560 branch October 12, 2026 12:02
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…169766)

Cron PR 2b-ii of the worker-owned redesign (docs/refactor/cron-worker-owned.md): the cron worker now owns timers, catch-up, pacing, schedule computation and CRUD reconciliation; the host pushes config snapshots and launches committed requests. Host scheduling paths are removed. Also: mutation validation no longer loads delivery routing, pending deadlines survive the cutover, catch-up overflow settles after initial receipts, startup clears stale disabled deadlines, and cached snapshot metadata no longer reads as changed workspace authority. No schema, config or CLI change. Refs openclaw#168072.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant