Skip to content

fix(sessions): release discarded tool output backing strings - #164361

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-heap-regression-r35-20260919
Oct 3, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-heap-regression-r35-20260919

Conversation

@steipete

@steipete steipete commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

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.mjs reports strong-edge dominators; process heap differences and retained-graph sizes are separate measurements.

Ownership path Post-GC heap at 20 Post-GC heap at 60 Growth / entry, 20→60
Previous JSON-copy ownership 40,737,168 B 42,876,168 B 53,475 B
Candidate shared ownership 50,388,856 B 71,420,032 B 525,779 B
Fixed shared ownership 40,943,464 B 43,130,016 B 54,664 B

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.history calls. 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.

Build Post-GC main heap, turn 20 Post-GC main heap, turn 60 Delta / appended entry
Base bd03f427 261,197,296 B 267,529,688 B +26,385 B
Candidate f965e0ea 265,732,704 B 264,903,216 B −3,456 B
Candidate with diagnostic revert of #164251 266,033,336 B 271,769,944 B +23,903 B
Candidate plus this fix 265,623,952 B 268,030,016 B +10,025 B

These 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, and Global 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 TMPDIR below .rig/tmp, nice -n 10 ionice -c3, and loopback-only listeners. Base, candidate, and diagnostic revert built with OPENCLAW_RUN_NODE_SKIP_DTS_BUILD=1 pnpm build; fixed built with pnpm build sourcePerformance. Snapshot pairs were compared using node 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

  • Blacksmith Testbox tbx_01m412k94992mpt2rxex20a373, provider blacksmith-testbox, profile openclaw-check: original normalization and async-message baseline passed 34 tests / two files, 29.04 s across the two routed shards. The initial command found missing dependencies; one frozen-lockfile installation fixed the lease setup.
  • The production patch passed src/agents/sessions/session-manager-async-message.test.ts, src/agents/sessions/agent-session-tool-result-redaction.test.ts, and src/logging/redact.test.ts on 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.
  • New regression: eight small payloads must release eight 2 MiB donor strings, including frozen/preserved input and prepared-redaction metadata. On original 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.
  • Final 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 in checks-node-changed-3.
  • Changed gate on the same Blacksmith Testbox: passed, exit 0, 22m38.553s command / 22m39.033s total. 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 --staged invocation selected no paths and is not counted as gate proof. The lease was stopped after validation.
  • Independent Codex review: scoped-clean through P2, no accepted/actionable findings. The reviewer explicitly agreed that retained-entry proof does not establish a production slope fix. The final rebase onto 6d05367678fb preserved all eight reviewed/tested file blobs exactly; the branch contains only this fix. Current-head CI run 37131871478 passed in 510 s on 39995114e9f212735e5366178c324fe4854f4a24, including openclaw/ci-gate; final rollup: 76 passing, zero pending or failed checks. The lead’s watcher merged this PR as bb46fa6e36721b45e6838345251ef7f2f7c295a7 at 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. freezeJsonSnapshot keeps 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.

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.
@clawsweeper

clawsweeper Bot commented Oct 3, 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 agents Agent runtime and tooling size: S labels Oct 3, 2026
@steipete
steipete marked this pull request as ready for review October 3, 2026 15:03
@github-actions

github-actions Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 39995114e9f212735e5366178c324fe4854f4a24
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/logging/redact-internal-state.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/logging/redact-internal.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@steipete
steipete enabled auto-merge (squash) October 3, 2026 15:04
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 11:08 AM ET / 15:08 UTC.

ClawSweeper review

What this changes

The 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
Reviewed head: 39995114e9f212735e5366178c324fe4854f4a24

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with strong scoped measurements, meaningful negative regression evidence, and no identified blocking defect.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded Linux/Node canonicalization heap snapshots exercise the changed normalization owner and show reduced retained backing storage with unchanged bytes and graph sharing. Dist Gateway runs additionally exercise actual tool-result persistence and history reads, without proving a production-wide slope fix. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded Linux/Node canonicalization heap snapshots exercise the changed normalization owner and show reduced retained backing storage with unchanged bytes and graph sharing. Dist Gateway runs additionally exercise actual tool-result persistence and history reads, without proving a production-wide slope fix. No stored-data contract changes.
Evidence reviewed 8 items Pinned introduced change: Reviewed the complete merge-base-to-head patch across all eight paths. String detachment and descendant freezing are consolidated into normalization; prepared-message roots remain frozen. The verified test merge uses the pinned base and head parents.
Still necessary on fetched main: Fetched main's normalizer retains ordinary string values without detaching their backing storage and lacks the new weak ownership classification. No current-main implementation of this repair was found. Inspection of the latest release's corresponding blob failed because the promisor fetch returned HTTP 403, so no release-content conclusion is claimed.
Existing ownership contract: The documented append contract already transfers ordinary JSON payloads by reference and freezes nested objects during pending appends. Inspection of canonicalization, worker preparation, receipt adoption, and existing async-message tests supports preserving that contract; no stored schema, configuration, or serialization format is changed.
Findings None None.
Security None None.

