Skip to content

fix(workers): cancel queued host callbacks at task deadlines - #167740

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-worker-host-callback-deadlines-20260919
Oct 9, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-worker-host-callback-deadlines-20260919

Conversation

@steipete

@steipete steipete commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes expired worker tasks leaving host callbacks queued for SQLite, history, usage, cold-restoration, and worktree operations. The pool deadline repair in #167446 bounds the worker task; several downstream handlers still dropped its abort signal before reaching their queue owners.

User Impact

Expired callbacks cancel waiting work and emit WORKER_HOST_CALLBACK_TIMEOUT with a bounded callback name. Accepted native writes and required cleanup keep their settlement ownership. Independent callers sharing an actor opening remain usable when its first caller cancels.

No configuration, schema, dependency, or operator migration changes.

Why This Change Was Made

Carry the existing task signal through the remaining callback interfaces. Reuse the cancellable FIFO for cold restoration and broker opening, removing the uncancellable queue paths. Cancellation stops observations of shared retirement/preparation; their resource owners continue settling. Transient callback signals no longer become retained history authority, and abandoned successful opens still retire when idle.

The audit covers ten callback families. Existing transcript-index and report-generation network/store callbacks already forward signals. Synchronous hydration/catalog callbacks do not queue work; Code Mode retains its explicit approval-aware deadline owner. Prepared-runtime waits added on main follow the same cancellation/settlement boundary. Close receipts now publish in the validated reply owner before caller completion, removing the broker's forwarding adapter.

Production TypeScript delta is +317 lines. The requested non-test/non-doc path filter reports +320 (+4 README lines, −1 obsolete mock-baseline entry). Growth carries the existing cancellation contract through previously signal-free interfaces; there is no second scheduler or timeout manager.

Evidence

Validated staged source on base 3b3cd5939993f16017b6747cbcf80a83b49006ef, with source hashes checked before execution. Heavy checks ran on AWS Crabbox cbx_635d3f27917d and the authorized isolated Linux rig; none ran on the development Mac.

Check Result
node scripts/check-changed.mjs --staged Passed, including production types, all 27 test-type graphs, lint, and storage/import guards
Focused deadline, cancellation, and lifetime cases 26 passed; unresolved callbacks abort at their 950–1,000 ms virtual task deadlines and a successor completes
Relevant owner and sibling suites 957 passed across 79 files; one existing macOS/SetFile birthtime case skipped on Linux
Export collision guard and eager-import/PR-wrapper closure suites Passed; 20 closure checks
pnpm build Passed in 322 s
Independent review Scoped clean through P2; four passes, no accepted/actionable findings

Before-fix controls reproduce queued operations remaining pending after cancellation until the 30-second test guard, canceled work being admitted, and one opener's cancellation poisoning independent callers. Three prepared-runtime cases also fail on the current main implementation. The corrected cases reject before the held writer or retiring worker is released. Separate controls verify that ordinary and persistent storage failures still propagate. This measures cancellation behavior, not production CPU or throughput.

Focused wrapper wall times (node scripts/run-vitest.mjs <files> --maxWorkers=1): the corrected lease file passed 14 cases in 43.02 s including worker-fixture compilation; the history/ACP/compute group passed 5 cases in 150.67 s including 92.9 s compilation. Real history/ACP test bodies cost 3.2–4.8 s, and compute cancellation 1.7 s; prepared-runtime cancellation bodies cost 2–3 ms. These use existing fixtures and deferred barriers, with no new timer sleeps or test files. Final-head CI is recorded below.

AWS and the isolated rig were used after Blacksmith admission did not complete. Superseded and interrupted attempts are not counted as passing evidence.

Known follow-up: process-held history omits prepared subagent visibility facts from its worker protocol. A synthetic forwarded-child assertion fails identically on unchanged base 687e6e9d1a8a1c698f0a713c58f7e7dd6d6312a9. This change preserves existing display behavior and the original page/delta/SSE assertions. Live production was not modified or benchmarked. Custom host code must honor its signal; the pool cannot forcibly stop arbitrary host JavaScript.

CI follow-through

