Skip to content

Reduce memory used to save conversation history - #2722

Open
cartridgebasic wants to merge 3 commits into
Zoo-Code-Org:mainfrom
cartridgebasic:fix/history-snapshot-memory
Open

cartridgebasic wants to merge 3 commits into
Zoo-Code-Org:mainfrom
cartridgebasic:fix/history-snapshot-memory

Conversation

@cartridgebasic

Copy link
Copy Markdown
Contributor

Reduce memory used to save conversation history

Related GitHub Issue

Closes #2721

Description

Long conversation histories can exhaust the extension host heap during a save.

Copy arrays and plain objects without copying their string values. Track object identity and preserve sparse arrays. If the graph contains a special object, use the native clone for the full graph so references across that boundary stay intact. Leave locking, save order, and retry behavior in place.

Test Procedure

Use a task with a large UI and API transcript. Save repeatedly while the task receives new messages. An allocation capture showed 120 MB of UI history and 156 MB of API history in one affected task.

The checks below ran in the Linux review container with Node and pnpm.

pnpm --dir src exec vitest run --maxWorkers=2 core/task-persistence/__tests__/historySnapshot.spec.ts core/task/__tests__/Task.persistence.spec.ts
pnpm --dir src exec tsc --noEmit
pnpm --dir src exec eslint --prune-suppressions --max-warnings=0 core/task/Task.ts core/task/__tests__/Task.persistence.spec.ts core/task-persistence/historySnapshot.ts core/task-persistence/__tests__/historySnapshot.spec.ts

All listed checks passed.

Pre-Submission Checklist

  • Issue Linked
  • Scope
  • Self-Review
  • Writing Style
  • Testing
  • Documentation Impact
  • Contribution Guidelines

Documentation Updates

  • No documentation updates are required.

Additional Notes

This patch can be reviewed on its own. Assignment is pending. The author reviewed the local changes. AI assistance was used for implementation, tests, and preparation of this draft. Maintainers can reach @cartridgebasic in this thread.

Get in Touch

Share immutable strings while copying mutable transcript containers. Use a native clone for the full graph when a legacy value needs it.

Refs Zoo-Code-Org#2721
@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Task and API histories now retain independent snapshots when saves happen concurrently, preventing later changes from altering previously saved records.
    • Retries capture the latest task data without changing snapshots from earlier failed attempts, helping preserve accurate history for nested inputs and related data.
    • Snapshot handling now better preserves relationships and special values in task history, reducing the risk of saved records differing from the data at the time of saving.

Adds snapshotHistory to copy plain history graphs while preserving cycles and shared references. Unsupported values use a whole-graph structuredClone fallback. UI and API persistence paths now use this function before saving.

Changes: Task History Snapshots

Layer / File(s) Summary
Snapshot history graphs
src/core/task-persistence/historySnapshot.ts, src/core/task-persistence/__tests__/historySnapshot.spec.ts
Adds graph copying for arrays and plain or null-prototype objects, preserving cycles and shared references. Unsupported values trigger a whole-graph structuredClone fallback. Tests cover graph shape, special objects, accessors, and errors.
Use snapshots for persistence
src/core/task/Task.ts, src/core/task/__tests__/Task.persistence.spec.ts
UI and API history save paths use snapshotHistory instead of structuredClone. Tests cover independent save snapshots, failed-save retries, and updated nested input on API retry.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: Minimal · up to 7f1bf

This change reduces memory use when saving large conversation histories while keeping save behavior the same. No merge-blocking risk was identified.

Pre-merge checks: Passed 8

