Skip to content

perf(plugins): reduce gateway scope frame allocations - #181771

Merged
steipete merged 6 commits into
mainfrom
steipete/perf-micro-plugin-scope-frames-20260919
Oct 23, 2026
Merged

steipete merged 6 commits into
mainfrom
steipete/perf-micro-plugin-scope-frames-20260919

Conversation

@steipete

@steipete steipete commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

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/hasToken and enter; 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 public respond callback 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):

Metric Pair 1 baseline → candidate Pair 2 baseline → candidate Mean paired delta
Estimated allocated bytes/callback 12,049.6 → 10,247.6 12,053.7 → 10,184.4 −15.23%, −1,835.7 B
CPU µs/callback 13.208 → 13.132 13.466 → 14.353 +3.00%, +0.405 µs; opposite signs, inconclusive
GC µs/callback 0.761 → 0.699 0.836 → 0.753 −9.03%
Promoted bytes/callback 475.37 → 445.74 475.63 → 443.25 −6.52%
Event-loop p99 ms (3,999 samples/side/pair) 1.548 → 1.510 1.669 → 1.636 −2.21%

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-runs option 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.

Metric Pair 1 Pair 2, swapped Pair 3 Three-pair absolute mean delta
Estimated allocated B/RPC 213,078.5 → 213,854.8 214,215.6 → 203,609.9 206,459.3 → 197,027.3 -6,420.5 (-3.04%)
Main-thread CPU ms/RPC 1.5671 → 1.5577 1.7293 → 1.7512 2.0317 → 1.9587 -0.0202 (-1.13%)
Process CPU ms/RPC 10.5618 → 10.7477 11.1627 → 11.2410 12.6555 → 12.7001 +0.1029 (+0.90%)
GC ms/RPC 0.2152 → 0.1893 0.2094 → 0.1941 0.2435 → 0.2686 -0.0053 (-2.40%)
Event-loop p99 ms 20.5292 → 20.6111 20.6602 → 20.6111 21.0043 → 21.0043 +0.0109 (+0.05%)
RPC p95 ms (240 samples/side) 1.3407 → 1.3153 1.3838 → 1.3973 1.8202 → 1.6452 -0.0623 (-4.11%)
Promoted B/RPC 29,360.8 → 31,657.3 29,247.0 → 30,580.1 41,719.6 → 29,142.5 -2,982.5 (-8.92%)

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:

node --import ./scripts/tsx.mjs scripts/perf/team-shape-fixture.ts \
  --state-dir "$FIXTURE" --sessions 5000 --runs 6000 --settled-runs \
  --approvals 200 --cron 100 --projects 1 --transcript-mib 16 --port 41603
node --import ./scripts/tsx.mjs scripts/perf/transcript-broadcast-measure.ts \
  --state-dir "$FIXTURE" --entry src/entry.ts --scenario plugin.scope \
  --port 41603 --mock-port 41605 --clients 1 --runs 1 --rpc-concurrency 1 \
  --warmup-operations 40 --operations 240 --rpc-interval-ms 300 --rounds 1 \
  --diagnostics --trace-gc --start-at "$SHARED_START"

Add --allocations only for the separate allocation pass. Run baseline/candidate concurrently with separate state/ports and interleaved 16-CPU placements, then swap placements. Measurements used baseline b19bade1d3ad29533784228947e7a729c70a0961 plus 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 190f1c8c1932f010c106f34ed710f95df0506cdc passed CI run 39995665978, and both required openclaw/ci-gate checks are successful. ClawSweeper reviewed this exact head with no findings.

After deployment, compare the native Map/iterator allocation stack under plugin-instance-invocation → runWithPluginGatewayScope → withPluginRuntimePluginScope at comparable traffic. The deterministic signal is direct-call store installs 3 → 2; production allocation savings still need that live confirmation.

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@steipete
steipete marked this pull request as ready for review October 23, 2026 17:01
@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: M labels Oct 23, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-23T17:30:48.665652Z 190f1c8 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@steipete
steipete force-pushed the steipete/perf-micro-plugin-scope-frames-20260919 branch from d8b6437 to cd5225c Compare October 23, 2026 17:07

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

@steipete
steipete force-pushed the steipete/perf-micro-plugin-scope-frames-20260919 branch from 27914ea to 614bda7 Compare October 23, 2026 17:17
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 23, 2026
@steipete
steipete force-pushed the steipete/perf-micro-plugin-scope-frames-20260919 branch from 614bda7 to 190f1c8 Compare October 23, 2026 17:30
@steipete

Copy link
Copy Markdown
Contributor Author

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

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 23, 2026
@clawsweeper

clawsweeper Bot commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This 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.

  • Before: The reported direct-call workload installs three native stores.
  • After: It installs two stores while preserving request identity across an await.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization supported by detailed real Gateway measurements and distinct scope regressions, with no actionable defect found.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The inspected body records isolated real Gateway WebSocket requests through a registered plugin, verifying identity and scope continuity across await with paired allocation and CPU measurements; source inspection matches that exercised path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Frequent plugin calls generate avoidable temporary allocations in busy Gateways.
Reason: The maintainer-authored direction removes measured redundant work while preserving existing public behavior and recovery contracts.

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
Reviewed head: 190f1c8c1932f010c106f34ed710f95df0506cdc

Before merge

None.

Findings

None.

Agent review details

How this fits together

Plugin 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]
Loading

Technical review

Best 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

  • Recovery context installation keeps the original intent (571040c: Provide per-agent recovery admission while healthy agents continue serving, with saved input preceding fresh input.)
  • Shared execution frames and mutable Gateway views keeps the original intent (refactor(gateway): reduce allocations during parallel sessions #146219: Reduce async-context allocation while retaining Gateway identity, mutable sibling isolation, and caller authority through invocation changes.)
  • Generation-frame composition keeps the original intent (1418ad7: Compose prepared generation facts through the existing execution frame while preserving independent scope exits.)
  • Synthetic team-shaped fixture keeps the original intent (test(perf): add shared team-shaped state fixtures #171151: Generate realistic synthetic state through existing storage owners without overwriting existing destinations.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit a08cdc5 adds src/plugins/runtime/gateway-request-scope.ts:116 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a08cdc50bc04; files: src/plugins/runtime/gateway-request-scope.ts)

PR surface

Source +7, Tests +104, Docs +35, Other +52. Total +198 across 12 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 40 33 +7
Tests 6 129 25 +104
Docs 1 35 0 +35
Config 0 0 0 0
Generated 0 0 0 0
Other 3 58 6 +52
Total 12 262 64 +198

Review metrics

Metric Value Why it matters
Runtime versus regression coverage Runtime +40/-33 lines; tests +129/-25 lines The net seven runtime lines replace a per-call closure and restore wrapper with an explicit structural context and source-identity check; tests cover isolation, restoration, and fixture state.
Performance tooling options Two flags and one scenario --settled-runs and --rpc-interval-ms support the new plugin.scope measurement without adding product configuration.

Labels

Label changes:

  • add P2: A measured performance improvement on frequent plugin calls has useful but limited user impact.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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:

  • P2: A measured performance improvement on frequent plugin calls has useful but limited user impact.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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 execution lanes are retired.

Reviewed October 23, 2026, 1:36 PM ET / 17:36 UTC.

@steipete
steipete merged commit 68bc4fc into main Oct 23, 2026
154 of 155 checks passed
@steipete
steipete deleted the steipete/perf-micro-plugin-scope-frames-20260919 branch October 23, 2026 17:47
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 24, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. 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: M 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