The first PR run exposed two stale Gateway test fixtures. Cold restoration now uses the cancellable writer queue, so its revocation fixture now pauses the actual queued metadata read instead of spying on the retired queue. The ended-transcript fixture preserves its exact request, recipient, and output-size checks while allowing the optional signal argument.

AWS Crabbox cbx_957137c80b84, run run_aeb5b438f18389c7f65a774d471b5168, verified the follow-up source hashes and passed:

  • Both repaired files: 23 tests, 134 seconds through node scripts/run-vitest.mjs ... --maxWorkers=1.
  • node scripts/check-changed.mjs --staged: passed in 280 seconds, zero lint warnings/errors, both affected Gateway test-type graphs passed.
  • Cold-storage preflight and admission siblings: 11 tests passed.
  • Fresh isolated review: no actionable P0–P2 findings.

Combined with unchanged-source proof above, 980 distinct tests across 81 files passed, plus the 20 closure checks. The follow-up changes tests only.

On unchanged CI main parent 21ecc39d75d46362b2717487c7dc49a90c7ddd21, both Doctor files reproduced the same resolved-instead-of-rejected failures, and the CLI-update type graph reproduced update-cli.windows-lifecycle.test.ts:508 TS2554. The Doctor fixtures still expect rejection after main changed failed-readiness/running-service handling to warn and return. The Windows fixture calls a typed signal listener without its signal argument. These baseline failures are excluded from passing test counts. The final-head Windows type, legacy-updater, and assertion-ratchet jobs pass after independent main fixes.

Final-head CI run 37913423324 tested 4c1e1059b9c85c910212e40973d0ded3784bf28c through merge dea79148c26992a08869a6e1ee5e5325cbae592f onto main 3223e13a514c6134e10ee7f585627434d245fd20: 87 jobs succeeded, 23 were skipped, and the sole failing test job is the inherited managed-Doctor restart-unhealthy assertion. The aggregate fails only for that job. All five relevant production/fixture files are byte-identical between the directly tested main baseline, CI main parent, and PR merge. Landing uses the inherited-failure exception; no CI rerun or unrelated repair is included.

Propagate task cancellation through history, usage, cold restoration,
shared-state admission, and worktree effects. Name timed-out callbacks
while keeping accepted native work under its settlement owner.

Preserve independent coalesced openers and completed history authority.
Record close receipts in the reply owner before caller settlement.
@clawsweeper

clawsweeper Bot commented Oct 9, 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 agents Agent runtime and tooling size: XL labels Oct 9, 2026
@steipete
steipete marked this pull request as ready for review October 9, 2026 09:11
@steipete
steipete enabled auto-merge (squash) October 9, 2026 09:14
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The PR carries worker-task cancellation into queued database, history, usage, and worktree operations so expired requests stop waiting while accepted work finishes safely.

Example: A database opening expires while another opening holds the worker reply.

  • Before: The canceled opening remains queued and can create its database after the held reply arrives.
  • After: The canceled opening rejects with “queued open deadline expired,” its database remains absent, and a successor successfully writes “survived canceled open.”

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is coherent and supported by real worker-boundary fault evidence, with confidence limited to harness-based execution rather than a shipped CLI or Gateway demonstration.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (live_output): Recorded isolated Linux runs exercise the production broker and real Worker transport with held replies and writers: canceled waiting operations reject before release, canceled databases remain absent, accepted work settles, and successors progress. The follow-up changes fixtures only and records passing affected runs; the inspected storage screenshots are unrelated.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Expired history and usage requests can leave database work queued and consume resources after the caller has stopped waiting.
Reason: The repair completes an established deadline contract across existing owners. Prior merged area history supports the direction, and the optional plugin parameter is a narrow compatible repair.

Merge readiness

✅ Ready for maintainer review

This PR retains useful work beyond the merged deadline repair and the overlapping SQLite proposal. No concrete introduced defect was found; the latest fixture corrections preserve the existing safety assertions.

Priority: P1
Reviewed head: 4c1e1059b9c85c910212e40973d0ded3784bf28c

Before merge

None.

Findings

None.

Agent review details

How this fits together

OpenClaw workers request database and filesystem operations through callbacks in the main process. The worker scheduler supplies cancellation signals, while operation queues and resource owners control admission, settlement, and cleanup.

