Skip to content

improve: reduce allocation when preparing long conversations - #200888

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-session-manager-context-freeze-20260919
Nov 18, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-session-manager-context-freeze-20260919

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Preparing an agent session from a long conversation clones mutable model-context data, then validates all of those newly created containers again before freezing them. That repeated inspection allocates unnecessary keys and descriptors during attempt preparation and compaction.

User Impact

Long conversations require less allocation and CPU during initial-context preparation. Prompt bytes, writable SDK views, stored snapshot sharing, and opaque SDK values retain their existing behavior. No configuration or migration is required.

Why This Change Was Made

The transcript copier already knows which containers it creates. It now optionally freezes its output, using trusted freezing only when its existing traversal established the plain-data guarantee. Maps, Sets, symbol members, and native structured-clone fallbacks retain inspected freezing. A blanket trusted-freezer substitution would be unsafe for those SDK inputs.

Existing frozen-payload sharing and revision-bound prepared-context reuse remain the owners of those optimizations. Runtime delta is +21 lines to preserve the opaque-value contract; there is no new cache or session-row projection change.

Evidence

Five counterbalanced A1/A2/B process groups on Node 26.12.1/macOS arm64, each with 20 warmups and 100 measured operations. A1 and A2 use the same parent copier/codec. Synthetic workload: 4,000 entries, 1,000 user/tool-call/tool-result/answer turns, 2 KiB tool output, 3,171,895 serialized input bytes. Acceptance was fixed before measurement: B must beat both controls on allocation and CPU, preserve context bytes, and avoid a material latency regression.

Per operation, median across processes A1 A2 B
Construction + initial context allocation, MB 38.2274 38.2322 23.7080
Construction + initial context CPU, ms 30.2312 31.1711 28.4604
Mutable owner allocation, MB 30.4333 30.4234 15.9188
Mutable owner CPU, ms 22.4081 22.5343 19.5968
Frozen owner allocation, MB 5.6160 5.6169 4.1845
Frozen owner CPU, ms 3.7429 3.6921 3.4247

Construction wall median/p95: A1 29.719/36.586 ms, A2 30.327/37.498 ms, B 28.073/35.405 ms. Mutable owner median/p95: 21.351/29.054, 21.924/28.027, 19.256/27.374 ms. Frozen owner median/p95: 3.569/4.361, 3.569/4.504, 3.316/4.325 ms. Host one-minute load ranged 4.61–6.66. Allocation uses exact cumulative V8 counters, including later-collected objects; CPU uses thread CPU counters. CPU profiles confirm the removed validating traversal at this call site. Profiled timings are excluded from the table.

Every measured model-context hash matches across all arms. The 20 MB mutable-owner regression budget fails on the parent at 30.19 MB/operation and passes with this change. The SDK construction measurement includes fromEntries import cloning; owner measurements separately cover mutable and deeply frozen branches. These are owner measurements, not whole-Gateway throughput or production deployment claims.

Reproduce with node --import ./scripts/tsx.mjs scripts/perf/session-manager-context-freeze-measure.ts --output <json>. For A, save the parent's session-manager-codec.ts and transcript-snapshot.ts, then pass --codec-file <file> --snapshot-file <file>. Add --max-owner-bytes 20000000 for the allocation regression check.

Validation: 94 focused tests passed across codec, transcript snapshot, stored-context isolation, retained data, and prompt-prefix stability. New SDK coverage exercises mutable nested arguments, Maps/Sets, typed arrays, symbol members, and frozen payload identity. Codec test file: 30 tests; initial full invocation 43.73 s including compilation and the snapshot shard. Consumer invocation: 62 tests, 135.46 s including compilation. CI timing pending.

Independent local Codex autoreview of the parent-to-working-tree change and full ownership sources is scoped-clean through P2, with no actionable findings. Production and full-tree unused-file scans pass. Browser output-fidelity E2E: 4 passed; Chromium tool-card tests: 3 passed. The first component run could not launch because the pinned headless shell was absent; installing that exact Playwright shell resolved setup, and all component tests then passed. All selected pnpm check:changed stages now have passing proof: the full invocation found one benchmark-only unique-symbol typing error; the module-namespace fix passed the exact failed scripts typecheck and reran the allocation budget successfully. Every other stage passed in that invocation, including all core/test typechecks, lint, format, export scans and runtime guards. No inherited-main failure is being claimed.

