Skip to content

perf(agents): reuse frozen request projection wrappers - #183243

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-stable-projected-wrappers-20261025
Oct 25, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-stable-projected-wrappers-20261025

Conversation

@steipete

@steipete steipete commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Repeated model requests rebuild projection wrappers around unchanged, deeply frozen transcript messages, defeating message-level fingerprint reuse and allocating fresh fingerprint records on every request.

User Impact

Request preparation uses less CPU and allocation for unchanged history. Provider-facing message bytes, tool-result truncation policy, image blocking, runtime-context retention, and mutable-input behavior stay unchanged. No configuration or migration is required.

The tradeoff is additional weakly held projection state: this fixture retains 0.83 MiB more in projection/admission state, but 1.68 MiB less in observation state, for 0.85 MiB less overall. Cold observation CPU rises by 0.44 ms on average; the repeated-request path improves by 0.89 ms. These are owner-path measurements, not a whole-Gateway throughput claim.

Why This Change Was Made

Cache pure projections at their existing owners, using deeply frozen sources as weak keys and separate policy variants. Key binding survives attempt-state recreation for canonical tool results; ambiguous identities remain scoped to their projection state. Replacement projections also key by immutable replacement content and check canonical key, source hash, and TTL mode. Version-4 normalization, detail stripping, custom conversion, image policy, and retention now preserve immutable wrapper identity across requests.

Runtime-context retention was the downstream mutation boundary: frozen carriers now select a frozen projection in the request-owned array, while mutable carriers retain their existing in-place behavior. The per-message tool-result merge moved out of the batch owner into one module; its old implementation was removed. The checkpoint owns the shared projection shape so its leaf contract does not depend on the projection implementation. The core conversion package and fingerprint implementation are unchanged.

Production source delta is +192 lines; tests add 179 lines (+182/-3). This is necessary growth for the requested weak identity reuse and policy separation, plus copy-on-write retention that preserves the existing mutable contract. One shared helper owns frozen-source memoization for the pure projections; there is one merge implementation and no parallel legacy algorithm. Including the benchmark, the requested non-test/non-doc stat is +296 lines. Simplification review found no further coherent deletion without losing one of these boundaries.

Evidence

Five alternating base/head pairs on Node 26.12.1, synthetic 16 sessions × 128 messages, 20 rounds: 320 warm requests plus 16 cold observations per process. The path is cloneTranscriptView → fresh-state key binding → tool-result replay (including owner-recorded replacements) → version-4 normalization → session conversion → retention → request observer → beginPromptCacheObservation.

Measured base: dfcb2469b18ab1c92aa5421eb994b3f7cc5c9677; measured candidate: fce2acaaa58014d0816ee5ec79ed1db495304394. The final branch was rebased without conflicts; the measured production patch was preserved. A subsequent CI repair moves only the unchanged TypeScript projection type into its leaf checkpoint contract; runtime algorithms are unchanged. CPU/retained-heap runs are untraced; allocation uses separate 512-byte sampling profiles including collected objects. Retention uses forced GC. Promotion has its own two traced pairs and is not used to infer untraced timing. Each row reports arithmetic side means and the mean of paired percentage changes.

Metric Base Candidate Paired change Samples per side
Recreated final wrappers/request 96 0 −100% 5 × 128-message identity probes
Message fingerprint identity reuse 32/128 (25%) 128/128 (100%) +75 percentage points 5 probes
Warm preparation + observer CPU/request 1.4106 ms 0.5231 ms −62.91% 5 × 320 requests
Total sampled allocation/model call 1110.98 KiB 298.53 KiB −73.13% 5 × 336 calls
Fingerprint-family sampled allocation/model call 714.83 KiB 0.325 KiB −99.95% 5 × 336 calls
Observation retained heap 2.789 MiB 1.111 MiB −60.14% 5 forced-GC samples
Projection/admission retained heap 0.725 MiB 1.552 MiB +114.04% 5 forced-GC samples
Total retained heap 3.514 MiB 2.663 MiB −24.22% 5 forced-GC samples
Cold observer CPU/request (preparation excluded) 5.168 ms 5.610 ms +9.18% 5 × 16 observations

