Skip to content

perf(workers): reduce task scheduling overhead - #165230

Merged
steipete merged 4 commits into
mainfrom
codex/worker-overhead
Oct 5, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/worker-overhead

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Worker task scheduling performs avoidable async-context allocation, repeats shared native-source servicing, and sends redundant reference-control messages.

User Impact

There is no user-visible API or lifecycle change. Tasks retain their submitting context through execution and owned cleanup; released tasks can let that context be collected while their handles remain usable. Native failure checks, synchronous progress, resource custody, and shutdown settlement remain intact.

Why This Change Was Made

Apply the focused task-context approach used by Piscina and Tinypool to our internal worker runtime. A separately scoped AsyncResource runner reduces capture allocations without retaining callers through unrelated enqueue callbacks. Each synchronous pool or rotation pass captures its workers before callbacks and lets the host service their shared native source once; nested calls create a fresh pass. Native ref() and unref() send messages only on reference transitions while retaining availability checks and liveness refreshes.

The existing context capture already allowed released callers to be collected. This change reduces scheduling work while preserving that behavior. The internal host owns source grouping, and individual stop/resource operations retain their own synchronous servicing.

Evidence

  • Independent Codex P0–P2 review found no actionable findings in the final source.
  • Focused pnpm test … --maxWorkers=1 runs: the combined candidate passed 87 tests across six files in 332.10 seconds wrapper wall time. After extracting the shared service-pass helper, all 38 affected tests across four files passed again in 190.04 seconds. The context-retention GC fixture took 395 ms; the new reference-transition assertion took 1 ms and failed the original implementation as intended. Per-file CI seconds were unavailable in the inspected run artifacts.
  • Thirteen actual-source live checks passed after the final extraction on Node 24.21.0: SQLite read/refresh/failure recovery, snapshot custody, binary transfers, abort/close receipts, nested two-worker servicing without Promise reactions, caller context, rotation, and cleanup. A 96-task queue across two real workers emitted exactly four reference-control packets. All workers exited and task-owned state was removed.
  • The private package runtime/declaration build passed in 117.96 seconds. The executable PR-wrapper inventory check passed in 20.03 seconds.
  • Full changed-file validation passed, including production/test types, lint, formatting, dead exports, architecture guards, wrapper inventory, and zero runtime import cycles. Mechanical main integration preserved all reviewed implementation/test/README bytes and the two inventory additions.
Context optimization measurements and earlier controls

Actual-core retention controls passed on Node 24 and Bun 1.4.2. Earlier actual-source transport checks passed on Node 26.10.0. The unsafe alternative that captured its resource inside enqueue failed the intended GC assertion; the isolated helper and original baseline both collected released callers correctly.

Isolated Node 26 measurements reduced context capture plus four invocations from about 770 ns to 127 ns, and retained memory per capture from about 513 to 152 bytes. Longer native-worker runs used less main-thread CPU in 13 of 14 paired windows, but shared-host wall-time variation was substantial. These are allocation/CPU and synthetic-worker results, not a stable Gateway-throughput percentage.

Historical CI qualification for the original context-only head

CI run 37249796216, attempt 1 completed with one independently attributed inherited failure: checks-ui-e2e (4/7), plus the downstream CI gate. The offline mocked-Gateway rail test expected transcript scroll position 0 after a wheel gesture and observed 8925. Its UI, test, and workflow sources exactly match the tested main parent; the in-browser mock was deliberately disconnected before the interaction, so this path never reaches the changed Node worker pool. The exact UI failure mechanism remains unresolved, and no rerun or speculative fix was made. All other selected owners, including security-fast and real-Gateway UI, succeeded.

This is historical evidence for the original context-only head, not a current-head CI exception. The combined head uses the normal fresh-CI landing path.

Capture per-task caller state with a separately scoped AsyncResource
runner instead of a variadic snapshot binding. Preserve automatic
resource destruction and caller context through retained cleanup.

