Skip to content

refactor(cron): finish worker-owned results and recovery - #169946

Merged
steipete merged 3 commits into
mainfrom
upd/upd-l1561
Oct 12, 2026
Merged

steipete merged 3 commits into
mainfrom
upd/upd-l1561

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Cron completion and restart recovery still had competing host-side receipt settlement and recovery paths after scheduling moved to the worker.

Refs #168072.

User Impact

Execution and primary-delivery outcomes are recorded with job state and history. On restart, recorded terminal results are restored once; uncertain active runs are interrupted without replaying their payload or delivery. Timed queued requests can resume; requests whose transient payload was lost are recorded as skipped. Manual run IDs remain available for exact history lookup.

This deliberately accepts a potentially missed occurrence after a crash to avoid uncertain payload or delivery replay. There are no schema, configuration, CLI-option, dependency, or permission changes. Existing task, transport, heartbeat, and permission owners retain their live-effect checks and provenance.

Why This Change Was Made

The worker owns terminal accounting and startup recovery in synchronous transactions. The host publishes committed facts and dispatches post-run notifications asynchronously. Receipt custody, nonce settlement, receipt-authority binding, foreign-receipt monitoring, obsolete registrations, and private protocol tests are removed together. Completion preserves newer job edits and settles the next deadline before publishing the finished event. Shutdown joins owned work and reports cleanup failures as warnings. A lost finalization reply invalidates public views without replaying execution.

Execution-identity audit coverage is preserved: after admission, the launcher records one opt-in context/execution link to the existing receipt through the worker and existing lazy binding store. The first admitted execution keeps that diagnostic link; duplicate trigger/payload admissions cannot replace it. Failed writes warn without aborting execution. Disabled/default collection allocates neither a binding table nor rows. Readers and deletion retain their existing contract; no receipt authority or settlement machinery is restored. Gateway handoff and shutdown proof remains at the real boundary, including the terminal worker command. The rebase preserves main's independent test pruning and removal of the generic reader capture helper. UI and the general SQLite admission mechanism are untouched.

Evidence

  • Audit-coverage regression first failed on the uncorrected candidate because no lifecycle binding table existed (1 failed, 2 passed; 47.47 s wall). With the fix, all 3 enabled/disabled/default cases passed in 31.69 s wall (test bodies 1.126/0.946/0.943 s; worker preparation 18.794 s). The test runs scheduled work through real admission, makes distinct trigger/payload admissions, verifies one retained link, and inspects the terminal receipt through the audit presenter. It also verifies disabled/default collection creates no optional table.
  • Before the final rebase, audit-restoration full selection on 0e7320ea873d: 139/139 files and 1,274/1,274 tests passed, no unrun files and no reruns. node scripts/run-vitest.mjs <selected audit/cron/owner-sibling files> --maxWorkers=1 reported [test] passed 6 Vitest shards in 1250.50s; wall time was 1251.19 s. Shared runtime build took 268.7 s (tsdown 244.5 s); the longest reported individual test was 12.223 s. Shards: unit 11 files/89 tests/17.77 s; Gateway 4/107/63.63 s; infrastructure 14/176/95.15 s; cron 106/866/449.97 s; Doctor 1/18/118.49 s; E2E 3/18/59.76 s. Doctor test bodies totaled 100.701 s. All 17 audit files, the new scheduled-run identity regression, and direct/one-barrel owner siblings were included. The plugin-reload cases passed in this order; that is current-run proof, not a fix for the independently reproduced admission leak below.
  • Final conflict resolution rebased onto f458771780dd1384163965c1d81e330010e8e65b: preserved main's no-write history-maintenance fast path and this PR's removal of receipt-owner filtering. Removed the retired locallyOwnedReceiptIds field from main's new maintenance fixture. All 6 affected history/maintenance/RPC/audit-link files passed all 40 tests in 154.09 s (Gateway 21 tests/116.05 s; cron 19/27.88 s). Core types, cron test types, targeted lint, and Madge passed again. No UI or unrelated owner edits were introduced.
  • Audit-restoration static checks passed: core types, cron test types, targeted lint, formatting, database worker/dialect ratchets, and Madge (0 runtime value cycle(s)). Independent Codex review found no actionable P0/P1 issues. No schema definition, UI, dependency, config option, or CLI option changed.
  • Copied released database: [email protected] → candidate worker recovery passed in 26.43 s. Recorded history was restored once, uncertain runs were interrupted, and a lost queued payload was skipped. Cron/task table definitions stayed unchanged through the existing shared-state 20→21 migration. Backup rollback plus the released SDK reader passed in 2.90 s; original rows and schema hash matched exactly. This covers copied-database recovery/rollback, not a full installed-updater campaign.
  • Owner and sibling proof covered heartbeat/setup/execution deadlines, cleanup, skipped history, real webhook/notification outcomes, exact run lookup, and RPC/CLI/tool contracts. The frozen cron run passed 868/875 tests across 102 files. Two stale event expectations were corrected; their two files then passed all 21 tests. The remaining five failures are inherited (below). Gateway service/close passed 96 tests in 128.95 s; drain passed 14 in 135.36 s. Earlier Gateway coverage passed 458 tests across 28 files in 880.22 s. Existing fixture startup accounts for substantial wall time; no timeout or retry was raised.
  • All five previously unrun files passed: 40 tests in 84.99 s wall. Test bodies: admitted-run authority 0.156 s, delivery outcomes 9.630 s, execution diagnostics 18.019 s, state contracts 4.052 s, Gateway startup recovery 11.846 s. Runtime build took 6.9 s and worker preparation 3.95 s. Doctor cron-owner coverage passed all 18 tests in 75.33 s wall after the fixture was corrected to stop/join cron before offline repair.
  • After rebasing onto 4d440abc91932aacd17a193a1467ba005405fcd3 and installing its frozen dependencies, the six conflict-affected suites passed all 83 tests in 55.53 s wall (16.31 s compiler preparation). No test exceeded 30 s. Post-rebase pnpm tsgo:core and targeted lint for all six affected files passed (exit 0). The upstream fs-safe pin required refreshing this worktree's private installation; this PR changes no dependency file.
  • Pre-rebase check:changed passed its preceding guards, production types, all 28 dependent core-test graphs, root test types, formatting, coercion, and deprecated-API checks. It stopped at eight inherited Knip exports: two in unchanged src/config/sessions/session-accessor.transcript.ts and six in unchanged UI files. Running the downstream plan separately passed 10/11 steps; full-core lint reported 14 errors in unchanged files (13 line limits and one UI promise handler), none in changed files. No unrelated owner, baseline, ignore, or suppression was edited. Madge: zero import cycles. git diff --check passed. Independent Codex review completed; index-only conflict-resolution findings were corrected by staging the restored, tested files. No actionable findings remain.