Let the transcript copier certify its plain output before trusted freezing. Preserve inspected freezing for opaque and symbol-bearing SDK data, mutable detachment, and frozen payload sharing. Synthetic A/A/B construction proof reduces allocation by 38 percent with lower CPU and identical context bytes.
@clawsweeper

clawsweeper Bot commented Nov 18, 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.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: M labels Nov 18, 2026
@steipete
steipete marked this pull request as ready for review November 18, 2026 01:00
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T01:02:33.976704Z 9dc9368 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature 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:feature Preliminary submission classification; full source review pending. labels Nov 18, 2026
@clawsweeper

clawsweeper Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR lets the transcript copier freeze verified plain output without repeating generic validation.

Example: Prepare initial context for the supplied synthetic 4,000-entry conversation.

  • Before: The reported construction benchmark allocates 38.23 MB per operation.
  • After: The reported benchmark allocates 23.71 MB per operation with matching model-context bytes.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused implementation with useful owner-level measurements and compatibility coverage; evidence remains synthetic and was not independently executed.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored internal optimization preserves user-visible behavior; the supplied benchmark exercises real SessionManager construction and context preparation in process, without establishing whole-Gateway performance.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Preparing long conversations spends allocation and CPU re-inspecting containers the copier just created.
Reason: The maintainer-authored direction is established, the reported owner measurements improve, and the narrow change preserves existing output and mutation contracts.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR makes a focused, useful performance improvement that current main does not contain, with no actionable correctness or security findings.

Priority: P2
Reviewed head: 9dc93681ce9ab81d93ee9f69233390a3e573b3dd

Before merge

None.

Findings

None.

Agent review details

How this fits together

SessionManager projects transcript entries into model context; the transcript copier detaches mutable containers, shares immutable payloads, and publishes frozen internal context.

flowchart TD
  A[SessionManager history] --> B[Model context projection]
  B --> C[Transcript copier]
  C --> D[Verified plain output]
  C --> E[Opaque or symbol output]
  D --> F[Trusted freezing]
  E --> G[Inspected freezing]
  F --> H[Initial model context]
  G --> H
Loading

Technical review

Best possible solution:

Keep the optimization in the existing copier while retaining inspected freezing for opaque and symbol-bearing SDK graphs.

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

Source confirms the redundant generic inspection after cloning; the supplied benchmark reports a failing parent allocation budget, but no code was executed during this read-only review.

Is this the best way to solve the issue?

The copier already owns container construction, so recording its plain-data guarantee removes redundant work without another cache, wrapper, or publication owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Internal model-context publication keeps the original intent (245cbaf: Share immutable internal transcript payloads while detaching writable SDK views at their owning boundaries.)
  • Transcript container copying and opaque fallback keeps the original intent (fed5b24: Avoid copying retained payload strings while preserving independent mutable containers and cross-object aliases for opaque SDK graphs.)
  • Frozen-payload sharing keeps the original intent (3e342f3: Preserve the copier's immutable-payload default while keeping mutable model-context containers isolated.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit fed5b24 adds src/agents/sessions/session-manager-snapshot.ts:7 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: fed5b242dddf; files: src/agents/sessions/session-manager-snapshot.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: medium; commits: 7d518df910c8; files: src/agents/sessions/session-manager-codec.ts)
  • RoboClaw: Raw commit 472cd0a adds src/agents/sessions/session-manager-codec.ts:283 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 472cd0a2f542; files: src/agents/sessions/session-manager-codec.ts)

PR surface

Source +21, Tests +58, Other +156. Total +235 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 26 5 +21
Tests 1 58 0 +58
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 156 0 +156
Total 4 240 5 +235

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P2: Reduces measured allocation and CPU during long-conversation preparation without changing product contracts.
  • 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: Reduces measured allocation and CPU during long-conversation preparation without changing product contracts.
  • 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.

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 November 17, 2026, 8:16 PM ET / November 18, 2026, 01:16 UTC.

@steipete
steipete merged commit c72ba50 into main Nov 18, 2026
220 of 223 checks passed
@steipete
steipete deleted the steipete/perf-micro-session-manager-context-freeze-20260919 branch November 18, 2026 01:28
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…0888)

Let the transcript copier certify its plain output before trusted freezing. Preserve inspected freezing for opaque and symbol-bearing SDK data, mutable detachment, and frozen payload sharing. Synthetic A/A/B construction proof reduces allocation by 38 percent with lower CPU and identical context bytes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: M 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