Keep the resource closure independent of other task callbacks so a
retained completed task handle does not retain its released caller.
Extend the existing native retention proof and include the helper in
the PR wrapper's runtime import closure.
@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: S labels Oct 5, 2026
@steipete
steipete marked this pull request as ready for review October 5, 2026 01:02
@clawsweeper

clawsweeper Bot commented Oct 5, 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 P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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 Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 5, 2026, 12:48 AM ET / 04:48 UTC (Revision 5).

ClawSweeper review

What this changes

The PR reduces worker scheduling overhead by capturing task context more cheaply, servicing shared native workers once per pass, and sending reference-control messages only when reference state changes.

Merge readiness

✅ Ready for maintainer review

This PR remains useful: current main still performs the scheduling work it removes. No actionable introduced defect or unresolved prior finding was found.

Priority: P3
Reviewed head: f0f3a6b437d510a8ee2fa4822588c6a5031828fc

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with relevant production-path observations and lifecycle coverage supports a normal good-quality rating.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded actual-source Node 24.21.0 checks exercise the changed scheduler and native transport through nested servicing, context retention, reference transitions, cancellation, rotation, and cleanup, with observed successful settlement and reduced packets. No stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded actual-source Node 24.21.0 checks exercise the changed scheduler and native transport through nested servicing, context retention, reference transitions, cancellation, rotation, and cleanup, with observed successful settlement and reduced packets. No stored-data contract changes require migration proof.
Evidence reviewed 8 items Pinned introduction boundary: Read the complete introduced delta from the pinned base to the exact original PR head. The merged bootstrap-recovery work is already in the base and is not attributed to this PR.
Current main still needs the optimization: Fetched main still captures each task with AsyncLocalStorage.snapshot(), services native workers individually, and posts reference-control messages on repeated calls. The changed worker surfaces have no base-to-fetched-main delta. The latest release tree does not contain the private worker-runtime package or native-handle path.
Shared servicing owner: The host captures one native source for its pool. NativeWorker.service() delegates to that source's runtime, whose service loop drains control messages and visits every captured handle's task port and resources. Nested invocations obtain fresh captures; individual stop and resource settlement paths remain intact.
Findings None None.
Security None None.

How this fits together

OpenClaw's worker runtime accepts queued computation and retained tasks, then manages execution, replies, cancellation, and cleanup. Its host adapter connects that scheduler to native worker lifetimes and resource owners.

flowchart TD
  A[Task submissions] --> B[Capture caller context]
  B --> C[Bounded worker scheduler]
  C --> D[Native worker host]
  D --> E[Shared source servicing]
  E --> F[Replies and cleanup receipts]
  F --> C
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +37, Tests +95, Docs +7, Other +2. Total +141 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 7 52 15 +37
Tests 3 98 3 +95
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 12 159 18 +141

Review metrics

None.

Technical review

Best possible solution:

Keep one scheduler and native lifetime owner while reducing allocation and redundant servicing without changing task custody or public SDK behavior.

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

Not applicable as a bug reproduction: current-main source shows the avoidable scheduling operations, and the PR records comparative allocation and actual-worker observations.

Is this the best way to solve the issue?

Yes. The optimization stays within the existing scheduler and host owners, preserves public entrypoints, and retains availability and cleanup checks.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This is an internal scheduling performance improvement with no requested user-facing API or lifecycle change.
  • 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 (live_output): Recorded actual-source Node 24.21.0 checks exercise the changed scheduler and native transport through nested servicing, context retention, reference transitions, cancellation, rotation, and cleanup, with observed successful settlement and reduced packets. No stored-data contract changes require migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded actual-source Node 24.21.0 checks exercise the changed scheduler and native transport through nested servicing, context retention, reference transitions, cancellation, rotation, and cleanup, with observed successful settlement and reduced packets. No stored-data contract changes require migration proof.

Evidence

What I checked:

  • Pinned introduction boundary: Read the complete introduced delta from the pinned base to the exact original PR head. The merged bootstrap-recovery work is already in the base and is not attributed to this PR. (f0f3a6b437d5)
  • Current main still needs the optimization: Fetched main still captures each task with AsyncLocalStorage.snapshot(), services native workers individually, and posts reference-control messages on repeated calls. The changed worker surfaces have no base-to-fetched-main delta. The latest release tree does not contain the private worker-runtime package or native-handle path. (packages/worker-runtime/src/worker-task-pool-core.ts:222, fa468f6a64c4)
  • Shared servicing owner: The host captures one native source for its pool. NativeWorker.service() delegates to that source's runtime, whose service loop drains control messages and visits every captured handle's task port and resources. Nested invocations obtain fresh captures; individual stop and resource settlement paths remain intact. (src/infra/worker-native-lifecycle.ts:204, f0f3a6b437d5)
  • Context and reference invariants: The isolated AsyncResource closure captures caller context; owned release replaces its runner after cleanup. Reference transitions retain transport failure checks and native liveness refreshes. Added coverage exercises pending sample liveness, repeated failed admission, and collection of released caller context while the task handle remains usable. (src/infra/worker-native-task-port.test.ts:179, f0f3a6b437d5)
  • Recorded production behavior proof: The captured PR body reports thirteen actual-source checks on Node 24.21.0 after the final helper extraction, covering nested two-worker synchronous servicing, caller context, rotation, abort/close receipts, resource custody, failure recovery, and cleanup. A 96-task queue across two real workers produced four reference-control packets, and all workers exited. These observations match the changed production owners; no reviewer-side runtime execution was performed. (f0f3a6b437d5)
  • Review continuity and validation: The previous completed review covered this exact head and retained no findings or published rank-up moves. The supplied current-head context reports successful CI, dependency, and sensitive-change gates. Read-only diff checking passed, and the checkout remained clean. (f0f3a6b437d5)

Likely related people:

  • steipete: 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 (4 earlier review cycles)
  • reviewed 2026-10-05T01:07:52.266Z sha 250529b :: needs maintainer review before merge. :: none
  • reviewed 2026-10-05T01:14:03.740Z sha 250529b :: needs maintainer review before merge. :: none
  • reviewed 2026-10-05T01:55:21.348Z sha 250529b :: needs maintainer review before merge. :: none
  • reviewed 2026-10-05T04:38:05.401Z sha f0f3a6b :: needs maintainer review before merge. :: none

Require task-server readiness on internal retained transports. Freeze new worker construction after a genuine bootstrap failure, preserve healthy sibling capacity and checkpoint fairness, and retry only after successful rotation or a new pool generation.

Keep arbitrary SDK workers, ordinary task failures, input preparation, and native cleanup ownership on their existing paths. Proved the 12-task failure cohort drops from 12 starts to one, including actual retained-source worker execution and explicit recovery.
@steipete steipete changed the title improve: reduce worker task context allocation overhead improve: reduce worker task scheduling overhead Oct 5, 2026
@steipete steipete changed the title improve: reduce worker task scheduling overhead perf(workers): reduce task scheduling overhead Oct 5, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Oct 5, 2026
@steipete

steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete merged commit b7b7872 into main Oct 5, 2026
151 of 152 checks passed
@steipete
steipete deleted the codex/worker-overhead branch October 5, 2026 05:01
@steipete

steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 6, 2026
* perf(worker-runtime): reduce task context capture allocations

Capture per-task caller state with a separately scoped AsyncResource
runner instead of a variadic snapshot binding. Preserve automatic
resource destruction and caller context through retained cleanup.

Keep the resource closure independent of other task callbacks so a
retained completed task handle does not retain its released caller.
Extend the existing native retention proof and include the helper in
the PR wrapper's runtime import closure.

* fix(workers): stop repeated starts after initialization failure

Require task-server readiness on internal retained transports. Freeze new worker construction after a genuine bootstrap failure, preserve healthy sibling capacity and checkpoint fairness, and retry only after successful rotation or a new pool generation.

Keep arbitrary SDK workers, ordinary task failures, input preparation, and native cleanup ownership on their existing paths. Proved the 12-task failure cohort drops from 12 starts to one, including actual retained-source worker execution and explicit recovery.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts 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.

1 participant