Skip to content

improve(sessions): reduce stalls when reloading long chats - #202136

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-transcript-hydration-clone-20260919
Nov 20, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-transcript-hydration-clone-20260919

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Reloading long chats unnecessarily copies unchanged tool-result messages on the Gateway main thread. The string-sharing path thaws immutable hydration payloads, so model-context publication must copy and freeze them again.

User Impact

Less CPU, allocation, and synchronous blocking while reloading large histories. Stored transcripts, model context, history bytes, and writable Plugin SDK views retain their existing behavior. No configuration or migration is required.

Why This Change Was Made

The existing codec now reuses an equal resident message when both payloads carry the transcript owner's immutable admission. Equality includes property order to preserve serialized bytes. Entry envelopes remain private, and the existing per-entry ownership path detaches nested payloads before SDK exposure. Changed messages and mutable resident views retain the existing string-sharing path.

Production delta is +31 lines: the ordered comparison and ownership checks avoid the redundant copies without giving up physical string sharing. No new cache, state owner, or API is introduced. Rewrite/rollback and mutable SDK copies remain because their callers hold independent writable references.

Evidence

The regression fails on base abd4b4fc6a828 and passes with the fix. Equal, changed, reordered, and mutable resident payloads preserve serialized bytes and mutation isolation after publication. The real asynchronous SQLite reload test also verifies physical string sharing, rewrite correctness, and nested SDK mutation isolation. 105 distinct focused tests passed, including model-context snapshots and prompt-prefix stability.

Receiver-owner benchmark: 5,000 entries, 16 KiB tool results plus nested metadata; fresh structured-cloned reply each operation; two warmups and ten measured operations per process; five counterbalanced A/A and A/B pairs. Allocation was sampled separately, including collected objects. All 400 measured operations had identical history/model-context hashes.

Median across five processes Base Candidate Change
Main-thread CPU / operation 78.79 ms 48.90 ms −37.94%
p50 synchronous task 77.72 ms 45.20 ms −41.84%
p95 / max synchronous task per process 82.55 ms 60.31 ms −26.94%
Sampled allocation / operation 62.71 MiB 31.53 MiB −49.72%

A/A CPU: 77.41 / 78.57 ms; allocation: 62.99 / 62.82 MiB. Baseline CPU range 74.19–79.45 ms; candidate 47.90–50.94 ms. Maximum-task ranges 80.12–84.90 ms versus 58.35–63.67 ms. Host load is recorded per sample. This measures freeze, reload adoption, and initial-context publication; it excludes SQL, worker transport, and workspace discovery and makes no whole-Gateway stall claim.

Reproduce with node --expose-gc --import ./scripts/tsx.mjs scripts/perf/transcript-hydration-clone-measure.ts --output /isolated/result.json; use --owner-file /isolated/base-codec.ts for the base and --allocation in separate processes.

Independent Codex autoreview: complete local diff against the base above, P0/P1, scoped-clean, no findings. Codec suite: 34 tests, 12.12 s wall; hydration suite: 21 tests, 40.51 s wall; remaining 50 focused tests cover snapshots and prompt stability. Existing subprocess/SQLite fixtures account for most runtime; the change adds no new boot fixture. No browser-runtime module or visual behavior changed.

pnpm check:changed completed all selected checks. It initially reported two proof-only type errors (test-message narrowing and a benchmark unique-symbol import); both were corrected and their affected typechecks now pass. Production types, scoped lint/format, zero unused exports, database/schema boundaries, and import-cycle guards passed. The final four-case regression and benchmark smoke also pass. Final Codex P1 review of the corrected diff is scoped-clean.

Keep equal owner-sealed messages shared through reload and model-context publication. Preserve serialized property order, physical string reuse, and per-entry detachment before writable SDK exposure. Add aliasing regression coverage and a 5000-entry receiver-owner benchmark.
@clawsweeper