CPU improved 62.33–63.81% and allocation improved 73.07–73.18% in every pair. Cold deltas were mixed-sign (−4.15% to +28.51%); this is context, not a warm-path benefit.

GC, promotion, byte identity, reclamation, and reproduction

Untraced GC windows cover 320 warm requests each. All observed collections were minor; major collections were 0 on both sides, so there is no major-GC tail claim. Counts are below percentile admission thresholds; no p95/p99 claim is made. Both maxima and absolute totals are retained below, with no pause trimming or per-major-cycle normalization.

Pair Minor collections base/head Total GC base/head (ms) GC/request base/head (ms) Max pause base/head (ms)
1 11 / 2 84.957 / 1.156 0.2655 / 0.0036 19.281 / 0.598
2 11 / 2 170.139 / 1.382 0.5317 / 0.0043 40.842 / 0.848
3 11 / 2 66.519 / 1.154 0.2079 / 0.0036 17.076 / 0.641
4 11 / 2 42.417 / 1.159 0.1326 / 0.0036 6.470 / 0.591
5 11 / 2 24.105 / 1.243 0.0753 / 0.0039 4.149 / 0.720

GC has a noisy baseline (>5× spread), but decreases in all five pairs: signed mean −0.2388 ms/request (0.2426→0.0038). No adverse GC verdict or A/A-based rejection is being made. Event-loop and request-latency tails were not measured.

Separate traced main-isolate promotion windows:

Pair Minor collections base/head Promoted bytes base/head Promoted bytes/request base/head Traced max pause base/head (ms; context only)
1 11 / 2 13,689,056 / 159,888 42,778 / 500 15.109 / 10.091
2 11 / 2 13,818,064 / 156,864 43,181 / 490 10.863 / 0.567

Promotion decreases ~98.85% in both pairs; no major collections occurred. Traced timing is separate from the untraced GC comparison.

Every pair has identical payload digest 55f633cd462bd991e65ac85967495e605c165fa32a11ee94d114c07a87e84c7b and fingerprint digest d71c77698c08e3cd94a987465b69e853dbdb88a93b8e3118f638315993558fc4.

The original measurement script kept its last inspected message in the module frame: the source-release probe reported 0 base / 1 candidate survivor. A diagnostic located that exact envelope (index 127); moving shape counting into a function, outside sampling and timing, yielded 0/2,048 surviving candidate envelopes in two follow-up runs with unchanged payload/fingerprint digests. The original five performance pairs above are preserved, not silently replaced. The follow-up commit only corrects this benchmark reference lifetime.

node --expose-gc --import ./scripts/tsx.mjs scripts/perf/prompt-cache-observation-measure.ts --envelopes projected --replacements
node --expose-gc --import ./scripts/tsx.mjs scripts/perf/prompt-cache-observation-measure.ts --envelopes projected --replacements --measure allocation --output allocation.heapprofile
node --expose-gc --trace-gc-nvp --import ./scripts/tsx.mjs scripts/perf/prompt-cache-observation-measure.ts --envelopes projected --replacements --measure promotion

The new real-boundary regression fails on the base at wrapper identity and passes on the candidate. It interleaves replacement, image, normalization, and retention policies, checks payload bytes and fingerprint reuse, and preserves mutable/shallow-frozen behavior. The restored TTL test covers non-array replacement content with a frozen source.

Passed focused files (node scripts/run-vitest.mjs … --maxWorkers=1):

  • src/agents/embedded-agent-runner/run/attempt-session-boundary.media.test.ts
  • src/agents/embedded-agent-runner/run/attempt-session-boundary.test.ts
  • src/agents/embedded-agent-runner/tool-result-truncation.cache-ttl.test.ts
  • src/agents/session-transcript-repair.test.ts
  • src/agents/agent-tools.prefix-stability.test.ts
  • packages/agent-core/src/harness/messages.test.ts
  • src/shared/immutable-data.test.ts
  • test/scripts/eager-import-closure.test.ts
  • test/scripts/pr-wrapper-source-closure.test.ts