flowchart TD
  A[History or usage request] --> B[Worker task and deadline]
  B --> C[Host callback with cancellation signal]
  C --> D{Operation admitted?}
  D -->|Waiting and canceled| E[Remove queued operation]
  D -->|Already accepted| F[Resource owner settles work]
  E --> G[Request completes and successor progresses]
  F --> G
Loading

Technical review

Best possible solution:

Keep cancellation with the existing queue owners and preserve native settlement and cleanup after admission.

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

Yes: current main’s opening and cold-restoration queues omit cancellation, and the held-reply and held-writer regressions exercise those paths. The PR records failing baseline controls and passing candidate results; this read-only review did not rerun them.

Is this the best way to solve the issue?

Yes: forwarding the existing task signal into established admission owners repairs dropped cancellation while preserving FIFO ordering, live authority, and accepted-operation settlement.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 3223e13a514c.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Current main still has downstream cancellation gaps: Fetched main retains the signal-free opening promise chain and KeyedAsyncQueue-based cold restoration. The central owners have no intervening changes since the pinned merge base. (src/infra/sqlite-worker-input-admission.ts:40, 3223e13a514c)
  • Cancellation reuses the existing FIFO owner: Opening admission now forwards its signal to the existing writer queue, whose cancellation removes waiting tasks and detaches on admission so accepted work remains joined. (src/infra/sqlite-worker-input-admission.ts:52, 4c1e1059b9c8)
  • Real worker transport fault coverage: The regression holds an actual Worker reply, cancels a queued opening, verifies that its database was never created, preserves accepted opening settlement, and confirms a successful successor write. (src/infra/sqlite-worker-broker.test.ts:43, 4c1e1059b9c8)
  • Recorded source-bound validation: The supplied complete body, captured under sourceRevision 7f62d845516c538e88b37e1ec17044daabc00ae68b8575ca7d2f8effd21d8512, records failing original-code controls, passing cancellation and recovery scenarios on isolated Linux environments, 980 distinct passing tests, closure checks, changed-source checks, and a successful build. These are contributor-recorded results; this review executed no tests. (4c1e1059b9c8)
  • Latest commit changes fixtures only: The follow-up pauses the actual queued cold-metadata read and allows the optional signal argument while retaining request, recipient, output-size, revocation, and replacement-database assertions. (src/gateway/session-history-worker-lifecycle.test.ts:108, 4c1e1059b9c8)
  • Established deadline and settlement intent: The merged predecessor fix(history): keep committed reads responsive during writer stalls #167446 establishes caller-bounded host exchanges, approval-aware Code Mode waits, and accepted-write settlement. This PR carries that contract into downstream owners. (packages/worker-runtime/src/worker-task-pool-core.ts:544, 486cdae054fe)

Likely related people:

  • Peter Steinberger: Raw commit 486cdae adds packages/worker-runtime/src/worker-task-pool-core.ts:547 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 486cdae054fe; files: packages/worker-runtime/src/worker-task-pool-core.ts)

PR surface

Source +317, Tests +680, Docs +9, Other -1. Total +1005 across 70 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 49 751 434 +317
Tests 18 804 124 +680
Docs 2 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 70 1564 559 +1005

Review metrics

Metric Value Why it matters
Production versus test growth Production TypeScript +317 lines net; tests and test support +680 lines net Production growth carries the existing cancellation contract through its consumers and reuses the established FIFO instead of adding a scheduler.
Plugin API addition 1 optional signal parameter in keyed-store deletion options The repair exposes queued cancellation while preserving existing callers.

Labels

Label changes:

  • add P1: Expired requests can leave database and history operations waiting behind stalled owners, prolonging broken agent workflows.
  • add merge-risk: 🚨 compatibility: The plugin keyed-store API gains cancellation behavior through a narrow, source-compatible repair that preserves existing calls and accepted-write settlement.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P1: Expired requests can leave database and history operations waiting behind stalled owners, prolonging broken agent workflows.
  • merge-risk: 🚨 compatibility: The plugin keyed-store API gains cancellation behavior through a narrow, source-compatible repair that preserves existing calls and accepted-write settlement.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-09T09:19:54.937Z sha 4da8daf :: needs maintainer review before merge. :: none