clawsweeper Bot commented Nov 20, 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 20, 2026
@steipete
steipete marked this pull request as ready for review November 20, 2026 00:04
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 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-20T00:06:54.906653Z 52e16dc 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:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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. labels Nov 20, 2026
@clawsweeper

clawsweeper Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses equal immutable transcript messages during reload while preserving serialized bytes and writable SDK isolation.

Example: Reload a chat containing an unchanged read tool result with 16 KiB of text.

  • Before: Reload adoption clones the immutable message, and model-context publication copies and freezes it again.
  • After: Reload adoption shares the equal sealed resident message; public SDK access still receives detached writable data.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The patch is focused and source-consistent, with useful owner measurements and regression coverage, but the required product-path evidence remains incomplete.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Reloading long chats performs avoidable synchronous copying on the Gateway thread.
Reason: The maintainer-authored direction removes measured redundant work without changing configuration, persistence, public APIs, or writable SDK behavior.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR removes redundant reload copying still present on main, and source review found no introduced correctness or security defect.

Priority: P2
Reviewed head: 52e16dc5f11fc64e9a17258733605becdfeb258c

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Provide redacted logs or terminal output from an isolated Gateway with a real agent reloading a representative long tool-result history through the changed path, showing the after-fix result.
Agent review details

How this fits together

SQLite hydration supplies immutable transcript snapshots to SessionManager, which publishes model context and detaches selected entries for writable SDK access.

flowchart TD
  A[SQLite transcript] --> B[History worker]
  B --> C[Immutable snapshot]
  C --> D[SessionManager reload codec]
  E[Resident sealed messages] --> D
  D --> F[Immutable model context]
  D --> G[Detached writable SDK views]
Loading

Technical review

Best possible solution:

Keep the focused codec optimization with ordered equality, existing immutable admission, and existing SDK detachment.

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

Current main clones frozen incoming messages during resident-string reuse and then clones mutable data during context publication; the body reports a base-failing regression, but no code was executed during this read-only review.

Is this the best way to solve the issue?

This is a small repair at the existing shared owner: ordered equality preserves bytes, immutable admission permits sharing, and changed or mutable payloads retain the established path.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Resident reload payload reuse changes intended behavior with a stated reason (775e4d5: Reduce retained duplicate transcript strings while keeping mutable message containers private.)
  • Immutable hydration and SDK mutation isolation keeps the original intent (245cbaf: Share immutable internal transcript payloads and detach selected entries at writable public boundaries.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 775e4d5 adds src/agents/sessions/session-manager-codec.ts:163 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 775e4d51cf8d; files: src/agents/sessions/session-manager-codec.ts)
  • Vincent Koc: Raw commit 9bf980e adds src/agents/sessions/session-manager-codec.ts:44 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 9bf980ed4a1b; files: src/agents/sessions/session-manager-codec.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)

PR surface

Source +31, Tests +52, Other +155. Total +238 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 33 2 +31
Tests 2 52 0 +52
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 155 0 +155
Total 4 240 2 +238

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.

Review metrics

Metric Value Why it matters
Production versus regression coverage Runtime +33/-2; tests +52/-0 Runtime growth implements ordered equality and immutable admission checks without a new owner; coverage protects distinct equality and mutation boundaries.

Labels

Label changes:

  • add P2: This is a bounded performance improvement for long-chat reloads without evidence of an urgent outage caused by this specific copying path.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish 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 is a bounded performance improvement for long-chat reloads without evidence of an urgent outage caused by this specific copying path.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish 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 19, 2026, 7:21 PM ET / November 20, 2026, 00:21 UTC.

@steipete
steipete merged commit b783fa1 into main Nov 20, 2026
201 of 203 checks passed
@steipete
steipete deleted the steipete/perf-micro-transcript-hydration-clone-20260919 branch November 20, 2026 00:26
@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 20, 2026
…202136)

Keep equal owner-sealed messages shared through reload and model-context publication. Preserve serialized property order, physical string reuse, and per-entry detachment before writable SDK exposure. Add aliasing regression coverage and a 5000-entry receiver-owner benchmark.
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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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