Repository navigation
perf: reduce CodeMode latency and session lookup work - #134935
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed September 1, 2026, 3:25 AM ET / 07:25 UTC. ClawSweeper reviewWhat this changesThe 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 readinessKeep 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 Review scores
Verification
How this fits togetherCode 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]
Decision needed
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
Agent review detailsSecurityNone. PR surfaceSource -12, Tests +310, Docs +7, Other 0. Total +305 across 33 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest 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. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
|
Exact-head CI is green for 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. |
|
Merged via squash.
|
* perf: reduce CodeMode latency and session lookup work * refactor: validate worker messages at the catalog boundary
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.
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:
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.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 headc998a9ed9c410e273ce5ef292602ca88982d05a9: 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:
advancePreparedModelRuntimeOwnerConfigstamps a new snapshot without updatingownersBySnapshot, 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.