Check name Status Explanation
Title check Passed The title names the main change: reducing memory used when saving conversation history. The PR adds a snapshot function that copies arrays and plain objects, and Task.ts uses it in the UI and API save…
Description check Passed The description follows the template. It links the issue (Closes #2721) and explains the approach, including identity tracking, sparse arrays, and the native clone fallback. It gives a concrete test p…
Linked Issues check Passed [#2721] Requirement: stop large per-save allocations in Task.saveClineMessages() and Task.saveApiConversationHistory() so that saves keep the full conversation without heap exhaustion. At head 7f1bfef…
Out of Scope Changes check Passed All changes relate to #2721. historySnapshot.ts holds the snapshot logic. Task.ts changes only the persistence call sites to use snapshotHistory(). historySnapshot.spec.ts and Task.persistence.spec.ts…
Regression Evidence Passed The changed behavior is the new snapshotHistory helper (src/core/task-persistence/historySnapshot.ts) and its use in Task.saveApiConversationHistory and Task.saveClineMessages. No visible UI c…
Security Boundaries Passed The PR changes four files: a new src/core/task-persistence/historySnapshot.ts, two replaced structuredClone calls in src/core/task/Task.ts, and two test files. I read the full diff for the chang…
Persistence Integrity Passed The PR changes two persistence paths in src/core/task/Task.ts. saveApiConversationHistory and saveClineMessages now pass snapshotHistory(...) instead of structuredClone(...) to `saveApiMessage…
Lifecycle Resource Cleanup Passed The changed lifecycle paths do not introduce a listener, watcher, provider, timer, task, or other resource leak, and they do not add duplicate work after cancellation, disposal, or restart. Diff evide…
Full details: Title check

Explanation

The title names the main change: reducing memory used when saving conversation history. The PR adds a snapshot function that copies arrays and plain objects, and Task.ts uses it in the UI and API save paths. The title is short, specific, and in active voice. It does not use file lists or vague terms.

Full details: Description check

Explanation

The description follows the template. It links the issue (Closes #2721) and explains the approach, including identity tracking, sparse arrays, and the native clone fallback. It gives a concrete test procedure with commands and results, and it marks the checklist and documentation sections. Some items remain incomplete. The Issue Linked checkbox is unchecked, although the description links the issue. The Recorded Stream section is left blank, but it applies only to new provider PRs. The Get in Touch section still has the placeholder comment and no Discord name. The Description section does not describe the trade-offs or the reviewer checks that the template asks for. The Additional Notes say the patch can be reviewed alone and that assignment is pending, which adds little to the review. The Visual Snapshots and Videos sections are omitted, which is acceptable for a non-UI change.

Resolution

Optional improvements: tick the Issue Linked checkbox, add a Discord name or remove the placeholder comment in Get in Touch, and state the trade-offs and the parts reviewers should check closely, such as the fallback to structuredClone for special objects.

Full details: Linked Issues check

Explanation

[#2721] Requirement: stop large per-save allocations in Task.saveClineMessages() and Task.saveApiConversationHistory() so that saves keep the full conversation without heap exhaustion. At head 7f1bfef, src/core/task-persistence/historySnapshot.ts still implements snapshotHistory(). It rebuilds arrays and plain or null-prototype objects, returns string and other primitive values as-is, tracks identity through a WeakMap so aliases and cycles are preserved, and keeps sparse arrays and extra array properties. Functions, symbols, proxies, non-plain prototypes, and accessors throw a private sentinel. The helper then runs structuredClone on the whole graph, so cross-boundary references stay intact. The spec file at head covers these cases: no structuredClone call for ordinary data, aliases and cycles, holes and extra properties, own proto with normal and null prototypes, whole-graph fallback with Map, Set, Date, ArrayBuffer and view references, single getter evaluation, and DataCloneError for function, symbol, and proxy inputs. The incremental change since the previous review strengthens these tests. It does not alter the core snapshot logic shown at head. Limits: the incremental diff could not be read, so the exact test edits are known only from the PR objectives and the spec file at head. The PR does not report the result of a repeated-save heap measurement, so the heap reduction is not measured. These gaps do not block a coding-requirement PASS.

Full details: Out of Scope Changes check

Explanation

All changes relate to #2721. historySnapshot.ts holds the snapshot logic. Task.ts changes only the persistence call sites to use snapshotHistory(). historySnapshot.spec.ts and Task.persistence.spec.ts test the snapshot helper and persistence behavior. The incremental change strengthens regression tests, which supports the same objective. The PR states that locking, save order, and retry behavior are unchanged. No unrelated change is evident in the inspected files. The incremental diff could not be read, so this verdict rests on the whole-PR summary and the spec and source files at head.

Full details: Regression Evidence

Explanation

The changed behavior is the new snapshotHistory helper (src/core/task-persistence/historySnapshot.ts) and its use in Task.saveApiConversationHistory and Task.saveClineMessages. No visible UI changes are in the diff, so snapshot requirements do not apply. Test evidence at the lowest valid layer: - historySnapshot.spec.ts is a unit spec that calls the real snapshotHistory function. It does not copy the implementation. It covers: - the ordinary plain-container path, including a check that structuredClone is not called; - aliases and cycles; - array holes, explicit undefined, extra array properties, and primitives such as NaN, BigInt, and -0; - own __proto__ properties under both normal and null prototypes; - whole-graph fallback for Map, Set, Date, ArrayBuffer, and typed-array graphs; - accessors, with a check that the getter runs once; - the negative and error cases: DataCloneError for functions, symbols, and proxies. - Task.persistence.spec.ts covers the changed call sites through the real save methods. It checks isolation across concurrent saves, fresh snapshots on retry without mutating the failed snapshot, reference preservation across legacy special objects, and API backoff with nested tool input. I did not find a concrete, plausible regression case that lacks a test. A possible gap is a direct test for a custom class instance, which the code rejects through the prototype check. That path shares the fallback branch that the Map/Set/Date graph test already covers, so I do not treat it as a concrete gap.

Full details: Security Boundaries

Explanation

The PR changes four files: a new src/core/task-persistence/historySnapshot.ts, two replaced structuredClone calls in src/core/task/Task.ts, and two test files. I read the full diff for the changed paths. - Task.ts changes only two lines. saveApiConversationHistory and saveClineMessages now call snapshotHistory(...) instead of structuredClone(...). The lock, save order, retry logic, and the saveApiMessages/saveTaskMessages destinations are unchanged. No approval, allowlist, or command-execution path is touched. - historySnapshot.ts rebuilds arrays and plain or null-prototype objects. It copies only own enumerable string-keyed data properties, using Object.defineProperty. This avoids invoking __proto__ setters. Accessors, functions, symbols, proxies, and non-plain prototypes fall back to structuredClone. The data is the task's own conversation history, which the existing code already persisted. The change does not add a new input source, does not evaluate input, and does not expose secrets or personal data beyond what the previous structuredClone path already wrote to the same storage. I found no concrete defect in a changed path that matches the check's criteria (exposed secrets or personal data, trusted or executed unvalidated input, or bypassed approval/allowlist controls). Behavior differences such as deep-recursion limits or dropped non-enumerable properties affect correctness, not the security boundaries named in this check.

Full details: Persistence Integrity

Explanation

The PR changes two persistence paths in src/core/task/Task.ts. saveApiConversationHistory and saveClineMessages now pass snapshotHistory(...) instead of structuredClone(...) to saveApiMessages and saveTaskMessages. The diff touches nothing else in those methods. The await, the merge flag, the task ID, and the storage path are unchanged, so write ordering and retry behavior stay as they were. I read the new snapshotHistory in src/core/task-persistence/historySnapshot.ts and checked each condition that could lose or corrupt state: - Snapshot isolation: arrays and plain or null-prototype objects are rebuilt. Strings and other primitives are returned as-is, which is safe because they are immutable. - Aliases and cycles: a WeakMap keeps the copy identical to the source graph. - Sparse arrays: new Array(length) plus copying only own keys keeps the holes. - Own __proto__ keys: Object.defineProperty stores them as data properties. - Accessors, functions, symbols, proxies, and other prototypes (Map, Set, Date, typed arrays, class instances): these throw the internal sentinel, and the whole graph goes to structuredClone. That keeps the old semantics, including DataCloneError for functions and symbols. - Partial failure: the plain-copy pass has no side effects on the source and writes nothing to storage. Its partial result is discarded before the fallback runs. I found no write without await, no non-atomic write, and no missing rollback path in the changed code. The change does not alter the persistence write logic itself. Its risk is memory use, which the check does not cover.

Full details: Lifecycle Resource Cleanup

Explanation

The changed lifecycle paths do not introduce a listener, watcher, provider, timer, task, or other resource leak, and they do not add duplicate work after cancellation, disposal, or restart. Diff evidence (base..head): - src/core/task-persistence/historySnapshot.ts (new file) adds snapshotHistory<T>. It is synchronous. It creates no listeners, timers, watchers, or providers. Its only state is a local WeakMap and a local snapshot tree, both released when the call returns. On a fallback, the partial snapshot is left for garbage collection. It does not hold a resource. - src/core/task/Task.ts: the only changes replace structuredClone(this.apiConversationHistory) in saveApiConversationHistory and structuredClone(this.clineMessages) in saveClineMessages with snapshotHistory(...). The call sites, await flow, merge flag, and surrounding try/catch are unchanged. The contributor states that locking, save order, and retry behavior are unchanged, and the diff does not contradict this. - The two spec files are test-only additions. They do not change runtime lifecycle code. No changed path adds a cleanup obligation or a repeated operation on cancel, dispose, or restart. The change does not alter when saves run or how often they retry.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between e946213 and 7f1bfef.

Files selected for processing: 2

  • src/core/task-persistence/__tests__/historySnapshot.spec.ts
  • src/core/task/Task.ts

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 2 remain after this review.

Recent review details

Context from checks skipped due to timeout: 2

  • GitHub Check: CodeRabbit
  • GitHub Check: extension-host-visual
Additional context used

Path-based instructions: 5

Check saved state and lifecycle rules.

CodeRabbit configuration file

Files:

  • src/core/task/Task.ts
Require regression tests at the lowest test layer that can show the behavior.

CodeRabbit configuration file

Files:

  • src/core/task-persistence/__tests__/historySnapshot.spec.ts
Check types and behavior for normal, boundary, error, cancellation, retry, and compatibility cases.

CodeRabbit configuration file

Files:

  • src/core/task-persistence/__tests__/historySnapshot.spec.ts
  • src/core/task/Task.ts
Check extension and webview contracts, cancellation, error propagation, and the VS Code lifecycle.

CodeRabbit configuration file

Files:

  • src/core/task-persistence/__tests__/historySnapshot.spec.ts
  • src/core/task/Task.ts
Review each change as an independent reviewer.

CodeRabbit configuration file

Files:

  • src/core/task-persistence/__tests__/historySnapshot.spec.ts
  • src/core/task/Task.ts

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Review status

Thanks for contributing. This comment tracks the review sequence and the next action.

Current step: Awaiting fresh human maintainer or CODEOWNER approval.

Automated review is complete for the latest commit but does not replace human approval.

Review-state labels are managed by this workflow; do not edit them manually. community-approved is managed the same way — do not add or remove it manually. It signals a fresh community code approval for the current head as an advisory priority only; maintainer review is still required.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.65217% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/core/task-persistence/historySnapshot.ts 95.65% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@cartridgebasic
cartridgebasic marked this pull request as ready for review November 30, 2026 17:30
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Changed-code mutation testing

Report for PR head 7f1bfefdd584.

Surviving / uncovered mutants Advisories
0 1
Details: mutants, guidance, and reproduction

Changed-code mutation testing

PackageChanged executable linesValidKilledTimeoutSurvivedNo coverageResult
extension4100000Advisory incomplete

Focused tests

  • extension (cwd src): The mutation run was incomplete; selected test file names were not recorded. See Advisory findings for the failure.

Reproduce locally

From a full checkout containing both commits:

pnpm install --frozen-lockfile
node scripts/stryker-diff.mjs ci --base 9f8e4836680277425d36b47866b65b1b78b8b55c --head 07321c49c8b1ac195daa3360348f8351a18aceb4

Mutation reports

  • extension: reports/mutation/extension/mutation.html

The workflow uploads generated reports in the changed-code-mutation-report artifact. A direct artifact link appears below after upload.

Advisory findings

  • extension Stryker preflight failed: 19:28:03 (2931) INFO ProjectReader Found 2 of 1453 file(s) to be mutated. 19:28:03 (2931) INFO Instrumenter Instrumented 2 source file(s) with 52 mutant(s) 19:28:03 (2931) INFO ConcurrencyTokenProvider Creating 2 test runner process(es). 19:28:05 (2931) INFO DryRunExecutor Note: running the dry-run only. No mutations will be tested. 19:28:05 (2931) INFO DryRunExecutor Starting initial test run (vitest test runner with "perTest" coverage analysis). This may take a while. 19:30:44 (2931) ERROR DryRunExecutor One or more tests failed in the initial test run: coding eval host command boundary rejects an outside-workspace git diff in clamp-range before command execution Cannot find module '../../../../scripts/agent-evals/coding-fixtures' imported from /home/runner/work/Zoo-Code/Zoo-Code/.stryker-tmp/sandbox-wHuT4C/core/tools/__tests__/coding-eval-boundary.spec.ts 19:30:44 (2931) ERROR Stryker There were failed tests in the initial test run. file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/process/3-dry-run-executor.js:65 throw new ConfigError('There were failed tests in the initial test run.'); ^ ConfigError: There were failed tests in the initial test run. at DryRunExecutor.validateResultCompleted (file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/process/3-dry-run-executor.js:65:27) at DryRunExecutor.executeDryRun (file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/process/3-dry-run-executor.js:100:14) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async WorkItem.execute (file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/concurrent/pool.js:32:28) at async file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/concurrent/pool.js:69:13 { innerError: undefined } Node.js v22.23.4

@github-actions github-actions Bot added coderabbit-review-active Required CI passed; CodeRabbit review is active awaiting-coderabbit Waiting for CodeRabbit to approve the latest commit labels Nov 30, 2026
coderabbitai[bot]
coderabbitai Bot previously approved these changes Nov 30, 2026
@github-actions github-actions Bot added awaiting-maintainer CodeRabbit approved; waiting for a human maintainer and removed coderabbit-review-active Required CI passed; CodeRabbit review is active awaiting-coderabbit Waiting for CodeRabbit to approve the latest commit labels Nov 30, 2026

@edelauna edelauna left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome, thanks for adding this, locally I benchmarked this to reduce heap from 90 -> 7mb 🚀

I just had 2 comments, more to help me understand the implementation and act as a guarantee to prevent any regressions.

Once addressed can you re-request my review.

Comment on lines +97 to +98
it.each([() => {}, Symbol("uncloneable")])("preserves native clone errors for unsupported values", (value) => {
expect(() => snapshotHistory({ value })).toThrow()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These cases only assert .toThrow(). Would they still pass if the internal sentinel Symbol leaked out of snapshotHistory? Could we assert expect.objectContaining({ name: "DataCloneError" }) and add %s to the title so each case has its own name?


it("preserves null prototypes and safely copies an own __proto__ property", () => {
const original = JSON.parse('{"__proto__":{"polluted":true},"text":"legacy"}') as Record<string, unknown>
Object.setPrototypeOf(original, null)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

setPrototypeOf(original, null) makes this a null-prototype case. A plain snapshot[key] = copy(...) would still pass here, because a null-prototype object has no __proto__ setter. Could we add a case with a normal-prototype object from JSON.parse('{"__proto__":...}')?

@github-actions github-actions Bot added awaiting-author PR is waiting for the author to address requested changes and removed awaiting-maintainer CodeRabbit approved; waiting for a human maintainer labels Dec 2, 2026
@cartridgebasic

Copy link
Copy Markdown
Contributor Author

Thanks for running the benchmark. Both test changes make sense. I’ll give each failure case its own name and check for DataCloneError explicitly so a leaked internal Symbol fails the test. I’ll also add a JSON.parse case where a regular object has its own __proto__ property. I’ll re-request your review once both changes are in.

@github-actions github-actions Bot removed the awaiting-author PR is waiting for the author to address requested changes label Dec 2, 2026
@github-actions github-actions Bot added coderabbit-review-active Required CI passed; CodeRabbit review is active awaiting-coderabbit Waiting for CodeRabbit to approve the latest commit labels Dec 2, 2026
@github-actions github-actions Bot added awaiting-maintainer CodeRabbit approved; waiting for a human maintainer and removed coderabbit-review-active Required CI passed; CodeRabbit review is active awaiting-coderabbit Waiting for CodeRabbit to approve the latest commit labels Dec 2, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting-maintainer CodeRabbit approved; waiting for a human maintainer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Saving a large conversation can exhaust the extension host heap

2 participants