Skip to content

perf(plugins): reduce prompt-hook envelope copying - #183457

Merged
steipete merged 1 commit into
mainfrom
perf/l1743-prompt-hook-envelope
Oct 25, 2026
Merged

steipete merged 1 commit into
mainfrom
perf/l1743-prompt-hook-envelope

Conversation

@steipete

@steipete steipete commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Prompt hooks still copy their complete event envelope through structuredClone, even after #182349 made owned transcript payloads shareable. A sampled Gateway workload attributed 13.23 MB in 30.484 seconds to that residual clone; #182349 is already an ancestor of the sampled build.

User Impact

Lower allocation and CPU cost when preparing prompts with plugins. Prompt bytes and hook isolation semantics are unchanged: handlers in one dispatch share their mutable envelopes, separate dispatches remain isolated, and owned transcript leaves remain frozen.

Why This Change Was Made

Construct the fresh envelopes directly and clone only their unowned values as one graph. This preserves aliases, native-value behavior, and shared-memory rejection without serializing immutable strings or re-copying freshly constructed envelopes. A dispatch with no unowned values now needs no native clone.

Core production delta is +20 lines; benchmark instrumentation/usage adds 99 net lines. The remaining graph/position bookkeeping preserves the existing public contract for arbitrary unowned hook values; the whole-envelope clone and owned-field removal/restoration machinery are deleted. No cache, plugin registration flag, or alternate policy path is introduced.

Evidence

Acceptance: identical synthetic workloads, separate unprofiled CPU and sampled-allocation passes, five samples per cell; reduced allocation/dispatch without changing output or isolation. Built-Gateway stress additionally checks CPU, GC, event-loop and list tails, memory, real mock-provider tool turns, and hook execution.

Owner measurements (median, one handler, 20 dispatches × 5 samples per cell):

Messages / prompt chars Allocation bytes/build, base → candidate CPU ms/build, base → candidate
64 / 16 324,181 → 152,520 (−53.0%) 0.1718 → 0.0976 (−43.2%)
200 / 16 1,034,337 → 444,655 (−57.0%) 0.5475 → 0.2963 (−45.9%)
1,000 / 16 4,765,878 → 2,265,892 (−52.5%) 2.8810 → 1.5654 (−45.7%)
64 / 262,144 591,621 → 154,303 (−73.9%) 0.1899 → 0.1021 (−46.2%)

The full one/two-handler owned-history matrix reduces allocation 50–74% and CPU 41–55%. The fully unowned-history control (5 dispatches × 5 samples) ranges from −5.3% to +0.3% allocation and −6.5% to +5.2% CPU; no broad speedup is claimed for that retained native-clone path. Run scripts/perf/hook-isolation-measure.ts --expect-shared-history --calls 20 --samples 5 with --prompt-chars 16 and 262144; the script header documents invocation.

Built-Gateway stress completed on isolated local Gateways: independently generated 10,000-session states, 6,000 settled runs, 32 project worktrees, 64 WebSocket clients, 32 mock turn clients, 40 verified fixture plugins plus memory-core, and two positively counted prompt hooks. List/search/sidebar churn and successful exec read/grep calls continued throughout. No production Gateway was load-tested.

Base a36ac4e43966329ce7cf396cb0f66add46ae5676: 614.7 s untraced, 911 turns, 3,076 model-request attempts. Candidate pre-rebase source 9736f220a7af1cc76e07ec1200d3ac36708448e8 (patch unchanged at PR head f3a6cf70276e561b99eca9cbe959920aa50b0633): 606.5 s, 1,697 turns, 4,642 attempts. Allocation windows were separate (78.2 s / 196 requests and 68.4 s / 382 requests).

Metric Base Candidate
Main-thread CPU 66.08% 83.74%
Main CPU / model request 132.05 ms 109.42 ms
Allocation rate (separate sampled window) 132.84 MB/s 306.73 MB/s
Allocation / model request 52.98 MB 54.89 MB
GC time 1.950 s/min 2.179 s/min
GC / model request 6.493 ms 4.745 ms
Event-loop p95 / p99 42.17 / 127.40 ms (n=30,335) 26.77 / 59.41 ms (n=38,865)
sessions.list p95 / p99 1638.42 / 3168.36 ms (n=7,687) 842.08 / 1358.44 ms (n=7,680)
RSS / used heap after window 3.805 / 0.916 GB 4.888 / 0.845 GB
Largest GC pause 280.11 ms 880.17 ms
Prompt-hook allocation / history message 12,305 B 10,925 B (−11.2%)

