Skip to content

perf(sessions): reuse resident strings in initial model context - #182893

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-session-context-residency-20261024
Oct 25, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-session-context-residency-20261024

Conversation

@steipete

@steipete steipete commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

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.

Pair Baseline added bytes/run Candidate added bytes/run Signed delta Relative delta
1 2,097,933.2 198,895.6 -1,899,037.6 -90.519%
2 2,110,492.0 223,185.2 -1,887,306.8 -89.425%
3 2,100,897.6 191,232.4 -1,909,665.2 -90.898%
4 2,120,749.6 212,571.6 -1,908,178.0 -89.977%
5 2,100,772.8 196,764.0 -1,904,008.8 -90.634%

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

Metric Baseline Candidate Signed mean delta Mean paired delta
GC ms/operation 1.784572 1.547319 -0.237253 -13.289%
Whole-cycle mean ms 29.902031 30.514828 +0.612797 +2.053%
Whole-cycle p95 ms (n=2,000/side) 33.319672 34.123715 +0.804043 +2.414%
Whole-cycle p99 ms (n=2,000/side; adjudicated below) 37.530267 36.819880 -0.710387 -1.855%
Initial-context mean ms 11.621078 12.033793 +0.412715 +3.569%
Initial-context p95 ms (n=2,000/side; adjudicated below) 14.466722 14.569597 +0.102875 +0.744%
Initial-context p99 ms (n=2,000/side) 16.254006 16.617718 +0.363712 +2.270%
Loop p99 ms (counts above) 24.035327 24.354815 +0.319488 +1.347%
Process CPU ms/operation (context) 58.014128 60.273924 +2.259796 +3.898%

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.

GC kind Collection counts, pairs 1 / 2 (baseline → candidate) Mean total ms per 2,000 operations Signed delta Mean paired delta
Minor 1,320 → 1,324 / 1,319 → 1,325 3406.739 → 2965.410 -441.330 ms -12.949%
Major 16 → 13 / 16 → 13 146.591 → 116.423 -30.169 ms -20.577%
Incremental 16 → 13 / 16 → 13 15.813 → 12.805 -3.007 ms -19.136%

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.

Pair Baseline maximum GC ms Candidate maximum GC ms Signed delta Safeguard threshold ms
1 12.017 15.347 +3.330 50.000
2 11.315 11.940 +0.625 50.000
Declared extra 40.959 15.071 −25.888 81.918

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.

Traced pair Baseline promoted B/operation Candidate promoted B/operation Signed delta Relative delta
1 6,262,333.920 4,373,235.972 −1,889,097.948 −30.166037%
2 6,266,801.960 4,375,458.144 −1,891,343.816 −30.180367%
Mean 6,264,567.940 4,374,347.058 −1,890,220.882 −30.173202%

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:core and 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-safe 0.26.11 while the unchanged trust anchor requires 0.26.13. Both actual import-inventory checks and pr-wrapper-source-closure.test.ts passed. 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 ddbd18a15b7f8c5f379ca6d45a03440a91892c15 completed 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.

@clawsweeper

clawsweeper Bot commented Oct 24, 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.

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

chatgpt-codex-connector Bot commented Oct 24, 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-25T01:15:07.960841Z ddbd18a 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 24, 2026
@steipete
steipete force-pushed the steipete/perf-session-context-residency-20261024 branch from cf527ea to fdbf946 Compare October 24, 2026 21:20
@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. 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 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

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

  • Before: Initial model context retains separately copied transcript strings.
  • After: Equal resident strings can be reused while edits to model-context objects remain isolated.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused implementation and reported owner tests support correctness; the claimed performance benefit remains unqualified.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor-proof gate is waived for this maintainer-authored PR; functional owner tests are reported passing, but the committed bounded-open benchmark has no completed candidate residency, latency, CPU, GC, or promotion results in the body or discussion.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Opening retained sessions can keep another copy of large transcript strings in initial model history.
Reason: The maintainer-authored direction targets measured redundant storage while preserving existing behavior and avoiding new configuration or state ownership.

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
Reviewed head: fdbf9468a6dcebb58f1582139b9dbe8a8384c9dd

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Completed matched baseline/head initial-context residency and cost results are not yet supplied.
Agent review details

How this fits together

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

Technical review

Best 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

  • Model-context projection keeps the original intent (7d518df: Project storage-only metadata before cloning while retaining nested mutation isolation.)
  • Transcript snapshot copier keeps the original intent (fed5b24: Reuse transcript strings while detaching mutable containers and preserving opaque SDK graph identity.)
  • Immutable-payload sharing keeps the original intent (7c084ff: Consume existing ownership facts instead of repeatedly inspecting and freezing internal transcript payloads.)
  • Prepared initial-context reuse keeps the original intent (1efc0b4: Reuse an accepted context while existing write receipts, manager identity, and live writer checks remain valid.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 1efc0b4 adds src/agents/sessions/session-manager.ts:158 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1efc0b40276e; files: src/agents/sessions/session-manager.ts)
  • Josh Avant: Raw commit 7d518df adds src/agents/sessions/session-manager-codec.ts:143 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7d518df910c8; files: src/agents/sessions/session-manager-codec.ts)

PR surface

Source +17, Tests +72, Docs +86, Other +597. Total +772 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 31 14 +17
Tests 2 82 10 +72
Docs 2 86 0 +86
Config 0 0 0 0
Generated 0 0 0 0
Other 2 597 0 +597
Total 9 796 24 +772

Review metrics

Metric Value Why it matters
Production versus test growth Runtime production +17 lines net; tests +72 lines net. Production growth extends the existing copier rather than adding another owner; tests cover writable frozen descendants, authoritative ordering, accessor avoidance, and stored-view isolation.

Labels

Label changes:

  • add P2: This targets avoidable retained-session memory use without evidence of an urgent user-facing outage.
  • 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: This targets avoidable retained-session memory use without evidence of an urgent user-facing outage.
  • 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.

  • Complete the declared matched baseline/candidate measurements and assess them against the existing acceptance criteria.

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 24, 2026, 5:35 PM ET / 21:35 UTC.

@steipete
steipete force-pushed the steipete/perf-session-context-residency-20261024 branch from fdbf946 to ddbd18a Compare October 25, 2026 01:12
@steipete

Copy link
Copy Markdown
Contributor Author

The two typecheck failures on ddbd18a15b7f8c5f379ca6d45a03440a91892c15 are inherited. Both report TS2739 at src/gateway/server-methods/session-catalog.test-helpers.ts:122, where {} lacks minProtocol, maxProtocol, and client.

Main has the identical failing diagnostics in check-prod-types and check-test-types-core-2, at f0dcb354e45b06d60df466de136f85cd1b7b148e. The helper, complete connection-type chain, both failing configs, and lockfile are byte-identical on that main revision, this PR's base, and its head. The PR CI merge 7881e7e20f20b40ef9fa3d800161c144ba83311e has the exact same tree as the PR head. Each failed job log was retrieved once; no CI rerun or unrelated source repair was made.

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.

@steipete
steipete merged commit 3e342f3 into main Oct 25, 2026
158 of 164 checks passed
@steipete
steipete deleted the steipete/perf-session-context-residency-20261024 branch October 25, 2026 02:21
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
…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.
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