Also passed: changed-file formatting/lint, pnpm tsgo:core (native default checker), export-name collision check, full Madge import-cycle check (0 cycles after the type-ownership repair), line-cap ratchet, and git diff --check. No Testbox lease was allocated; broad proof is delegated to PR CI under the lane's validation rule.

Review: independent subagent review (autoreview route unavailable), clean after implementation and extraction, plus clean incremental reviews of the benchmark lifetime correction and the CI type-ownership repair. The autoreview preflight rejected the provider/config mismatch; no configuration was changed.

CI repair: the first run passed 72 checks but failed the full import graph guard (and its aggregate gate). The runtime-only cycle check passed; the new checkpoint-to-projector type import created a type-level cycle through projection state. Moving that unchanged type back into the leaf checkpoint contract removes the reverse dependency. This was a PR defect, not an inherited failure; no rerun-for-green was requested.

Final-head CI: 73 checks passed on e76c062a9d41f63388e6df277e9f6c0fc958fcf3, including the repaired architecture guard. The only substantive red is test/scripts/check-deadcode-exports.test.ts:234, “models exact generated and module-hook named consumers”: expected the generated addDoctorLegacyIssues import, received only the other three imports. The PR failure annotation is byte-identical to the newest scheduled main run (2026-10-25 04:35 UTC, 3d020b496ad8d8c4bf0486232d86a55491509db2). The test, dynamic compiler, and Doctor source it reads also match that main revision byte-for-byte. Aggregate CI/security gates are red solely from that inherited test failure. No rerun or further rebase was used to chase green.

Open limits: synthetic owner-path proof only, no production deployment or live-provider traffic, no whole-Gateway latency/promotion claim. Mutable or opaque source graphs intentionally remain uncached. After deploy, look for less fingerprintRecord/mutable-memo allocation beneath beginPromptCacheObservation, stable request bytes/prefixes, and no offsetting retained-heap or promotion growth. This PR is intentionally left open for lead verification and merge.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@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-25T05:23:28.886728Z a35d270 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts agents Agent runtime and tooling size: L labels Oct 25, 2026
@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 25, 2026
@steipete
steipete force-pushed the steipete/perf-stable-projected-wrappers-20261025 branch from a9e35f6 to e76c062 Compare October 25, 2026 04:37
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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 25, 2026
@clawsweeper

clawsweeper Bot commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses immutable request-message projections to reduce repeated fingerprinting and allocation.

Example: Repeated preparation of the supplied 128-message frozen-history fixture.

  • Before: 96 wrappers are recreated per request, with 32 of 128 message fingerprints reused.
  • After: The supplied measurements report no recreated wrappers and reuse of all 128 fingerprints, with identical payload digests.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful and coherent implementation with substantive synthetic owner-path evidence, but no shipped-entry-point proof.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the ordinary contributor proof gate; its Node 26.12.1 benchmark exercises hydration, replay, normalization, conversion, retention, and observation, but supplies no live Gateway/provider execution.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Repeated requests spend avoidable CPU and allocation rebuilding projections of unchanged conversation history.
Reason: The maintainer-directed change demonstrates a substantial owner-path benefit, preserves existing policies, and explicitly accepts its measured cold-path and retention tradeoffs.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it provides a useful, maintainer-directed optimization absent from current main, with no actionable correctness finding.

Priority: P2
Reviewed head: e76c062a9d41f63388e6df277e9f6c0fc958fcf3

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence stops at synthetic production-owner composition and does not show a shipped Gateway request with a real agent and model.
Agent review details

How this fits together

Session history enters request preparation, which applies tool-result replay, message normalization, conversion, image policy, and retention before prompt-cache observation and provider dispatch.

flowchart LR
  A[Session transcript] --> B[Tool result replay]
  B --> C[Boundary normalization]
  C --> D[Conversion and image policy]
  D --> E[Runtime context retention]
  E --> F[Prompt cache observer]
  F --> G[Provider dispatch]