How this fits together

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

Before merge

None.

Agent review details

Security

None.

PR surface

Source +12, Tests +98. Total +110 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 6 29 17 +12
Tests 2 98 0 +98
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 127 17 +110

Review metrics

Metric Value Why it matters
Production versus regression growth production +12 net; tests and test support +98 Production growth has a stated ownership justification and removes redundant recursive freezing; added coverage directly detects donor-string retention.

Technical review

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

Labels

Label changes:

  • add P2: This is a bounded, evidenced transcript-retention repair; an urgent production-wide heap-growth regression has not been established.
  • add proof: sufficient: Contributor real behavior proof is sufficient. Recorded Linux/Node canonicalization heap snapshots exercise the changed normalization owner and show reduced retained backing storage with unchanged bytes and graph sharing. Dist Gateway runs additionally exercise actual tool-result persistence and history reads, without proving a production-wide slope fix. No stored-data contract changes.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded Linux/Node canonicalization heap snapshots exercise the changed normalization owner and show reduced retained backing storage with unchanged bytes and graph sharing. Dist Gateway runs additionally exercise actual tool-result persistence and history reads, without proving a production-wide slope fix. No stored-data contract changes.

Label justifications:

  • P2: This is a bounded, evidenced transcript-retention repair; an urgent production-wide heap-growth regression has not been established.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded Linux/Node canonicalization heap snapshots exercise the changed normalization owner and show reduced retained backing storage with unchanged bytes and graph sharing. Dist Gateway runs additionally exercise actual tool-result persistence and history reads, without proving a production-wide slope fix. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded Linux/Node canonicalization heap snapshots exercise the changed normalization owner and show reduced retained backing storage with unchanged bytes and graph sharing. Dist Gateway runs additionally exercise actual tool-result persistence and history reads, without proving a production-wide slope fix. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the complete merge-base-to-head patch across all eight paths. String detachment and descendant freezing are consolidated into normalization; prepared-message roots remain frozen. The verified test merge uses the pinned base and head parents. (src/config/sessions/transcript-json.ts:75, 39995114e9f2)
  • Still necessary on fetched main: Fetched main's normalizer retains ordinary string values without detaching their backing storage and lacks the new weak ownership classification. No current-main implementation of this repair was found. Inspection of the latest release's corresponding blob failed because the promisor fetch returned HTTP 403, so no release-content conclusion is claimed. (src/config/sessions/transcript-json.ts:72, 2c0278b46cd2)
  • Existing ownership contract: The documented append contract already transfers ordinary JSON payloads by reference and freezes nested objects during pending appends. Inspection of canonicalization, worker preparation, receipt adoption, and existing async-message tests supports preserving that contract; no stored schema, configuration, or serialization format is changed. Public docs: docs/plugins/sdk-runtime.md. (docs/plugins/sdk-runtime.md:146, 39995114e9f2)
  • Redaction metadata safety: Metadata copying now retains the target's owned string while preserving the existing text-equality, effective-pattern, full-context, and registry-revision checks. This changes storage ownership rather than authorization or redaction policy. (src/logging/redact-internal-state.ts:63, 39995114e9f2)
  • Behavior evidence and scope: The complete supplied body, captured under sourceRevision 9b2ea9029bc904b4de44aab55a1a2709803027cb0f19f18e180543a69543eb0c, reports Linux/Node 26.8.1 canonicalization snapshots reducing retained-array growth from 20,991,032 to 2,130,600 bytes while preserving 500 shared message identities and identical serialized bytes. Four dist Gateway runs exercised actual tool results, SQLite appends, reconnecting clients, and history reads. Their aggregate heaps did not reproduce the production slope. These are contributor-recorded observations, not reviewer-executed tests. (39995114e9f2)
  • Regression value and cost: The new isolated-GC regression covers plain, frozen, preserved, and prepared-redaction inputs, checks both external and heap retention before inspecting strings, and verifies Unicode and graph reuse afterward. The body records a pre-fix failure retaining 16,777,256 external bytes and a fixed result of 40 external bytes; the focused file took 1.37 seconds wrapper wall time. No tests or builds were executed during this review. (src/config/sessions/transcript-json.retention.test-support.ts:43, 39995114e9f2)

Likely related people:

  • Peter Steinberger: Raw commit e40ed06 adds src/config/sessions/transcript-json.ts:6 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e40ed06f23cb; files: src/config/sessions/transcript-json.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete
steipete merged commit bb46fa6 into main Oct 3, 2026
204 of 205 checks passed
@steipete
steipete deleted the steipete/perf-micro-heap-regression-r35-20260919 branch October 3, 2026 15:12
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
…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.
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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security-sensitive-changed size: S 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