Repository navigation
perf(sessions): reuse resident strings in initial model context - #182893
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. |
cf527ea to
fdbf946
Compare
|
Codex review: needs maintainer review before merge. What this changesThis PR reuses resident transcript strings when preparing initial model history while preserving independently writable containers. Example: Reopen a retained session containing 8 KiB tool results.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this maintainer-authored PR addresses a distinct allocation boundary, and inspection found no concrete correctness or security defect. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherSessionManager consumes selected transcript history from the existing reader and supplies initial messages to agent-session creation. flowchart LR
A[Transcript reader] --> B[Selected branch]
B --> C[Existing snapshot copier]
D[Resident SessionManager entries] --> C
C --> E[Detached model context]
E --> F[Agent session]
Technical reviewBest possible solution: Retain the existing copier-based implementation if the declared measurements demonstrate a memory benefit without unacceptable context-preparation costs. Do we have a high-confidence way to reproduce the issue? Source confirms the separate initial-context copying boundary, and the author reports a synthetic baseline reproduction; this read-only review did not independently measure V8 string residency. Is this the best way to solve the issue? The patch uses the existing snapshot owner, preserves mutable-container and opaque-graph contracts, and adds no cache or competing selection policy. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against c6afe91b0b85. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +17, Tests +72, Docs +86, Other +597. Total +772 across 9 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 24, 2026, 5:35 PM ET / 21:35 UTC. |
fdbf946 to
ddbd18a
Compare
|
The two typecheck failures on Main has the identical failing diagnostics in check-prod-types and check-test-types-core-2, at The revised retained-memory result qualifies, but latency and promotion remain pending. This attribution does not waive the performance gates or any other unresolved CI result. |
…claw#182893) Reuse equal resident transcript strings while preserving independently writable initial-context containers. Saves 1.814 MiB per run and reduces main-isolate promotion by 30.17% in the calibrated synthetic workload. Initial-context latency rises 0.413 ms within the declared gates. Production LOC grows by 34 to preserve the existing mutation contract. Exact-head CI has only documented inherited type failures matching main; focused tests, relevant sibling checks, security checks, and independent review pass.
What Problem This Solves
Opening a retained session and loading its initial model context retains a second copy of the same transcript strings. A synthetic persisted-session reproduction adds 2.00 MiB per run beyond the SessionManager itself.
Related: #182253.
User Impact
Initial model history can reuse equal transcript strings already retained by the session. Model-context containers remain independently writable, including nested tool arguments and metadata. No configuration, schema, or provider-request changes are intended.
Why This Change Was Made
Persisted initial-context payloads are mutable, so sharing entire payload objects would violate existing SDK isolation. The codec now reuses equal resident strings inside the context reader's already private message containers, then builds initial history. This preserves authoritative fields and property order without an extra container copy. Resident SDK edits, getters and proxies cannot replace selected context values. The admitted cohort still makes one mutable container copy while preserving primitive strings, and stops copying a header it immediately discarded.
Production code grows by 34 lines to preserve the existing mutable-container contract. This adds no retained cache, owner, or invalidation policy. The shared copier's existing immutable-payload default remains unchanged.
Evidence
The final revision qualifies on retention, untraced costs, and separately calibrated traced promotion. Five fresh counterbalanced retained-heap comparisons reduced initial-context overhead from 2.008599 MiB/run to 0.195055 MiB/run, saving 1.813545 MiB/run (90.290% mean paired reduction). Total manager-plus-context retention fell from 5.977062 to 4.162101 MiB/run (−30.365%); manager-only retention was effectively unchanged (3.968463 → 3.967046 MiB). Baseline source:
4b5aba362cafeb4c0f1b01a570633731fb2f0a76; candidate production bytes match the revised PR head.Each cohort retained 20 managers; eight yielded forced collections bracketed each heap reading. All 400 released manager and 200 context weak references reported zero survivors. All ten output hashes, source/load receipts, mutation checks and mutable-container isolation checks matched. Independent and root audits verified all 114 artifacts. There were no guard warnings. Post-release heap drift of 18,640–471,632 bytes is preserved; zero root survivors does not imply that the entire heap returned exactly to baseline. These are forced-GC main-heap retention results, not natural-GC, allocation-churn, or live-service measurements.
The first implementation saved 1.818 MiB/run but was rejected by calibrated latency gates: initial-context means rose 22.893% and 28.747% (+2.940 ms paired mean, +25.820%); p95 rose 18.134%/23.028%, and p99 rose 20.908%/18.991% (2,000 samples per side). Its 12.977% GC/work improvement did not offset those gates. The controller stopped before promotion; no favorable extra was run. The revised implementation removes that additional ordinary-path container copy. Qualified baseline controls are reused only because baseline source, runtime, harness, workload and instrumentation are unchanged; all revised candidate observations are fresh.
The original owner reproduction independently found approximately 2.00 MiB/run of added context and no completed-run registry survivors. The public fixture helper reproduced the canonical synthetic fixture byte-for-byte. An earlier setup failure caused by a disappearing shared dependency was preserved and replaced before samples; subsequent captures use pinned lane-owned copies of the same dependency bytes.
The revised actor seed/read smoke passed exact/window/complete output equality and mutation isolation. Sampled bytes/read were 180,973.712 → 179,356.768 (−0.893%), 1,205,486.160 → 1,223,096.200 (+1.461%), and 1,197,393.504 → 1,199,830.592 (+0.204%), respectively. Each side used 1,000 calls, 32 warmups, and 32,768-byte sampling including collected objects. These are allocation-attribution observations only; the raw profile tree was not persisted. A Dirty admission warning of 2,759,960 kB was retained, followed by a passing guard; no capture was interrupted.
Two fresh CPU-swapped untraced pairs passed ordinary cost thresholds and maximum-pause safeguards. The table reports means of the two baseline/candidate observations; percentages are means of paired relative changes. All latency tails have 2,000 samples per side per pair. Loop tail counts were 3,051/3,092 and 3,034/3,103 (baseline/candidate).
Whole-cycle p99 and initial-context p95 had mixed pair signs, so one predeclared swap-0 extra adjudicated exactly those metrics. Their signed three-pair means were −0.561199 ms versus an adverse threshold of +8.277491 ms, and +0.357861 ms versus +2.995505 ms, respectively. Both qualify. The extra's higher absolute whole-cycle p99 (49.102 → 48.839 ms, n=2,000/side) is retained, not trimmed. Original pairs remain the primary window; the extra is not a new independent window. No admission/watch warnings or diagnostic loss/errors occurred in the revised timing comparisons.
Weak-callback and unknown GC counts were zero. Minor p95 changed −0.544 ms (−11.031%) and p99 −0.832 ms (−14.457%), with the per-side counts above: submillisecond context under v5.3. Major p95 changed −0.352 ms (−3.143%) and p99 +0.192 ms (+1.761%); counts 16 → 13 per pair make both context-only. No normalization by major-cycle count.
Initial-read maxima were 18.760 → 27.029 ms and 20.294 → 21.519 ms (n=2,000/side); loop maxima were 31.556 → 34.701 ms and 34.472 → 32.227 ms (counts above). These are preserved context.
Separately traced promotion qualified after four fresh matched A/A pairs. The first control window had tiny mixed signs (−0.061468%, +0.081976%), so its one declared extra was included: the signed three-pair mean was +1,358.928 B/operation versus the +1,253,127.501 B/operation threshold. The other control window was +0.031861% mean and required no extra. No control triggered an adverse promotion gate.
All four candidate raw trace totals independently match the reported main-isolate promotion. Each side captured 2,000 complete operations; minor counts were 1,317 → 1,324 and 1,318 → 1,324, major counts 16 → 14 in both pairs. Promotion by kind was 12,273,495,792 → 8,588,664,136 minor / 251,172,048 → 157,807,808 major bytes in pair 1, and 12,275,891,544 → 8,584,503,352 minor / 257,712,376 → 166,412,936 major bytes in pair 2. No GC-cycle normalization, capture trimming, forced main-isolate GC, guard warning, or interruption occurred. Maximum traced GC pauses were 21.465 → 18.995 ms and 15.312 → 26.638 ms; these are context only. Larger traced-control maxima, including 90.600 ms, remain in the evidence and are not untraced timing gates. All four sides retain the known post-capture 1+1 survivor diagnostic. Raw worker-isolate events are counted separately; this is not a worker-promotion or live-service claim.
The committed owner benchmark uses the real bounded open and initial-context read. Before candidate cost interpretation, four fresh matched A/A controls precede two CPU-swapped A/B pairs, separately for untraced costs and traced promotion. Each side performs 2,000 complete cycles after synchronized warmup, retains a rotating ring of 20 roots, and uses prepared synthetic state. Forced-GC retention is measured separately in five counterbalanced baseline/candidate samples. All comparisons retain guard outcomes, absolute and relative deltas, tail sample counts, GC kinds, and both maximum pauses. No deployed or whole-Gateway improvement claim.
Focused validation for the revision: 24 codec, 31 model-context snapshot, and 11 prompt-prefix tests passed. The snapshot tests cover writable nested values, frozen resident payloads, changed SDK values and property order, throwing accessors, proxies, and resident cycles. The final ownership-only adjustment moves context construction into the codec operation; all 31 snapshot tests passed again afterward. Changed-file lint has only the existing SessionManager size limit (baseline 706 counted lines, revised candidate 705, limit 700); an intermediate 710-line revision was rejected by the commit ratchet and corrected before commit. Formatting and the export-name collision guard passed. Prior
pnpm tsgo:coreand actor tests passed on the first candidate; the revised head relies on PR CI for broad proof. Review: independent subagent review (autoreview route unavailable), clean after the ownership adjustment. The rebased revision preserves all reviewed production/test/doc bytes. All declared performance stages are complete.The requested import-closure checks ran again on the revision: 19 passed and three wrapper bootstrap cases failed because this local install has
@openclaw/fs-safe0.26.11 while the unchanged trust anchor requires 0.26.13. Both actual import-inventory checks andpr-wrapper-source-closure.test.tspassed. This is a local dependency setup gap; the test and wrapper source are unchanged by this PR. Exact-head PR CI completed using its lockfile installation; the local bootstrap gap remains recorded.The final head
ddbd18a15b7f8c5f379ca6d45a03440a91892c15completed CI run 40149748949. Its inherited failures and relevant sibling proof are detailed below. An earlier CI attempt caught two benchmark type declarations; both were repaired and the script typecheck passed, with production bytes unchanged.The untraced controls qualified after four matched A/A pairs and the two predeclared extra-pair adjudications for their original windows. All admission/watch Dirty warnings are retained, with no guard interruption. Every control and candidate cost process reported one manager/context survivor after capture; this remains an unresolved benchmark-frame lifetime diagnostic, not zero-survivor evidence. Captured costs stopped before teardown, and the separate retained-memory cohorts released all roots.
The revised head has two inherited typecheck failures: TS2739 in unchanged
src/gateway/server-methods/session-catalog.test-helpers.ts:122. Main reports identical diagnostics in production types and Gateway test types. The helper, type chain, failing configs and lockfile are identical on main, base and head; the actual PR CI merge tree equals the PR head tree. No CI rerun or unrelated source repair was made. The completed run has no other failed jobs except the aggregate gate reporting those two errors. All other selected checks passed or were intentionally skipped. The performance gates qualify.Exact-head CI logs explicitly verify 34 relevant sibling files across six successful jobs, including model-context, hydration, actor replica/residency, bounded/branching, worker context reads, and Gateway boundary E2Es. The codec has separate direct local proof; this bounded log audit does not claim every sibling file ran.