Loading

Technical review

Best possible solution:

Retain the owner-local weak projections and existing mutable-input behavior while completing the requested lead verification.

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

Current-main source rebuilds wrappers around unchanged frozen messages, and the committed benchmark exercises that composition; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The smallest complete fix preserves immutable identity at the existing projection owners, keys policy differences separately, and leaves mutable inputs uncached; no unnecessary parallel algorithm was found.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against a0b170fac1ac.

Provenance checked

  • Tool-result merge, bounded retention, and TTL replay keeps the original intent (improve: bound retained tool-result projection data #139157: Retain projected bytes without pinning complete original messages, while preserving canonical metadata and source-rewrite invalidation; earlier filtered-block and sticky-TTL contracts remain intact.)
  • Canonical tool-result identity keeps the original intent (d13db41: Preserve admitted tool-result bytes across replay, including rewritten identities; memoization retains the same key computation and ambiguous-state scope.)
  • Runtime-context and system-update projection keeps the original intent (fix: prevent internal runtime context from appearing in replies #163471: Preserve producer-owned runtime provenance and shipped replay bytes rather than inferring authority from text; the patch retains those transformations and separates their policy variants.)
  • Runtime-context retention keeps the original intent (06d4475: Apply the same transcript retention policy to local and node execution; frozen carriers now use copy-on-write while mutable carriers keep in-place behavior.)
  • Session conversion and image policy keeps the original intent (cb00966: Share normal-turn and fork reconstruction conversion without eager fork snapshots; the patch retains the shared harness converter and image-policy semantics.)
  • Tool-result detail removal keeps the original intent (cee0906: Exclude opaque details while preserving the synthetic unknown-outcome marker; both rules remain unchanged.)
  • Measurement workload and fingerprint documentation keeps the original intent (perf(agents): compact primitive fingerprint revisions #183137: Measure retained observation costs around real production owners; this PR extends the workload to replacement replay and complete projection preparation.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit c09f136 adds src/shared/model-context-message.ts:6 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c09f1360bbe4; files: src/shared/model-context-message.ts)
  • Vincent Koc: Raw commit 16e1625 adds src/agents/embedded-agent-runner/tool-result-truncation.ts:398 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 16e16255e390; files: src/agents/embedded-agent-runner/tool-result-truncation.ts)
  • Dallin Romney: Raw commit cd9913f adds src/agents/embedded-agent-runner/run/runtime-context-prompt.ts:123 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: cd9913f1b110; files: src/agents/embedded-agent-runner/run/runtime-context-prompt.ts)

PR surface

Source +192, Tests +179, Docs 0, Other +104. Total +475 across 14 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 10 351 159 +192
Tests 2 182 3 +179
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 123 19 +104
Total 14 657 182 +475

Review metrics

Metric Value Why it matters
Production versus tests Production +351/-159, net +192; tests +182/-3, net +179. Growth supports weak identity reuse, policy separation, and copy-on-write retention; the previous merge implementation is removed.
Benchmark option One new benchmark-only flag: --replacements. Exercises owner-recorded truncation replay without adding a runtime user setting.

Labels

Label changes:

  • add P2: A measured request-preparation improvement with limited blast radius and no demonstrated urgent user regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp 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 request-preparation improvement with limited blast radius and no demonstrated urgent user regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Capture one repeated-history request through an isolated Gateway and real model to confirm unchanged provider bytes and reuse in the shipped composition.

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 25, 2026, 1:06 AM ET / 05:06 UTC.

@steipete
steipete merged commit 037ad05 into main Oct 25, 2026
127 checks passed
@steipete
steipete deleted the steipete/perf-stable-projected-wrappers-20261025 branch October 25, 2026 05:30
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
* perf(agents): reuse frozen request projection wrappers

* test(agents): release benchmark inspection references

* fix(agents): keep projection types in the leaf checkpoint contract
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 P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: L 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