Repository navigation
perf(sessions): persist transcript entries without deep-copying them - #164251
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: needs maintainer review before merge. Reviewed October 3, 2026, 7:24 AM ET / 11:24 UTC (Revision 2). ClawSweeper reviewWhat this changesSession transcript appends share immutable payloads, send serialized bytes to the database worker, and propagate replacement tool results when redaction changes. Merge readiness✅ Ready for maintainer review The PR remains useful, and no blocking correctness finding was identified. The updated byte-equivalence and reopen evidence addresses the earlier compatibility concern; the measured retention benefit is clearly distinguished from latency improvement. Priority: P2 Review scores
Verification
How this fits togetherSessionManager records agent messages and metadata in SQLite and supplies transcript views for subsequent model requests. This change coordinates payload ownership between callers, the database worker, and live agent history. flowchart TD
A[Agent messages and metadata] --> B[Normalize and freeze payload]
B --> C[Serialized worker request]
C --> D[SQLite transcript writer]
D --> E[Fresh or authoritative replay receipt]
E --> F[Shared transcript and prompt history]
F --> G[Redaction policy changes]
G --> H[Replacement model context]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +276, Tests +562, Docs +9. Total +847 across 22 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Keep one immutable append payload owner, preserve existing transcript bytes and authoritative replay custody, and publish redaction changes as runtime replacements. Do we have a high-confidence way to reproduce the issue? Not applicable as a bug reproduction: this is a performance change. Current main visibly deep-copies entries, and the captured before/after workload measures retained duplicates through persistent SessionManagers. Is this the best way to solve the issue? Yes. Sharing immutable payloads at the existing append owner removes duplicate retention while preserving native JSON semantics, database ownership, replay custody, and committed transcript bytes. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against de1f4385dc66. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
Transfer ordinary append payloads into the session owner's immutable graph, serialize them once for the SQLite worker, and reuse prepared host payloads for fresh receipts. Keep authoritative pending-input and replay payloads writer-owned, and preserve shipped custom JSON serialization semantics. Capture payloads before queue waits and keep raw caller-owned envelopes separate. Publish immutable runtime replacements when redaction changes after commit, preserving the stored transcript and the original canonical payload. Document append ownership and isolate the process-wide warning test fixture. The ten-minute synthetic workload retained 42,672,384 bytes per 1,000 tool results versus 101,981,152 bytes before (-58.16%), with one object per entry and identical persisted payload bytes. Measured append time increased 53.05%; this establishes a retention benefit, not a latency or production-slope fix.
Use real transcript rehydration to exercise carrierless timestamp fallback, rather than relying on append to deep-copy its input. Separately cover the retained exact prompt beside same-time steering, preserving the ambiguity assertions and ensuring steering never inherits the original prompt context. Reproduced the original failure with the repository-pinned Bun runtime on Testbox, then passed the repaired steering cases on both Node and Bun.
f7fc600 to
7e3354e
Compare
…penclaw#164251) * perf(sessions): persist transcript entries without deep-copying them Transfer ordinary append payloads into the session owner's immutable graph, serialize them once for the SQLite worker, and reuse prepared host payloads for fresh receipts. Keep authoritative pending-input and replay payloads writer-owned, and preserve shipped custom JSON serialization semantics. Capture payloads before queue waits and keep raw caller-owned envelopes separate. Publish immutable runtime replacements when redaction changes after commit, preserving the stored transcript and the original canonical payload. Document append ownership and isolate the process-wide warning test fixture. The ten-minute synthetic workload retained 42,672,384 bytes per 1,000 tool results versus 101,981,152 bytes before (-58.16%), with one object per entry and identical persisted payload bytes. Measured append time increased 53.05%; this establishes a retention benefit, not a latency or production-slope fix. * test(agents): exercise transcript replay ownership explicitly Use real transcript rehydration to exercise carrierless timestamp fallback, rather than relying on append to deep-copy its input. Separately cover the retained exact prompt beside same-time steering, preserving the ambiguity assertions and ensuring steering never inherits the original prompt context. Reproduced the original failure with the repository-pinned Bun runtime on Testbox, then passed the repaired steering cases on both Node and Bun.
What Problem This Solves
Transcript appends retain duplicate tool-result graphs and repeatedly copy text into cache-TTL history markers. A ten-minute synthetic workload retained two tool-result objects per call ID and 101,981,152 bytes on the main heap.
User Impact
SessionManager instance appends transfer ordinary JSON payload ownership at submission. Receipts, transcript views, and prompt history share immutable payloads; callers must create a new value for a later update, including while an append is pending. Stored transcript bytes and database schema are preserved; no migration is needed.
Why This Change Was Made
The append owner normalizes ordinary JSON in place, freezes captured payloads before queue waits, and sends serialized payloads to the SQLite metadata worker. Fresh receipts reuse the prepared host object. Pending-input promotion and idempotent replay still return their authoritative payloads. Raw
persistAsynccaptures a shallow private envelope while sharing its immutable payload; static note APIs retain their existing input-capture contract.Unchanged tool-result preparation reuses its content array. A redaction change after commit creates an immutable runtime projection which sync and streamed-async consumers adopt without changing the committed object or bytes. Maintenance rewrites take a mutable publication snapshot. Prepared static-note redaction is invalidated by the registry revision and effective pattern values.
Production LOC is +276 net (+419/−143, excluding tests, test support, and docs). This is a contract-driven exception to the net-negative target: the public v2026.9.8 custom-data API requires native key-sensitive
toJSON, getter ordering, omission, and opaque-value semantics; bytes-only transport must retain authoritative pending/replay receipts; and frozen committed messages require complete runtime replacement propagation after redaction changes. Native conversion remains only for exceptional serialization graphs. Ordinary whole-entry and prepared-message JSON round trips are removed.Evidence
The same ten-minute Linux/Node 26 workload uses ten persistent SessionManagers, 1,000 unique 32 KiB tool results, retained caller histories, and 100 cache-TTL markers with growing 4 KiB projection strings. Main-isolate live-only allocation sampling and before/after heap snapshots identify caller history and manager entries as the original strong retainers.
Retained heap decreases 59,308,768 bytes / 58.16%. All 100 metadata snapshots reuse their input objects. Live sampled canonicalization allocation falls 24,714,680 → 103,328 bytes; worker-reply deserialization no longer appears among sampled survivors.
All 1,100 stored events / 57,669,896 JSON bytes match, with normalized raw-byte SHA256
9d4979e5df602da52f5d0625efda2a71c2d2f1d5f2331ab45afb9536f4091eca. Only generated envelope IDs, parents, and timestamps were normalized; payload bytes and property order were preserved.Data compatibility: this changes in-memory ownership and worker transport, with no stored schema/version or transcript-shape change. The byte comparison above covers old and new append implementations;
transcript-json.test.tsverifies native JSON byte semantics,session-manager.persistence-compat.test.tsreads existing SQLite transcript/control rows, andsession-manager-async-entries.test.tsreopens every appended entry family with unchanged state and ancestry. All are included in the passing Testbox run below. No migration is required; a published-install upgrade campaign was not run.Timing tradeoff: summed append time was 11,988.996 → 18,349.597 ms (+53.05%) on the shared, profiled rig. This demonstrates retention improvement, not a latency improvement or a fix for the production heap-growth slope. Worker-isolate transient allocations are outside these snapshots. The workload was repeated after the payload-custody fixes; the final lint repairs preserve that behavior.
Validation:
tbx_01m40ke2wgvrxa7jw4bve4c586, profileopenclaw-check: 183 tests across 14 files passed, four shards in 126.16 s, using the focused command below with one worker. All 21 candidate file hashes and base7a635c2117ea6743ccf2b36e1fde56d45e614063were checked before execution.node scripts/check-changed.mjs --staged. Production types, all 27 test type graphs, guards, and dead-export scans passed; two lint findings were repaired. The same Testbox then reran production types (42.64 s), changed-file lint (7.71 s, zero warnings/errors), and every remaining native-plan check: schema version, legacy stores, media helpers, sidecar loaders, import cycles, webhook bodies, and pairing guards. All passed; earlier unaffected proof was retained.tbx_01m402sawq9kb5zkkkmv82nvq2failed the new ownership assertion on the original implementation (six roots instead of three).tbx_01m40chak90njf6zacswpc7kr2reproduced both sync/async post-commit continuation failures, pattern-policy admission failure, and all four payload-custody/getter-order defects with their fixes removed. The restored candidate passed those cases. Actual SDK AgentSession sync/async rig turns also preserved committed SQLite bytes while publishing masked runtime replacements.tbx_01m40p82qtgecmq4kcnd26qmcp, profileopenclaw-check, reproduced the original Bun steering failure and four Node stream-prepare failures. The repaired paths passed 60 Node tests / two files (23.19 s) and nine Bun steering tests (7.19 s). The complete reproduction/repair command took 101.017 s, exit 0.node scripts/check-changed.mjs --staged --timedpassed all selected checks, including the agents-other and gateway-server test type graphs, in 267.405 s.git diff --checkpasses. No local suites, builds, or typechecks ran on the saturated Mac. The final rebase onto6153557c49168f07a02c0479d8124facc2ecc888preserved all 23 tested file contents, including the inherited fixture repair; this PR changes 22 files. Current-head CI and the aggregate CI gate passed on7e3354e021f22b395ea91d8eaa3bf26697397abf(run 37119166782); the final PR rollup has 89 successful checks and no pending or failed checks.Focused Testbox command
The same command ran after two scoped negative probes:
agent-session-tool-result-redaction.test.ts -t reprojectswith only runtime projection changes reversed, andsession-manager-static-notes.test.ts -t "pattern redaction"with only the pattern snapshot change reversed. Both patches were restored before the combined run.