Repository navigation
perf(plugins): reduce gateway scope frame allocations - #181771
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review in progressClawSweeper is reviewing this revision. This supersedes any previous blocked status. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
d8b6437 to
cd5225c
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cd5225cdf3
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
27914ea to
614bda7
Compare
Remove one native context-map restore and the per-entry recovery resolver. Preserve mutable Gateway views, exact recovery-source identity, and all instance and delegated authority fences. Add paired plugin RPC measurement with optional pacing.
614bda7 to
190f1c8
Compare
|
The remaining recovery-test callers and the tool-factory store-count assertion are migrated; their focused regressions pass. The full three-pair owner/RPC measurements and limitations are now in the PR body, with no rejection threshold crossed. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Codex review: needs maintainer review before merge. What this changesThis PR restores plugin invocation and input-recovery contexts through one async resource and extends the existing performance tooling. Example: An owned plugin callback runs inside a Gateway request.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this maintainer-authored PR provides a measured allocation reduction without an identified correctness defect; current-head CI remains pending. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherPlugin invocation scopes carry Gateway request facts and lazily resolve recovery admission for nested channel and reply operations, then restore the caller's context. flowchart TD
A[Gateway request] --> B[Plugin instance admission]
B --> C[Plugin execution resource]
C --> D[Invocation and recovery stores]
D --> E[Plugin callback]
D --> F[Reply and channel recovery admission]
Technical reviewBest possible solution: Use the existing plugin async resource to restore both stores while retaining lazy recovery lookup, exact source matching, and independent mutable request views. Do we have a high-confidence way to reproduce the issue? The base source shows the redundant recovery.run restoration around the existing async resource, and the PR supplies comparative owner and real Gateway measurements; no target code was executed during this review. Is this the best way to solve the issue? The change removes redundant work at the existing owner without introducing a cache or parallel lifecycle, and the added source comparison preserves generation-view rebinding. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against c3b57f74833d. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +7, Tests +104, Docs +35, Other +52. Total +198 across 12 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 23, 2026, 1:36 PM ET / 17:36 UTC. |
* perf(plugins): restore invocation and recovery scopes together Remove one native context-map restore and the per-entry recovery resolver. Preserve mutable Gateway views, exact recovery-source identity, and all instance and delegated authority fences. Add paired plugin RPC measurement with optional pacing. * fix(plugins): preserve optional recovery owner in scope type * test(perf): support settled run history in team fixtures * test(perf): verify plugin scope against installed source * test(plugins): migrate remaining recovery context callers * test(plugins): account for recovery store in scope entry count
What Problem This Solves
Plugin invocations copy a native async-context map again when the input-recovery wrapper restores its parent, even though the enclosing plugin async resource already restores that context.
User Impact
Reduces allocation in plugin calls while preserving recovery admission, mutable request isolation, and plugin lifecycle checks. No configuration or SDK behavior change.
Why This Change Was Made
Install the recovery source inside the existing plugin async resource and let that resource restore both stores. Carry the request view directly instead of allocating a resolver closure. Re-enter only when the plugin frame, invocation, or recovery source differs. The recovery-source comparison matters because generation scopes can create a new mutable view while retaining the parent's recovery context.
Instance admission remains owned by
PluginInstance.activeCall/hasTokenandenter; retained consumers and closure-bound delegated capabilities keep their existing checks. Registry borrowing and mutable sibling views remain independent. The small runtime LOC increase pays for the structural recovery-source contract and exact source comparison; the per-call closure and extra restore operation disappear.Evidence
Focused scope/invocation tests: 21 passed. The new work-count regression fails on the base and passes with the change; sibling recovery rejection and generation-view rebinding also pass. Closure guards: 22 passed. Export-name collision guard, changed-file format/lint, and
pnpm tsgo:core(tsrs) pass. Independent Codex review completed for the implementation and follow-up test/fixture corrections. Recovery consumers: 29 tests passed; tool-factory context: 16 passed; team fixture: 4 passed. All remaining callers of the removed recovery wrapper were migrated. The fixture uses the publicrespondcallback and compares plugin source against the original installation path, not the captured artifact’s__filename.Measurement acceptance: identical synthetic workloads in concurrent pairs on interleaved 16-CPU placements, swapped for pair two. Decide using paired means. A 20% adverse mean or 10% adverse in both pairs rejects; opposing signs or baselines differing by more than 5× are inconclusive and get a third pair if gating. GC pause shifts below 1 ms are context; report counts and maxima. The owner workload measures 4,000 turns × 33 plugin callbacks, with separate collected-allocation and unprofiled CPU/GC passes. A real plugin RPC complement uses synthetic 5,000-session/6,000-run state at approximately 200 RPC/minute, with allocation and CPU passes separate. All paired measurements completed without a guard interruption; the third-pair results below resolve mixed-sign metrics using absolute means.
Broad validation is delegated to PR CI. No Testbox/Crabbox lease or local broad suite/build was used.
Owner measurement (132,000 plugin callbacks per side per pair, Node 26.12.1):
Minor GC counts: 87 → 107 and 86 → 73; major counts: 5 → 6 and 5 → 5. Minor p99: 1.498 → 1.726 ms and 1.670 → 1.793 ms (context: fewer than 1,000 collections and mean +0.176 ms). Minor maxima: 1.498 → 1.743 ms and 1.670 → 1.793 ms; major maxima: 7.729 → 4.971 ms and 7.619 → 6.505 ms. Major tails are context with fewer than 50 collections. No max-pause threshold is crossed. Native store installs per turn: 150 → 100; direct instance call: 3 → 2; nested same-instance calls: 6 → 4 while preserving independent mutable views.
Runtime production delta: +7 lines across two owner files; the added structural type and source identity check preserve mutable-view and generation rebinding contracts. Benchmark/test additions are separate from runtime growth.
A third owner pair resolves the opposite-sign CPU result under the absolute-mean rule: 14.263 → 13.891 µs/callback (−0.372 µs, −2.61%). Across all three pairs the absolute CPU delta is +0.146 µs/callback (about +1.07% of the mean baseline), below the rejection thresholds. The third pair confirms allocation reduction (12,133.8 → 10,211.1 B, −15.85%). Its minor/major counts are 123/5 → 105/5; minor maxima 2.680 → 5.265 ms, major maxima 7.873 → 6.083 ms, and loop p99 1.904 → 1.829 ms (3,999 samples each). No max-pause gate is crossed.
Real Gateway plugin RPC result
The registered plugin verifies its ID, original source, origin, registry, and client before and after an
await, then replies through the public callback. Each side completes 240 RPCs after 40 warmups, paced at about 201 RPC/minute. Synthetic state contains 5,000 sessions, 6,000 settled retained runs, 200 approvals, 100 cron jobs, and one project. The new--settled-runsoption preserves retained history and failed terminal outcomes while excluding the restart-recovery backlog. The default mixed fixture remains unchanged.Both versions initially failed startup on the mixed fixture’s recovery-capacity limit; those attempts were excluded. An initial probe also exposed the distinction between installed plugin source and captured runtime filename; correcting that assertion made both sides pass. No production state or Gateway was used.
Allocation and unprofiled CPU/GC passes were separate. Values below are baseline → candidate. Opposite-sign results received a third pair. The final column uses the absolute mean of all three deltas; its percentage is relative to the mean baseline, not a mean dominated by a small denominator.
The first two unprofiled pairs had GC −9.65%, promotion +6.19%, and process CPU +1.23%; none crossed a gate. Their main-thread CPU, loop p99, and RPC p95 directions were mixed, so the third pair was required. Its GC delta was +10.29%, with a three-pair absolute mean still −0.00534 ms/RPC. No metric meets the rejection rule. This is a modest whole-Gateway allocation reduction with essentially neutral CPU and latency. The larger 15.23% result applies to the isolated scope-owner workload.
Event-loop sample counts (baseline → candidate): 3,569 → 3,568; 3,566 → 3,566; 3,561 → 3,562. RPC p99 is context only with 240 samples per side: 1.451 → 1.393 ms, 1.478 → 1.486 ms, and 3.050 → 3.081 ms.
Unprofiled minor GC counts: 62 → 61, 63 → 56, 60 → 56; no major collections occurred. Minor p95: 0.954 → 0.970 ms, 1.014 → 1.030 ms, 1.542 → 1.574 ms. Minor p99: 1.118 → 1.002 ms, 1.070 → 1.198 ms, 1.990 → 2.142 ms. These tails are context only (sample count and sub-millisecond mean shift). Maximum pauses: 4.482 → 1.032 ms, 1.083 → 1.306 ms, 2.213 → 11.299 ms; no max-pause gate is crossed.
For completeness, the allocation-pass minor counts/maxima were 59/1.229 → 59/1.001, 56/1.167 → 55/1.463, and 60/1.486 → 55/1.388 ms. Each side also had one profiler-related major collection: maxima 109.244 → 82.554 ms, 104.438 → 118.771 ms, 94.154 → 125.762 ms. CPU/GC decisions use the unprofiled passes above.
Reproduce with the committed owner workload
scripts/perf/plugin-gateway-scope-measure.ts --turns 4000 --calls 16, using--expose-gc --trace-gc-nvp, separate--start-at/--cpu-start-at, and output/GC-log paths. For the RPC complement:Add
--allocationsonly for the separate allocation pass. Run baseline/candidate concurrently with separate state/ports and interleaved 16-CPU placements, then swap placements. Measurements used baselineb19bade1d3ad29533784228947e7a729c70a0961plus only the two candidate runtime owners; subsequent rebases left those measured files unchanged.CI follow-up and deployment signal
The first broad run found a stale tool-factory store-count assertion; its exact failure was reproduced locally and corrected to count both explicit stores in each resource. All 16 tests in that file pass. The labeling job separately received GitHub HTTP 500 when applying labels. Final head
190f1c8c1932f010c106f34ed710f95df0506cdcpassed CI run 39995665978, and both requiredopenclaw/ci-gatechecks are successful. ClawSweeper reviewed this exact head with no findings.After deployment, compare the native Map/iterator allocation stack under
plugin-instance-invocation → runWithPluginGatewayScope → withPluginRuntimePluginScopeat comparable traffic. The deterministic signal is direct-call store installs 3 → 2; production allocation savings still need that live confirmation.