This is a shared-Mac sequential stress comparison, not a controlled estimate of Gateway-wide speedup. Outside load and completed-work counts differed. Average history during allocation grew from 152.6 to 282.6 messages/build; prompt-hook allocation/build therefore rose from 1.88 to 3.09 MB while allocation/history-message fell 11.2%. Raw allocation rate and CPU percentage rose with throughput. Allocation/request rose 3.6%; used heap fell 7.8%, but RSS rose 28.5%. The 880 ms maximum GC pause exceeds twice baseline and remains an unresolved max-pause signal; this lane did not run matched A/A stress controls. Do not read the lower request-normalized CPU/GC or lower latency tails as a causal claim. The repeatable owner matrix and the loaded hook-family allocation reduction are the performance evidence.

GC details (untraced): minor count 3,718 → 6,257, total 17.461 → 18.696 s, p95/p99 9.854/50.686 → 4.126/8.254 ms, max 268.33 → 116.84 ms. Major count 39 → 17, total 2.432 → 3.276 s, max 280.11 → 880.17 ms; major percentiles are context only below 50 collections. Incremental count 39 → 17, total 80.79 → 54.98 ms. Event-loop maxima were 2634.02 → 1163.92 ms. Maintenance stayed enabled; no pauses or windows were discarded after seeing their results.

Use the commands in scripts/perf/ws-counter-stress.ts's header with --duration-seconds 600 --allocation-seconds 60. A preliminary warmup-only attempt was discarded before measurement because the new harness incorrectly required nonempty history on the first turn of a fresh session; the corrected check requires hook execution in warmup and nonempty history in each measured window. Full baseline used a newly generated state after that harness smoke.

Correctness: the new zero-serialization regression fails on base a36ac4e43966329ce7cf396cb0f66add46ae5676; the other 43 hook cases pass there. Candidate: 86 tests pass across hooks.phase-hooks.test.ts, hooks.before-tool-call.test.ts, and agent-tools.prefix-stability.test.ts, including exact UTF-16 prompt bytes for four hook mixes, cross-dispatch isolation, shared frozen leaves, unowned native values/aliases, and shared-memory rejection. The hook files took 20.78 s including compilation (75 tests); the prefix file took 196.75 s including compilation (11 tests). One earlier attempt was discarded because a lint-only source edit invalidated the compiler snapshot. The existing scan-count check now measures warm dispatches: the projection owner legitimately admits frozen metadata on first access; payload identity and mutation assertions remain unconditional.

Focused oxfmt/oxlint, git diff --check, and pnpm tsgo:core pass. Baseline pnpm build completed; it reported pre-existing UI size-budget warnings (startup JS gzip 266.9 vs 266.7 KiB, CSS raw 1558.2 vs 1558.1 KiB). Candidate pnpm build runtime completed (2m 22s). PR CI run 40178171521 passed on exact head f3a6cf70276e561b99eca9cbe959920aa50b0633, including openclaw/ci-gate; no repair push or rerun was needed.

Independent subagent review (autoreview route unavailable): scoped-clean at P0–P2, including the measurement-counter followup. The autoreview helper refused a provider/operator-config mismatch; configuration was left unchanged.

GitHub code review also completed on f3a6cf7 with no findings.

@clawsweeper

clawsweeper Bot commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@steipete
steipete marked this pull request as ready for review October 25, 2026 08:49
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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 ✅ Completed 2026-10-25T08:51:44.842131Z f3a6cf7 Draft marked ready
ℹ️ 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.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: M labels Oct 25, 2026
@steipete
steipete merged commit 10c6c29 into main Oct 25, 2026
203 of 206 checks passed
@steipete
steipete deleted the perf/l1743-prompt-hook-envelope branch October 25, 2026 09:01
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

scripts Repository scripts size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant