Skip to content

perf: reduce CodeMode latency and session lookup work - #134935

Merged
steipete merged 2 commits into
mainfrom
codex/perf-session-workers-20260901
Sep 1, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/perf-session-workers-20260901

Conversation

@steipete

@steipete steipete commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Repeated CodeMode executions pay for fresh Node workers and TypeScript initialization on every execution/resume, while ordinary single-session Gateway reads decode unrelated session rows. Those costs consume CPU and delay concurrent work on large machines.

This is a maintainer-requested performance refactor. It replaces duplicated worker lifecycle code with one bounded execution owner and removes unnecessary work from single-session reads.

Why This Change Was Made

CodeMode and compaction reuse lazily created workers; TypeScript preparation runs in the worker, snapshots transfer ownership, and every CodeMode execution/resume still creates or restores an isolated QuickJS VM. Queueing and preparation consume the original deadline, and cancellation waits for actual worker termination before releasing capacity. Catalog workers stay bound to their immutable generation; auth warming remains disposable. Host tools, approvals and session orchestration retain their existing authority owners.

Single-session lookups use the existing exact SQLite row accessor, preserving hidden-session visibility and borrowed-read behavior. No configuration, dependency, protocol or database schema changes.

Production LOC: +1, 036 / -1, 048, net -12. Tests and test support: +576 / -266, net +310. Documentation: +7; assertion ratchet: net zero. The removed paths are per-task worker startup/termination plumbing, duplicate catalog request bookkeeping and main-thread TypeScript preparation.

User Impact

CodeMode becomes substantially faster after workers are warm, with less worker startup CPU and main-thread blocking. Sessions retain their existing orchestration and tool-authorization behavior; this does not move entire session loops to workers or claim a measured general Gateway throughput improvement.

Warm workers retain more memory. In the measured 16-way TypeScript workload, process RSS after the warm batch rose from approximately 910 MiB to 2,338 MiB. Workers retire after 60 idle seconds, but a sustained follow-up still recorded approximately 2,569 MiB RSS after every worker retired and a diagnostic parent GC. The source audit found no concrete retained per-execution VM/snapshot owner; native-memory attribution and long-term plateau remain unproven. This tradeoff was disclosed before the maintainer requested landing.

Evidence

Three alternating baseline/candidate packaged runs on Node 24.19.0, with the same installed dependencies and complete matching 148-plugin build inventories. Each process verified all 190 real host-tool bridge calls and independent context markers. The host also ran unrelated jobs, so these are observed sample medians rather than a dedicated-host capacity claim.

TypeScript workload Before After
First script, five host-tool bridges 329.7 ms 210.0 ms
Five warm sequential scripts 927.3 ms 60.1 ms
Sixteen warm concurrent scripts 297.8 ms 38.0 ms
Worker starts across the 190-call workload 228 16

The warm concurrent workload used about 85% less CPU time; the first-script main-thread timer overrun fell from 127.2 ms to 1.4 ms. A longer 1,790-call run stayed at 16 workers and all retired after the idle deadline; the memory limitation above remains.

Validation completed before publication:

  • Canonical focused suites covering real worker reuse, queue and active cancellation, termination ordering, early exit, transfers, generation fencing, TypeScript budgets, headless cancellation, compaction, catalog and auth: 191 passing tests across 10 files. The shared-pool suite was rerun after final test type fixes: 9/9 passed.
  • Gateway session/cache suites: 239 passed. The before-fix regression decoded 72 unrelated rows; the candidate decoded zero for both normal and borrowed reads.
  • ClawRouter prepared-catalog E2E: both cold discovery cases passed, with and without sibling catalog state.
  • node scripts/check-changed.mjs --base HEAD: passed, including core/test types, formatting, lint, architectural guards, dead exports and runtime import cycles.
  • node --import ./scripts/tsx.mjs scripts/build-all.mts sourcePerformance: passed, including packaged worker entries. Full build reached the UI gzip budget and failed on unchanged UI code: 348,450 bytes against 348,368. All 1,537 source modules in that closure matched the baseline; clearing only the dirty build flag still exceeded the budget. No UI budget was relaxed.
  • Real packaged Gateway mock-provider flow at 32 concurrent turns: both revisions completed 32 turns, 128 patches and 96 provider requests. Build-profile and host-load confounders prevent a causal Gateway speedup claim.
  • Fresh Codex autoreview found no actionable P0 findings. Independent source review covered lifecycle, cancellation, deadline accounting, VM isolation, snapshot ownership and current-main catalog integration.