The identical 126-path selection on pristine base 1589da87911da73ab5cba9f21658f67166fb8b2b reproduced the same five trigger-script.plugin-reload failures. Both runs reached the same 116 files before stopping; base passed 1,068 tests across 115 files, with only that plugin-reload file failing. Its cron group passed 911/916 tests in 457.82 s; the complete base command took 675.94 s. An optional JSON-reporter attempt stopped before cron on unsupported Gateway project configuration and is excluded from product evidence; the normal-reporter rerun kept the exact selection.

Inherited leak → L1562: the candidate diagnostic reports ERR_WORKER_OUT_OF_MEMORY before any tool effect. Base assertions omit the underlying error but reproduce the same five rapid, pre-effect failures. The admission publisher, Code Mode worker, and non-isolated runner are byte-identical between base and candidate. Real closed SQLite databases retain records published through setEnvironmentData: 300 closed databases produce 41,470,200 JSON bytes and exhaust the actual worker's 60 MiB old + 4 MiB young heap before readiness. Retiring those owned records restores startup at 21.4 MB heap. The isolated reproducer uses task-created databases; no heap increase or admission bypass was applied. The campaign lead assigned the generic admission fix to L1562.

Physical line accounting separates test fixtures/harnesses from production. This PR: production +904 / -2,980 = -2,076 net (3,884 changed production lines); tests/support +1,425 / -5,886 = -4,461 net. The audit-coverage correction adds 140 net production lines and 63 net test/support lines.

Cut Production net Tests/support net
PR 1, #168619 -550 -860
PR 2a, #168772 -1,291 -1,635
PR 2b-i, #169364 -1,727 -1,782
PR 2b-ii, #169766 +102 +837
PR 3, this PR -2,076 -4,461
Cumulative -5,542 -7,901

Retired result/recovery-path checks both return no matches:

git grep -n -E 'observeRunRecovery|settleRunReceipt|nonceSettlement|CronFinalizationReceipt|foreign-receipt-monitor|run-receipt-execution-binding' -- src test
git grep -n -E 'commitGuard|revocation|nonce' -- 'src/cron/*run-recovery*' src/cron/service/startup-run-repair.ts src/cron/store/run-finalization.worker.ts src/cron/store/run-result.ts src/cron/service/timer-outcome-finalization.ts src/cron/service/timer-outcomes.ts

Cron terminal-result and restart-recovery owners have no commitGuard, revocation-generation, or nonce-settlement path. A whole-cron grep still finds the intentionally retained live caller/device, task, session, heartbeat, self-removal, and tool-permission guards; these are effect/permission checks, not terminal accounting. The restored audit link is diagnostic metadata only.

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

@steipete
steipete marked this pull request as ready for review October 12, 2026 14:18
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime commands Command implementations agents Agent runtime and tooling size: XL labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR consolidates cron results and restart recovery in the worker while preserving opt-in execution identity audit links.

Example: A one-shot scheduled for 12:00 becomes active, then the Gateway crashes before recording its result.

  • Before: Recovery could replay the payload when delivery was recorded as not started.
  • After: Recovery records an interruption with delivery Unknown and disables the uncertain one-shot.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The consolidation is coherent and supported by inspected boundary coverage; upgrade acceptance and failed-check attribution remain incomplete.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; copied released-database recovery supports compatibility, but the body explicitly excludes the installed-updater acceptance required by the staged design.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: Operators need durable execution and delivery outcomes across restart without replaying uncertain external effects.
Reason: The maintainer-directed design accepts the crash-loss tradeoff, and the patch removes competing machinery without adding public configuration or changing permission ownership.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep open: this maintainer-directed PR completes a useful worker ownership cutover, and no definite introduced correctness defect was found.

Priority: P2
Reviewed head: ca1b2fe6e8ff35290ffb5e4267f67f5005459b97

Before merge

  • Complete next step - Inspect the failed changed-lint and docs-formatting diagnostics, classify their cause, and repair only failures introduced by this PR.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: The required published-updater-to-candidate run with preserved settings/data, restart, and backup rollback remains unproven.
Agent review details

How this fits together

Cron receives scheduled, manual, and event requests; the Gateway executes committed requests, and the worker records job state, history, and terminal receipts before publishing results.

flowchart LR
  A[Run requests] --> B[Cron worker]
  B --> C[Gateway launcher]
  C --> D[Run executor]
  D --> B
  B --> E[SQLite state and history]
  B --> F[Views and notifications]
Loading

Technical review

Best possible solution:

Complete the single worker owner for results and recovery while preserving permission checks and the accepted no-replay policy.

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

This is an ownership refactor; current-main source retains the paths being replaced, and inspected tests cover terminal idempotency, restart recovery, and public run lookup without being executed during this review.

Is this the best way to solve the issue?

The implementation follows the approved staged design by removing competing accounting paths and retaining live permissions with their existing owners.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4ba65fccf9bc.

Provenance checked

  • Worker finalization and receipt settlement changes intended behavior with a stated reason (52618fc: Move finalization off the Gateway thread while preserving atomic receipt/job updates and settlement ownership.)
  • Interrupted one-shot replay changes intended behavior with a stated reason (187594c: Prevent duplicate delivery after ambiguous acceptance while allowing proven not-started delivery to recover; the new accepted policy also avoids uncertain payload replay.)
  • Exact lifecycle audit bindings keeps the original intent (2e9c8f8: Associate admitted execution identities with native lifecycle receipts without treating operational correlation as authorization.)
  • Acknowledged cadence edits during recovery keeps the original intent (bd9ed86: Prevent completed-run recovery from overwriting newer acknowledged scheduling edits.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b943945 adds src/cron/store/run-finalization.worker.ts:22 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b94394543d88; files: src/cron/store/run-finalization.worker.ts)
  • Shakker: Raw commit bd9ed86 adds src/cron/service/startup-run-repair.ts:156 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: bd9ed86c268c; files: src/cron/service/startup-run-repair.ts)
  • Josh Avant: Raw commit 2e9c8f8 adds src/audit/execution-owner-lifecycle-binding-store.ts:117 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2e9c8f8d3f21; files: src/audit/execution-owner-lifecycle-binding-store.ts)

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
Production versus tests and support Production +904/-2,980; tests/support +1,425/-5,886 Verified from the introduced diff; the reduction removes superseded coordination while retaining worker and Gateway boundary coverage.

Labels

Label changes:

  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: This is a normal-priority cron reliability and ownership improvement without an established urgent introduced regression.
  • merge-risk: 🚨 compatibility: Interrupted one-shots deliberately stop conditional replay and remain disabled with Unknown delivery; this tradeoff is explicitly accepted.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • 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 (1 earlier review cycle)
  • reviewed 2026-10-12T14:26:57.158Z sha a686993 :: blocked before merge. :: none

Reviewed October 12, 2026, 10:57 AM ET / 14:57 UTC (Revision 2).

Record execution, primary delivery, job state, and history in the worker.
Restore recorded terminal outcomes on restart and interrupt uncertain runs
without replaying payloads or delivery. Remove receipt settlement, foreign
monitoring, execution binding, and obsolete recovery protocols.

Preserve permission provenance and live effect checks. Post-run notifications
remain asynchronous and cannot undo committed terminal accounting.

Refs #168072
@clawsweeper clawsweeper Bot added the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Oct 12, 2026
@steipete
steipete merged commit 64400ff into main Oct 12, 2026
24 checks passed
@steipete
steipete deleted the upd/upd-l1561 branch October 12, 2026 15:03
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…er (openclaw#169946)

Final PR of the cron worker-owned redesign (docs/refactor/cron-worker-owned.md): one worker-owned terminal handler records execution and primary-delivery outcome, updates job and history, and emits post-run notifications without commit guards; restart recovery restores recorded results once and marks uncertain runs interrupted without replaying payloads or delivery. Nonce settlement, receipt binding/observation plumbing, foreign-receipt monitoring and host recovery orchestration are deleted. Opt-in audit execution bindings for scheduled runs are preserved through the existing store. Production -2,076 LOC (program total -5,542). Refs openclaw#168072.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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