Repository navigation
improve(sessions): avoid copying transcript history for internal readers - #195961
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 Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 38193d1cad
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| >; | ||
|
|
||
| function detachReplayHookContext<T extends { messages: AgentMessage[] }>(context: T): T { | ||
| context.messages = cloneTranscriptView(context.messages, { shareImmutablePayloads: false }); |
There was a problem hiding this comment.
Preserve replay metadata when detaching hook messages
For sessions with explicitly retained reset history, a configured history limit, and a provider replay hook (including ClawRouter's no-op hook), this copy silently removes retained context. cloneTranscriptView copies only Object.keys, dropping the Symbol.for("openclaw.sessionHistoryPrelude") marker installed by iterateSessionContextMessages. In the normal attempt flow, sanitation runs before limitHistoryTurns, so the latter now counts those retained messages as ordinary turns and can evict them. Preserve symbol metadata when producing writable hook copies; cloning a marked prelude followed by three user turns and applying a limit of one demonstrably drops the prelude, whereas the original messages retain it.
AGENTS.md reference: AGENTS.md:L22-L22
Useful? React with 👍 / 👎.
|
Codex review: needs changes before merge. What this changesThis PR shares immutable transcript snapshots among internal readers while preserving writable public SessionManager and plugin-hook views. Example: Four internal readers consume a synthetic 15,000-event transcript.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 2 items remain Keep this PR open: the maintainer-directed allocation reduction has value, but hook copies lose retained-history metadata and the internal-reader cutover breaks replay test fixtures. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherTranscript hydration loads session history from the storage owner, actor replicas retain selected snapshots, and SessionManager prepares history for agent replay and writable SDK consumers. flowchart TD
A[Session storage] --> B[Transcript hydration]
B --> C[Immutable snapshot]
C --> D[Actor replica]
C --> E[SessionManager]
E --> F[Internal model history]
E --> G[Writable SDK views]
F --> H[Writable provider hooks]
Technical reviewBest possible solution: Keep immutable sharing at the existing hydration owner, preserve replay metadata when detaching hook messages, and migrate the shared replay fixtures to the internal reader. Do we have a high-confidence way to reproduce the issue? Source shows repeated deep copies on main and the introduced metadata-loss path; supplied benchmarks quantify the former, and exact-head CI annotations corroborate the fixture failures without a local test run. Is this the best way to solve the issue? Sharing immutable history through the existing hydration and actor owners is appropriate, provided writable detachment preserves replay semantics and every affected test consumer adopts the internal reader. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against ba557d2b2640. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceAcceptance criteria:
What I checked:
Likely related people:
PR surfaceSource +274, Tests +181, Docs +12, Other +71. Total +538 across 39 files. Added test files: 0. View PR surface stats
Preflight sourceSource 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
LabelsLabel changes:
Label justifications:
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 November 9, 2026, 7:46 AM ET / 12:46 UTC. |
Detach registered context-engine message inputs at their public owner boundary. Keep projection prefixes immutable until SDK exposure, use copy-on-write for rewrite anchors, and remove prefix ownership bookkeeping. Update replay fixtures for internal readers and preserve mutation regressions under the test-file cap.
|
Landing note (maintainer review): on Team r301 a 30 s sampling heap profile attributed 74.6 MB of 333.6 MB sampled allocation (22.4%) to |
#196023) Preserve own symbol-keyed data descriptors in transcript clones so explicit reset-retained history survives provider sanitization and turn validation before history limiting. Keep the string-key copier and immutable sharing fast path unchanged. Fixes the regression introduced by #195961. Tests cover all three replay hook routes and symbol descriptor, alias, cycle, and detached-value contracts. Allocate exactly 108 regression-test lines.
…ers (openclaw#195961) * perf(sessions): share immutable transcript hydration views * fix(sessions): preserve writable plugin history boundaries Detach registered context-engine message inputs at their public owner boundary. Keep projection prefixes immutable until SDK exposure, use copy-on-write for rewrite anchors, and remove prefix ownership bookkeeping. Update replay fixtures for internal readers and preserve mutation regressions under the test-file cap.
openclaw#196023) Preserve own symbol-keyed data descriptors in transcript clones so explicit reset-retained history survives provider sanitization and turn validation before history limiting. Keep the string-key copier and immutable sharing fast path unchanged. Fixes the regression introduced by openclaw#195961. Tests cover all three replay hook routes and symbol descriptor, alias, cycle, and detached-value contracts. Allocate exactly 108 regression-test lines.
Qualify the beta.4 equivalent of #199840 (canonical commit 675297f). Beta.4 delegates getBranch directly to SessionEntryNavigation and does not have the writable-copy boundary introduced by main-only #195961. Assert payload identity across repeated manual-preparation branch reads. Hydration creates private mutable containers once, so main's owned-payload brand assertion does not apply; no product ownership change is needed. Focused manual compaction regression, formatting and lint pass. Co-authored-by: RomneyDa <[email protected]>
What Problem This Solves
Repeated session-history hydration and actor reads allocate deep copies of the same transcript containers for each internal reader.
User Impact
Lower allocation and CPU during internal transcript reads. Public SessionManager views and writable plugin hooks keep their mutation behavior. No configuration, schema, stored-byte, or migration changes are required.
Why This Change Was Made
The hydration owner freezes decoded transcript snapshots once. Actor seeds, exact retained reads, and readers joining one in-flight load share that immutable view. Derived bounded selections own their navigation containers while retaining the same event payloads. Cohort/model-context preparation uses internal readers and shares frozen messages instead of immediately materializing public writable views.
Writable copies stay at their owners: selected SessionManager getter slices, extension context hooks, provider replay hooks, and registered plugin context engines. Provider replay hooks preserve in-place edits on nullish returns without skipping the built-in validators. Legacy migration, branch/suffix edits, rewrite/rollback, and fresh reload string replacement retain their own mutation boundaries.
The public contracts are
SessionManagerandExtensionRunnerexported byopenclaw/plugin-sdk/agent-sessions, the session hydration documentation, and the provider replay hooks. Context hooks explicitly allow message modification inextensions/types.ts; provider replay contexts expose writableAgentMessage[]in the Plugin SDK. Registered context engines also receive writablemessage/messagesunder the ContextEngine SDK contract, now detached at the registry invocation boundary using trusted registration ownership.Evidence
Synthetic exact actor seed plus four reads, comparing parent
832bbf926fc55ec102bde3fb1a1b5e4341b848b6with this change. Node 26.12.1/V8 14.6, macOS arm64; 2k/15k events with 512-byte text; five counterbalanced process pairs for each size/input/measurement, 80 accepted processes. Allocation sampling includes collected objects and runs separately from untraced timing.Fresh mode includes transport materialization and producer freezing in every measured operation: 15k allocation drops 83.9%, CPU 77.3%. Its median per-process p95 drops 218.609 → 55.907 ms; GC time drops 13.648 → 5.148 ms/group. Matching-runtime A/A paired allocation shifts were +0.54%/+0.69%, CPU −0.50%/+1.20%, and wall −0.21%/+0.25%. All output hashes match; the candidate rejects all six nested payload, array, and Map mutations.
This measures the actor owner, not SQLite/worker I/O, asynchronous contention, residency limits, public SDK materialization, or end-to-end Gateway latency. Public hook copies and genuinely fresh reload string-replacement copies remain. Integrated cohort tests separately verify shared payload identities so internal model preparation does not relocate the deep copy.
Validation includes six ownership regressions failing on the exact parent; 315 focused manager/actor cases across the expanded run and targeted corrections; 99 provider/replay cases; import/prompt-prefix tests; Chromium history, 18 boot-boundary E2E cases, and the real-Gateway initial-setup E2E. The initial Codex review found no actionable P0–P2 defects. The final committed branch also passed Codex autoreview with
--max-priority P1(scoped-clean, no actionable P0/P1 findings). The runtime and matching UI assets were built for the real-Gateway proof.Final bounded broad Node proof: 11,017 passed / 1 failed / 8 skipped across 863 unique completed files, with zero emitted read-only/nonextensible/TypeError diagnostics. Eight broad owner plans completed; the plugin selection completed after a reporter setup recovery. Infra/runtime-config were stopped at a reasonable-time cutoff, then 96 previously uncompleted transcript/actor/hydration/model-context/history/manager files passed (610 cases). Sixty infra and 199 runtime-config files remain unexecuted: this is a scoped equivalent, not a full four-directory-suite green. Node 24.22.1 / V8 13.6.233.17-node.58; all 21 production files in the tested snapshot match the final pushed head.
The single final-source failure is the SQLite UTF-16 exclusion assertion. It reproduces on the exact main parent 832bbf9 using the same supported Node runtime. The expectation originated in 93450a667d2a / #138470; later consolidations only moved it. This newly discovered inherited main test regression needs follow-up. No maintenance code was changed.
The initial literal four-directory request was separately interrupted after 20 minutes on the repository-default Bun runtime (7,314 completed passing outcomes, four failures). Three failures were stale replay mocks missing the new internal reader symbol; those fixtures are corrected and affected cases pass. The CLI child-JSON EOF failure passed one same-runtime replay, but its original cause remains unclassified. Those incomplete/overlapping outcomes are not added to final Node totals.
The mutation-safety follow-up found and fixed a missed writable boundary for registered plugin context engines. Two strict-Node regressions fail against the previous revision; the complete context-engine scope passes 144 tests / 3 skipped after the fix. Both process/fallback and logical-turn invocation modes are covered, including a plugin that claims the display ID
legacy. Core registration retains shared payload identities. The prefix simplification exposed an anchor-array write in an existing regression; replacing that prefix container fixes it, and the complete cache-TTL suite passes 44/44.pnpm check:changedcompleted in the installed checkout. All task-owned type, lint, format, file-cap, ownership/import/schema/database checks passed. Two unrelated main failures reproduce on a clean worktree at the exact parent: the changelog attribution guard after 266a7aa0fe69 / #194364, and five unused Usage UI exports introduced by 0eb84f967507. These are inherited failures on the pinned parent, not ignored noise. During this task, #194461 added production consumers for the five Usage exports on newer main; that newer main was not fully rechecked here. The unchanged changelog guard still needs follow-up.Reproduction and change size
Use the same benchmark script in isolated parent/candidate worktrees:
Repeat with
--allocationsin separate processes,--input-mode reused, and 2k events/30 operations. Compare five alternating pairs; use the same Node version for controls and both arms.Production delta: +429/−182, net +247 LOC (27 fewer production lines than the first PR revision). The growth preserves writable public boundaries and tracks which private hydrated envelopes still need detachment. Frozen-value heuristics break existing immutable append aliases; the per-view ownership Set preserves those aliases through graph-cloned rewrites/rollback without an O(N) lookup per getter. It is consumed at writable exposure and cleared on view transitions, not a result cache. Omitted projection prefixes no longer enroll in that Set: their public getter detaches once, and rewrite anchor edits replace only the affected container. Prefix cleanup plumbing and an unused retention helper were removed. Existing indexing/container helpers move to the codec to keep class line limits intact. Regression tests add 282 net budgeted lines with an exact scoped allocation; the shared test ceiling is unchanged.
Prepared for review; intentionally not merged.