The first hosted CI run caught a test fixture filename outside the existing test-support convention and a new lint suppression. The correction renames the fixture and makes the shared transport accept unknown input; the catalog worker owns request validation. No lint/dead-code allowlists or budgets were increased. The same run also hit the independently reproduced Doctor readiness-fixture timeout. Its existing repair landed in #134812 as 113805d6a517c27b7c2521be58c2e1fd84093ba0: the canonical prepared-runtime fixture and explicit prerequisite retain the original deadlines and migration assertions. The next merge-candidate CI run includes that upstream repair; this PR does not duplicate or take credit for it. Correction verification passed: 43 tests across five files, the complete changed-file gate run, and fresh Codex P0 review with no findings. Hosted CI 33481377907 completed successfully on exact corrected head c998a9ed9c410e273ce5ef292602ca88982d05a9: 197 successful jobs, 16 skipped and 0 failures. Remaining follow-ups are sustained native-memory attribution and exported-source plugin discovery when an enclosing Git worktree reports an empty tracked-file list. The historical UI failure above remains recorded; current main includes separate UI-budget repairs.

A separate current-main follow-up found during integration reading needs reproduction: advancePreparedModelRuntimeOwnerConfig stamps a new snapshot without updating ownersBySnapshot, which may leave a subsequent explicit stale-catalog refresh unable to resolve its owner. This preexists the worker refactor and is outside its patch.

Review response and capacity decision

ClawSweeper's September 1 review identifies the same memory tradeoff reported above and explicitly offers maintainer acceptance as an alternative to adding a new process-wide ceiling. The maintainer requested landing after receiving those measurements. This PR takes that documented tradeoff: each reusable compute pool has a finite CPU-count ceiling, but the pools do not share a process-wide worker or memory budget. Larger CPU counts can retain more warm workers and consume substantially more memory. Sixty-second retirement proves worker lifecycle completion, not operating-system RSS reclamation or a proven long-term memory plateau.

The rank-up suggestion to add a process-wide ceiling is intentionally deferred; it requires separate capacity-policy and workload evidence. No claim of safe capacity at arbitrary core counts is made. The reported stored-data-model flags do not correspond to a schema change: the pool is in-process worker state, and session reads use an existing exact-row accessor without DDL, migration, or changed persistence semantics.

@clawsweeper

clawsweeper Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: XL labels Sep 1, 2026
@steipete
steipete marked this pull request as ready for review September 1, 2026 06:50
@openclaw-barnacle openclaw-barnacle Bot added the maintainer Maintainer-authored PR label Sep 1, 2026
@steipete
steipete requested a review from a team as a code owner September 1, 2026 06:50
@steipete steipete self-assigned this Sep 1, 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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 1, 2026
@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 1, 2026, 3:25 AM ET / 07:25 UTC.

ClawSweeper review

What this changes

The PR reuses worker threads for Code Mode and background planning, moves Code Mode validation into those workers, and changes single-session Gateway reads to load only the selected SQLite row.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep this maintainer-authored performance refactor open for an explicit capacity-policy decision. The lifecycle and exact-session-read changes are coherent, but the new warm-worker design still has a documented aggregate-memory tradeoff that the code does not bound process-wide.

