Repository navigation
fix(sessions): release discarded tool output backing strings - #164361
Conversation
Detach transcript string storage once while retaining shared immutable message graphs. Refresh prepared redaction facts to carry the owned text, and remove redundant descendant freezing. A retained-entry probe cuts graph growth from 20,991,032 to 2,130,600 bytes while preserving all 500 shared message identities. The four-build 60-turn Gateway comparison does not reproduce the reported production heap-growth slope; this commit fixes the independently proven append-boundary defect. Focused tests, the full changed gate on Blacksmith Testbox, and independent review passed.
|
🦞👀 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: needs maintainer review before merge. Reviewed October 3, 2026, 11:08 AM ET / 15:08 UTC. ClawSweeper reviewWhat this changesThe PR detaches retained transcript strings from discarded tool output, preserves shared immutable payloads, refreshes redaction metadata, and adds a memory-retention regression. Merge readiness✅ Ready for maintainer review This remains a useful, focused repair absent from fetched main. No actionable introduced defect was found; the evidence supports append-boundary retention improvement without claiming a production-wide heap-growth fix. Priority: P2 Review scores
Verification
How this fits togetherSession persistence receives agent messages and tool results, normalizes and redacts them, then sends serialized bytes to the SQLite writer. Retained message objects also feed transcript views and subsequent model context. flowchart TD
A[Agent messages and tool results] --> B[Transcript redaction]
B --> C[JSON normalization and string ownership]
C --> D[Shared immutable payload]
D --> E[Serialized worker handoff]
E --> F[SQLite transcript]
D --> G[Transcript views and model context]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +12, Tests +98. Total +110 across 8 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep string-storage ownership in the transcript normalizer while preserving immutable sharing, native JSON semantics, and unchanged persisted bytes. Do we have a high-confidence way to reproduce the issue? Yes: retaining small slices through transcript normalization exposes a clear backing-storage retention path, supported by recorded pre-fix GC measurements. This reviewer inspected source and regression coverage without executing a current-main reproduction. Is this the best way to solve the issue? Yes: detaching strings at the existing normalization owner and updating matching redaction metadata repairs both retaining paths without changing the append API or stored representation. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 2c0278b46cd2. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
|
…w#164361) Detach transcript string storage once while retaining shared immutable message graphs. Refresh prepared redaction facts to carry the owned text, and remove redundant descendant freezing. A retained-entry probe cuts graph growth from 20,991,032 to 2,130,600 bytes while preserving all 500 shared message identities. The four-build 60-turn Gateway comparison does not reproduce the reported production heap-growth slope; this commit fixes the independently proven append-boundary defect. Focused tests, the full changed gate on Blacksmith Testbox, and independent review passed.
What Problem This Solves
Small persisted tool-result strings can retain much larger discarded tool outputs after transcript appends started sharing JSON-shaped payloads. Related: #164251.
User Impact
Retained transcript payloads own their string backing storage while continuing to share immutable message objects. Stored transcript bytes, schema, redaction policy, and append ordering are unchanged. No migration or configuration change is needed.
This fixes a reproduced append-boundary retention defect. Attribution to a production completed-turn heap-growth regression remains unproven; the full Gateway comparison below must be read separately from the retained-entry benchmark.
Why This Change Was Made
V8 sliced strings can keep their full parent strings alive. JSON shape validation and freezing do not detach that storage. The transcript normalizer now copies string code units once, freezes admitted descendants, and recognizes only those immutable graphs through weak ownership metadata. Later preparation reuses the same message/content graph. The separate recursive payload-freezing pass is removed, and prepared-message publication only freezes the remaining root.
Prepared redaction metadata also adopts the target string. Reusing the old preparation object would otherwise keep the original backing storage alive through its WeakMap value. Native JSON conversion still owns custom prototypes, getters, nonenumerable members,
toJSON, Buffers, typed arrays, functions, and omission semantics.Production LOC: +12 net (+29/−17), excluding tests and test support. This bounded growth enforces the string-storage ownership contract while preserving object sharing; the weak immutable-graph classification prevents a second string copy from recreating frozen container graphs. Redundant recursive freezing is deleted. No compatibility path, configuration option, or dependency is added.
Evidence
Retained-entry boundary, Linux / Node 26.8.1
Sixty actual canonicalizations retain 50 KiB text and a 1.5 KiB detail tail from independent 512 KiB tool-output strings. Two forced GCs precede snapshots at entries 20 and 60.
scripts/heap-snapshot-diff.mjsreports strong-edge dominators; process heap differences and retained-graph sizes are separate measurements.The retained-entry array dominates 10,496,296 → 31,487,328 B on the candidate and 1,066,272 → 3,196,872 B with the fix. The candidate's named path is
retained[0] → message → details → tail → (sliced string).parent → 524,304-byte string; the owning message dominates the full parent string. The fix reduces this array's growth from 20,991,032 to 2,130,600 B (89.85%).A second 500-entry canonicalization + serialization measurement uses the same 26,480,170 JSON bytes in all variants: old ownership 174.83 ms / 0 shared message identities, candidate 70.51 ms / 500 shared, fixed 108.42 ms / 500 shared. Fixed time remains 37.99% below the old JSON-copy path, with 71,993,824 B process heap versus candidate 307,218,080 B. These are boundary timings on a shared rig, not end-to-end append latency claims.
Dist Gateway comparison
All four dist Gateway runs passed on Linux / Node 26.8.1. Each completed 60 actual agent turns, five sessions, 50–500 KiB generated tool text, nested detail previews, four persisted image results, three reconnecting signed Control UI clients, and 180
chat.historycalls. The real tool-output guard persisted 51,200–64,000 text characters per result. All variants stored exactly 135 entries at turn 20 and 375 at turn 60 (240 new entries, including 160 new messages), verified from SQLite using terminal receipt markers and snapshot timestamps.bd03f427f965e0eaThese are aggregate main-isolate heap deltas after two forced GCs, not exclusive transcript retention. This workload does not reproduce the reported production slope, and does not implicate #164251 in accumulating completed-turn main heap. There is no valid regression predicate here for a binary-search attribution across the commit range. The append-boundary defect above remains independently reproduced and repaired.
Same-PID snapshot diffs show SessionManagers holding larger current transcript views alongside code/bytecode collection. Candidate manager retained totals were 1,514,040 → 4,198,224 B (seven instances → two); base totals were 555,792 → 4,464,944 B (one → two). Ordinary strong paths, separately checked with weak and ephemeron table edges excluded, are
timerListMap[1000] → one-shot session-row refresh Timeout → AsyncContextFrame → assertCommitAllowed → externalAbortController → AgentSession → SessionManager, andGlobal handles → outbound Undici TCP/Socket → AsyncContextFrame → same run context → AgentSession → SessionManager. Both paths already exist in the base. Candidate's latest 1 KiB detail previews are independent internalized strings, with no 8 MiB donor-string parent. No new unbounded manager/registry holder was demonstrated.Commands used each isolated worktree's dist Gateway through the same synthetic runner, with
TMPDIRbelow.rig/tmp,nice -n 10 ionice -c3, and loopback-only listeners. Base, candidate, and diagnostic revert built withOPENCLAW_RUN_NODE_SKIP_DTS_BUILD=1 pnpm build; fixed built withpnpm build sourcePerformance. Snapshot pairs were compared usingnode scripts/heap-snapshot-diff.mjs <turn-020> <turn-060> --top 12 --json.Fixture repairs: initial runs accidentally placed synthetic workspace and live state under an enclosing Git root. Session baseline capture fingerprinted untracked SQLite SHM files, dropping process-wide POSIX locks; a readonly SQLite child then called
ftruncate(shmFd, 3)and the mapped Gateway crashed 9 ms later. Candidate and base both reproduced this before profiling. Giving each synthetic workspace its own Git root kept sibling state out of its inventory; all four corrected runs passed. Those failed runs are excluded from the table. One fixed-build attempt rejected a changed test-support input during preparation; after the fixture stabilized, a complete rebuild passed.Tests and checks
src/agents/sessions/session-manager-async-message.test.ts,src/agents/sessions/agent-session-tool-result-redaction.test.ts, andsrc/logging/redact.test.tson the same lease, 47.35 s across three shards. This covers shared message ownership, queued capture, native custom serialization, pending/replay custody, and post-commit redaction replacement.f965e0ea, it fails with 16,777,256 retained external bytes. Fixed: 40 external bytes and 57,384 heap bytes. Unicode/lone-surrogate bytes and repeated graph sharing are checked after the GC measurement. The first fixture checked only heap bytes and missed externalized string storage; it was corrected before accepting the negative proof.pnpm test src/config/sessions/transcript-json.test.ts --maxWorkers=1: 21 passed, 145 ms regression body, 659 ms Vitest duration, 1.37 s wrapper wall time. Current-head CI: 164 ms regression body, 765 ms Vitest duration, 1.97 s wrapper wall time inchecks-node-changed-3.node scripts/check-changed.mjs -- <all eight changed paths>passed production types, all 27 test type graphs, changed-file lint (zero warnings/errors), dead-export scans, formatting, and all selected guards. Crabbox sync preserves working-tree changes rather than the local index, so an earlier--stagedinvocation selected no paths and is not counted as gate proof. The lease was stopped after validation.6d05367678fbpreserved all eight reviewed/tested file blobs exactly; the branch contains only this fix. Current-head CI run 37131871478 passed in 510 s on39995114e9f212735e5366178c324fe4854f4a24, includingopenclaw/ci-gate; final rollup: 76 passing, zero pending or failed checks. The lead’s watcher merged this PR asbb46fa6e36721b45e6838345251ef7f2f7c295a7at 15:12:32 UTC. No manual merge command was issued. No local builds, suites, or typechecks ran.Ownership and attribution limits
The classifier still uses native JSON conversion for hidden/accessor/prototype/opaque graphs; frozen plain payloads reject later property attachment.
freezeJsonSnapshotkeeps only a call-local visited Set and a global WeakSet, so it does not provide a strong retaining root. Private WeakMap metadata is a separate identity-based relationship; prepared tool text is covered by this repair.Metadata workers receive serialized bytes and decode independent graphs. Fresh host receipts reuse the normalized payload; authoritative replay/pending receipts remain worker-owned. Session-list rows consume target/revision metadata rather than live message objects. History pages independently decode SQLite data and use a bounded worker cache. No direct live-message alias into that cache was found. Full-transcript source-message reads can still create a separate transient memory peak, but this investigation has not demonstrated that they retain the agent's shared payload graph.