Reviewed October 9, 2026, 5:53 AM ET / 09:53 UTC (Revision 2).

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 9, 2026
@steipete

steipete commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Final-head CI has one inherited test failure: doctor-health.managed-settlement.test.ts, restart-unhealthy, in job 113764553608. Main now warns and returns when the service runs but readiness remains unverified; the unchanged fixture still expects rejection.

The same assertion failed on unchanged main 21ecc39d75d46362b2717487c7dc49a90c7ddd21 on AWS Crabbox cbx_957137c80b84. The flow, maintenance owner, test and supporting fixtures are byte-identical in that baseline, the CI main parent 3223e13a514c6134e10ee7f585627434d245fd20, and tested merge dea79148c26992a08869a6e1ee5e5325cbae592f.

All task-caused CI failures are repaired and independently reviewed. The two corrected Gateway files pass all 23 tests; the final staged gate and 11 cold-storage siblings pass. Final-head CI reports 87 successful jobs and 23 skipped jobs, with only this test job and its aggregate red. Landing under the inherited-failure exception without rerunning CI.

@steipete
steipete merged commit 7dd2721 into main Oct 9, 2026
176 of 179 checks passed
@steipete
steipete deleted the steipete/perf-micro-worker-host-callback-deadlines-20260919 branch October 9, 2026 10:04
steipete added a commit that referenced this pull request Oct 9, 2026
The cancellation-wait helper captured opening options in the same V8
context as cached SQLite client callbacks. Reusing a handle could keep
completed callers and their admission authority alive for its lifetime.

Move the wait outside that scope and reuse one actor binding. Preserve
abort-reason identity, admission checks, and native settlement while the
existing forced-GC regression still requires zero retained caller objects
and reuse of the same store and actor.

Follow-up to #167740.
RomneyDa pushed a commit that referenced this pull request Oct 9, 2026
Backport the worker-runtime and SQLite/shared-state cancellation portion of
#167740 onto the release owners. Keep queued cancellation separate from accepted
native settlement, preserve FIFO and independent coalesced callers, and retain
cleanup custody. Carry cancellation through plugin-state and agent writes.

Adapt the necessary deadline ownership contract from #167446 without importing
its history refactor. Code Mode keeps its existing approval-aware host budget.
Use structured operation labels for diagnostics; raw callback strings retain
the worker-entrypoint fallback and never become log payloads.

This is a selected backport, not full #167740 coverage: its newer ACP/worktree,
history/usage and cold-restoration portions are deliberately not imported.

Proof: 200 distinct tests across 10 files; original host-wait suspension fails
all five deadline cases; donor raw-string labeling fails the payload case.
Physical frozen install, worker-runtime build, core types, all 27 core test
graphs, three zero-entry Knip scans, changed-source guards and scoped lint pass.
Post-review diagnostic repair has fresh affected build/type/lint/test proof.

Deadline ownership portion adapted from 486cdae.
(cherry picked from commit 7dd2721)
(cherry picked from commit b7984f6845f075a5f92825926632575bbcc0202c)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
…w#167740)

Propagate worker-task cancellation through queued host database, history, usage, cold-restoration, and worktree operations. Emit callback-specific timeout diagnostics while preserving accepted native effects and cleanup under their existing owners. Keep independent coalesced callers usable and retire abandoned successful opens.

Repair the history revocation and ended-transcript fixtures to observe the active callback boundary without coupling to optional argument arity.

Validation: 980 distinct tests across 81 files plus 20 closure checks, changed-source gates, export guard, and build passed on isolated remote validation. Full production and final fixture corrections passed independent review. Final-head CI had one independently reproduced inherited managed-Doctor readiness assertion; landed under the inherited-failure exception.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
The cancellation-wait helper captured opening options in the same V8
context as cached SQLite client callbacks. Reusing a handle could keep
completed callers and their admission authority alive for its lifetime.

Move the wait outside that scope and reuse one actor binding. Preserve
abort-reason identity, admission checks, and native settlement while the
existing forced-GC regression still requires zero retained caller objects
and reuse of the same store and actor.

Follow-up to openclaw#167740.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL 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.

1 participant