Priority: P2
Reviewed head: c998a9ed9c410e273ce5ef292602ca88982d05a9
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Lifecycle and session changes have coherent focused coverage, but aggregate warm-worker capacity remains a material unresolved merge decision.
Proof confidence 🌊 off-meta tidepool Not applicable: Not applicable under the maintainer-author exemption. The PR body describes packaged worker and Gateway runs, while source review confirms the changed worker layer retains Gateway-owned tool, approval, and session boundaries.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Not applicable under the maintainer-author exemption. The PR body describes packaged worker and Gateway runs, while source review confirms the changed worker layer retains Gateway-owned tool, approval, and session boundaries.
Evidence reviewed 6 items Independent OpenClaw implementation boundary: The Code Mode documentation explicitly distinguishes OpenClaw's QuickJS-WASI worker implementation from Codex Code Mode, so no Codex dependency-contract review is triggered by this PR.
Aggregate warm-worker capacity remains unbounded process-wide: The generic pool defaults to available CPU parallelism, while Code Mode and compaction each instantiate a default-sized reusable pool; the 60-second idle timer retires workers but is not a process-wide memory limit.
Worker lifecycle coverage: Focused tests exercise queued-task expiry, cancellation before replacement admission, worker retirement, transferred buffers, and per-run Code Mode global/bridge isolation.
Findings None None.
Security None None.

How this fits together

Code Mode sends guest JavaScript or TypeScript through Gateway-owned tool and approval boundaries into isolated QuickJS virtual machines. Gateway session utilities separately resolve persisted session entries for session-facing operations; this PR changes both execution reuse and exact-row lookup work.

flowchart LR
  A[Code Mode request] --> B[Gateway ownership and approvals]
  B --> C[Warm worker pool]
  C --> D[Isolated QuickJS virtual machine]
  D --> E[Tool bridge result]
  F[Gateway session request] --> G[Exact SQLite row lookup]
  G --> H[Session projection]
Loading

Decision needed

Question Recommendation
Should OpenClaw accept CPU-count warm pools without a process-wide worker or memory budget for this performance change? Add a process-wide capacity budget: Coordinate reusable compute pools behind a conservative aggregate cap and validate high-core memory behavior through idle retirement.

Why: The prior capacity concern is stated as deferred in the PR body, but current code still permits at least two independent CPU-scaled pools and does not mitigate the reported RSS behavior.

Before merge

  • Resolve merge risk (P1) - Each of the Code Mode and compaction pools can retain one worker per available CPU for 60 seconds; the PR body reports high RSS after a 16-worker Code Mode workload and does not establish aggregate high-core memory behavior.
  • Complete next step (P2) - The remaining action is a maintainer capacity-policy choice, not a narrow mechanical repair.
Agent review details

Security

None.

PR surface

Source -12, Tests +310, Docs +7, Other 0. Total +305 across 33 files.

View PR surface stats
Area Files Added Removed Net
Source 17 1036 1048 -12
Tests 14 576 266 +310
Docs 1 8 1 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 33 1621 1316 +305

Review metrics

Metric Value Why it matters
Implementation delta production +1,036 / -1,048 (net -12); tests and test support +576 / -266 (net +310) The refactor is production-net-negative while adding focused lifecycle and session-lookup coverage.
Default pool topology 2 CPU-scaled reusable pools; 2 fixed single-worker pools Independent CPU-scaled pools are the source of the aggregate capacity decision before merge.

Stored data model

Persistent data-model change detected: durable storage schema: src/infra/worker-task-pool.ts, unknown-data-model-change: src/agents/code-mode-worker.ts, unknown-data-model-change: src/infra/worker-task-pool.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Bound aggregate warm capacity before merge (recommended)
    Add a process-wide worker or memory budget that covers both CPU-scaled pools, then show retirement behavior under a representative high-core workload.
  2. Accept the measured memory tradeoff
    Record an explicit maintainer decision to retain the CPU-count pools without a process-wide ceiling and keep the RSS limitation visible in the PR evidence.

Technical review

Best possible solution:

Adopt a process-wide warm-worker capacity budget with aggregate high-core retirement evidence, or explicitly accept this documented memory tradeoff before landing.

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

Not applicable as a correctness-bug reproduction: this PR optimizes existing behavior. Its capacity concern is source-visible, and the PR body supplies reported high-concurrency measurements but no independently inspectable artifact.

Is this the best way to solve the issue?

