Repository navigation
perf(agents): reuse frozen request projection wrappers - #183243
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
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. |
a9e35f6 to
e76c062
Compare
|
Codex review: needs maintainer review before merge. What this changesThis PR reuses immutable request-message projections to reduce repeated fingerprinting and allocation. Example: Repeated preparation of the supplied 128-message frozen-history fixture.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherSession 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]
Technical reviewBest 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
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +192, Tests +179, Docs 0, Other +104. Total +475 across 14 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
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 25, 2026, 1:06 AM ET / 05:06 UTC. |
* perf(agents): reuse frozen request projection wrappers * test(agents): release benchmark inspection references * fix(agents): keep projection types in the leaf checkpoint contract
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.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.
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:
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
55f633cd462bd991e65ac85967495e605c165fa32a11ee94d114c07a87e84c7band fingerprint digestd71c77698c08e3cd94a987465b69e853dbdb88a93b8e3118f638315993558fc4.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.
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.tssrc/agents/embedded-agent-runner/run/attempt-session-boundary.test.tssrc/agents/embedded-agent-runner/tool-result-truncation.cache-ttl.test.tssrc/agents/session-transcript-repair.test.tssrc/agents/agent-tools.prefix-stability.test.tspackages/agent-core/src/harness/messages.test.tssrc/shared/immutable-data.test.tstest/scripts/eager-import-closure.test.tstest/scripts/pr-wrapper-source-closure.test.tsAlso 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, andgit 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 istest/scripts/check-deadcode-exports.test.ts:234, “models exact generated and module-hook named consumers”: expected the generatedaddDoctorLegacyIssuesimport, 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 beneathbeginPromptCacheObservation, stable request bytes/prefixes, and no offsetting retained-heap or promotion growth. This PR is intentionally left open for lead verification and merge.