Unclear. Shared workers and exact-row reads remove the stated repeated work, but a process-wide bound is the safer complete solution unless maintainers intentionally accept the documented memory tradeoff.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 4a2edc54888a.

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Not applicable under the maintainer-author exemption. The PR body describes packaged worker and Gateway runs, while source review confirms the changed worker layer retains Gateway-owned tool, approval, and session boundaries.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a bounded performance refactor with a significant but non-emergency availability tradeoff.
  • merge-risk: 🚨 availability: Warm worker retention scales with CPU count in separate pools, and the PR documents unresolved elevated RSS after worker retirement.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Not applicable under the maintainer-author exemption. The PR body describes packaged worker and Gateway runs, while source review confirms the changed worker layer retains Gateway-owned tool, approval, and session boundaries.

Evidence

What I checked:

  • Independent OpenClaw implementation boundary: The Code Mode documentation explicitly distinguishes OpenClaw's QuickJS-WASI worker implementation from Codex Code Mode, so no Codex dependency-contract review is triggered by this PR. Public docs: docs/tools/code-mode.md. (docs/tools/code-mode.md:25, c998a9ed9c41)
  • Aggregate warm-worker capacity remains unbounded process-wide: The generic pool defaults to available CPU parallelism, while Code Mode and compaction each instantiate a default-sized reusable pool; the 60-second idle timer retires workers but is not a process-wide memory limit. (src/infra/worker-task-pool.ts:58, c998a9ed9c41)
  • Worker lifecycle coverage: Focused tests exercise queued-task expiry, cancellation before replacement admission, worker retirement, transferred buffers, and per-run Code Mode global/bridge isolation. (src/infra/worker-task-pool.test.ts:69, c998a9ed9c41)
  • Exact-row session behavior: Owned and borrowed reads select the appropriate exact-row accessor; the focused test seeds 24 unrelated rows and verifies they are not decoded while projection and hidden-effect behavior remain intact. (src/gateway/session-utils-store-lookup.ts:220, c998a9ed9c41)
  • Current-main and release status: The fetched main revision and latest stable release do not contain the new worker-pool file, and the PR head is not an ancestor of fetched main; this work is neither implemented on main nor shipped. (src/infra/worker-task-pool.ts:42, 4a2edc54888a)
  • Feature-history routing: Local history shows Peter Steinberger's prior merged Code Mode lifecycle and output repairs, including the earlier bounded-worker lifecycle work; deeper blame could not be completed because this partial clone required an unavailable promisor fetch. (src/agents/code-mode-worker.ts:76, 681535cb8b98)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Obtain an explicit capacity-policy decision, or introduce a process-wide warm-worker budget with representative aggregate-memory evidence.

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 (1 earlier review cycle)
  • reviewed 2026-09-01T06:57:34.113Z sha 5471188 :: found issues before merge. :: [P1] Bound the default warm-worker capacity

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 1, 2026
@steipete

steipete commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Exact-head CI is green for c998a9ed9c410e273ce5ef292602ca88982d05a9: run 33481377907 completed with 197 successful jobs, 16 skipped and no failures. The correction also passed 43 focused tests across five files, the complete changed-file gates, and fresh Codex autoreview at P0 scope. Independent source review found no correctness regression in the worker message boundary correction.

The first failed run is retained in the PR evidence. This head fixes the test-support filename and removes the new lint suppression by validating raw worker input at the catalog owner. The independently recurring Doctor startup-fixture failure was repaired on main in #134812; the green merge-candidate CI includes that existing repair. No timeout, assertion, lint allowance or dead-code budget was weakened. Final production LOC is +1,036/-1,048, net -12; tests and test support are net +310.

For ClawSweeper's capacity finding, the maintainer requested landing after disclosure of the measured RAM cost. We are taking the review's documented acceptance option: CodeMode and compaction each have their own CPU-count worker cap, with no process-wide worker or memory ceiling. Their 60-second idle retirement terminates workers but does not promise RSS reclamation. The observed 16-way TypeScript RSS increase and unproven long-term plateau remain explicit limitations. The suggested process-wide ceiling is deferred for separate capacity-policy and workload evidence. The reported storage flags do not represent a SQLite schema or persistence change.

Proceeding through the native preparation and merge gates; no review or CI enforcement is being bypassed.

@steipete
steipete merged commit d9f3889 into main Sep 1, 2026
278 checks passed
@steipete
steipete deleted the codex/perf-session-workers-20260901 branch September 1, 2026 07:28
@steipete

steipete commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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 maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. 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