From e946213e3a3474cd5c5aa964eabd7a6aa843463d Mon Sep 17 00:00:00 2001 From: cartridgebasic <68982521+cartridgebasic@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:20:04 -0700 Subject: [PATCH 1/2] Reduce memory used to save conversation history Share immutable strings while copying mutable transcript containers. Use a native clone for the full graph when a legacy value needs it. Refs #2721 --- .../__tests__/historySnapshot.spec.ts | 104 ++++++++++++++ src/core/task-persistence/historySnapshot.ts | 51 +++++++ src/core/task/Task.ts | 5 +- .../task/__tests__/Task.persistence.spec.ts | 128 ++++++++++++++++++ 4 files changed, 286 insertions(+), 2 deletions(-) create mode 100644 src/core/task-persistence/__tests__/historySnapshot.spec.ts create mode 100644 src/core/task-persistence/historySnapshot.ts diff --git a/src/core/task-persistence/__tests__/historySnapshot.spec.ts b/src/core/task-persistence/__tests__/historySnapshot.spec.ts new file mode 100644 index 00000000000..6467c9eab68 --- /dev/null +++ b/src/core/task-persistence/__tests__/historySnapshot.spec.ts @@ -0,0 +1,104 @@ +import { describe, expect, it, vi } from "vitest" +import { snapshotHistory } from "../historySnapshot" + +describe("snapshotHistory", () => { + it("copies nested JSON containers without native string-copy serialization", () => { + const native = vi.spyOn(globalThis, "structuredClone") + try { + const original = [{ text: "large immutable payload".repeat(10000), blocks: [{ values: [1, null, true] }] }] + const snapshot = snapshotHistory(original) + expect(snapshot).toEqual(original) + original[0].blocks[0].values.push(2) + expect(snapshot[0].blocks[0].values).toEqual([1, null, true]) + expect(native).not.toHaveBeenCalled() + } finally { + native.mockRestore() + } + }) + + it("preserves aliases and cycles while isolating the graph", () => { + const shared = { entries: ["first"] } + const original: { left: typeof shared; right: typeof shared; self?: unknown } = { left: shared, right: shared } + original.self = original + const snapshot = snapshotHistory(original) + expect(snapshot.left).toBe(snapshot.right) + expect(snapshot.left).not.toBe(shared) + expect(snapshot.self).toBe(snapshot) + }) + + it("preserves holes, explicit undefined, extra array properties and primitive values", () => { + const original = new Array(5) + original[2] = undefined + original[4] = { number: NaN, big: 123n, zero: -0 } + Object.defineProperty(original, "extra", { value: { label: "legacy" }, enumerable: true }) + const snapshot = snapshotHistory(original) + expect(snapshot).toEqual(original) + expect(snapshot.length).toBe(5) + expect(0 in snapshot).toBe(false) + expect(2 in snapshot).toBe(true) + expect(Object.getOwnPropertyDescriptor(snapshot, "extra")?.value).not.toBe( + Object.getOwnPropertyDescriptor(original, "extra")?.value, + ) + }) + + it("preserves null prototypes and safely copies an own __proto__ property", () => { + const original = JSON.parse('{"__proto__":{"polluted":true},"text":"legacy"}') as Record + Object.setPrototypeOf(original, null) + const snapshot = snapshotHistory(original) + expect(Object.getPrototypeOf(snapshot)).toBe(null) + expect(Object.hasOwn(snapshot, "__proto__")).toBe(true) + expect(snapshot["__proto__"]).toEqual({ polluted: true }) + expect(snapshot["__proto__"]).not.toBe(original["__proto__"]) + expect(Object.getPrototypeOf(snapshot["__proto__"])).toBe(Object.prototype) + }) + + it("falls back for the whole graph so special objects can refer back into plain containers", () => { + const shared = { values: ["first"] } + const buffer = new ArrayBuffer(8) + const original: { + shared: typeof shared + map: Map + set: Set + date: Date + buffer: ArrayBuffer + view: Uint8Array + } = { + shared, + map: new Map([[shared, shared]]), + set: new Set([shared]), + date: new Date(1234), + buffer, + view: new Uint8Array(buffer), + } + original.map.set("root", original) + const snapshot = snapshotHistory(original) + expect(snapshot).toEqual(structuredClone(original)) + expect(snapshot.map.get(snapshot.shared)).toBe(snapshot.shared) + expect(snapshot.map.get("root")).toBe(snapshot) + expect(snapshot.set.has(snapshot.shared)).toBe(true) + expect(snapshot.view.buffer).toBe(snapshot.buffer) + expect(snapshot.buffer).not.toBe(buffer) + shared.values.push("changed") + expect(snapshot.shared.values).toEqual(["first"]) + }) + + it("uses native handling for accessors without evaluating a getter twice", () => { + const getter = vi.fn(() => ({ text: "value" })) + const original = { + get field() { + return getter() + }, + date: new Date(0), + } + expect(snapshotHistory(original)).toEqual({ field: { text: "value" }, date: new Date(0) }) + expect(getter).toHaveBeenCalledTimes(1) + }) + + it.each([() => {}, Symbol("uncloneable")])("preserves native clone errors for unsupported values", (value) => { + expect(() => snapshotHistory({ value })).toThrow() + }) + + it("does not treat a proxy as a plain serializable record", () => { + expect(() => snapshotHistory({ value: new Proxy({ text: "value" }, {}) })).toThrow() + }) +}) diff --git a/src/core/task-persistence/historySnapshot.ts b/src/core/task-persistence/historySnapshot.ts new file mode 100644 index 00000000000..0b48ee396ac --- /dev/null +++ b/src/core/task-persistence/historySnapshot.ts @@ -0,0 +1,51 @@ +import { types } from "node:util" + +const nativeCloneRequired = Symbol("native history snapshot required") + +function clonePlainHistory(value: unknown): unknown { + const seen = new WeakMap() + const copy = (current: unknown): unknown => { + if (typeof current === "function" || typeof current === "symbol") throw nativeCloneRequired + if (current === null || typeof current !== "object") return current + if (types.isProxy(current)) throw nativeCloneRequired + const previous = seen.get(current) + if (previous !== undefined) return previous + + const prototype: unknown = Object.getPrototypeOf(current) + if (!Array.isArray(current) && prototype !== Object.prototype && prototype !== null) throw nativeCloneRequired + const snapshot: object = Array.isArray(current) + ? new Array(current.length) + : prototype === null + ? Object.create(null) + : {} + seen.set(current, snapshot) + for (const key of Object.keys(current)) { + const descriptor = Object.getOwnPropertyDescriptor(current, key) + // Native cloning handles accessors once, rather than evaluating them in + // this pass and evaluating them again if a later property needs fallback. + if (!descriptor || !("value" in descriptor)) throw nativeCloneRequired + Object.defineProperty(snapshot, key, { + value: copy(descriptor.value), + enumerable: true, + configurable: true, + writable: true, + }) + } + return snapshot + } + return copy(value) +} + +/** Isolate JSON history's mutable containers without copying immutable string payloads. */ +export function snapshotHistory(value: T): T { + try { + // Every supported container is rebuilt, preserving the input's graph/type. + return clonePlainHistory(value) as T + } catch (error) { + if (error !== nativeCloneRequired) throw error + // Clone the WHOLE graph for non-JSON legacy/provider data. Cloning special + // objects separately would break aliases/cycles crossing Maps, Sets or views. + // The plain-clone frame has unwound, releasing its partial snapshot first. + return structuredClone(value) + } +} diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 3b2771ddfa7..f0fd1576b17 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -6,6 +6,7 @@ import { v7 as uuidv7 } from "uuid" import EventEmitter from "events" import { AskIgnoredError } from "./AskIgnoredError" +import { snapshotHistory } from "../task-persistence/historySnapshot" import { RateLimitClock, createRateLimitClock } from "./RateLimitClock" import { Anthropic } from "@anthropic-ai/sdk" @@ -1641,7 +1642,7 @@ export class Task extends EventEmitter implements TaskLike { private async saveApiConversationHistory(merge = true): Promise { try { await saveApiMessages({ - messages: structuredClone(this.apiConversationHistory), + messages: snapshotHistory(this.apiConversationHistory), taskId: this.taskId, globalStoragePath: this.globalStoragePath, merge, @@ -1846,7 +1847,7 @@ export class Task extends EventEmitter implements TaskLike { private async saveClineMessages(merge = true): Promise { try { await saveTaskMessages({ - messages: structuredClone(this.clineMessages), + messages: snapshotHistory(this.clineMessages), taskId: this.taskId, globalStoragePath: this.globalStoragePath, merge, diff --git a/src/core/task/__tests__/Task.persistence.spec.ts b/src/core/task/__tests__/Task.persistence.spec.ts index 86df5615db1..1b95d41e5a1 100644 --- a/src/core/task/__tests__/Task.persistence.spec.ts +++ b/src/core/task/__tests__/Task.persistence.spec.ts @@ -307,6 +307,134 @@ describe("Task persistence", () => { }) // ── saveApiConversationHistory (via retrySaveApiConversationHistory) ── + describe.each(["UI", "API"] as const)("%s history snapshot isolation", (kind) => { + function fixture() { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "snapshot isolation", + startTask: false, + }) + const legacy = { nested: { chunks: ["initial"] } } + const message = + kind === "UI" + ? { type: "say" as const, say: "reasoning" as const, ts: 1, text: "thinking", legacy } + : { role: "assistant" as const, content: [{ type: "text" as const, text: "response" }], legacy } + if (message.role === "assistant") task.apiConversationHistory.push(message) + else task.clineMessages.push(message) + return { + task, + legacy, + mock: kind === "UI" ? mockSaveTaskMessages : mockSaveApiMessages, + save: () => (kind === "UI" ? task["saveClineMessages"]() : task["saveApiConversationHistory"]()), + } + } + + it("takes isolated, ordered nested snapshots even while another save is pending", async () => { + const { legacy, mock, save } = fixture() + const gate = createDeferred() + const snapshots: unknown[][] = [] + mock.mockImplementation(async ({ messages }: { messages: unknown[] }) => { + snapshots.push(messages) + await gate.promise + return messages + }) + try { + const first = save() + legacy.nested.chunks.push("second") + const second = save() + legacy.nested.chunks.push("after both calls") + expect(snapshots).toHaveLength(2) + expect(snapshots[0]).toEqual([expect.objectContaining({ legacy: { nested: { chunks: ["initial"] } } })]) + expect(snapshots[1]).toEqual([ + expect.objectContaining({ legacy: { nested: { chunks: ["initial", "second"] } } }), + ]) + expect(snapshots[0]).not.toBe(snapshots[1]) + gate.resolve() + expect(await Promise.all([first, second])).toEqual([true, true]) + expect(mock).toHaveBeenNthCalledWith(1, expect.objectContaining({ merge: true })) + expect(mock).toHaveBeenNthCalledWith(2, expect.objectContaining({ merge: true })) + } finally { + gate.resolve() + mock.mockReset().mockResolvedValue([]) + } + }) + + it("retries a failed save with a fresh snapshot without changing the failed snapshot", async () => { + const { legacy, mock, save } = fixture() + const snapshots: unknown[][] = [] + mock.mockImplementationOnce(async ({ messages }: { messages: unknown[] }) => { + snapshots.push(messages) + throw new Error("disk unavailable") + }) + mock.mockImplementationOnce(async ({ messages }: { messages: unknown[] }) => { + snapshots.push(messages) + return messages + }) + expect(await save()).toBe(false) + legacy.nested.chunks.push("retry") + expect(await save()).toBe(true) + expect(snapshots[0]).toEqual([expect.objectContaining({ legacy: { nested: { chunks: ["initial"] } } })]) + expect(snapshots[1]).toEqual([ + expect.objectContaining({ legacy: { nested: { chunks: ["initial", "retry"] } } }), + ]) + }) + + it("preserves references crossing special legacy objects through the actual save", async () => { + const { legacy, mock, save } = fixture() + const extended = Object.assign(legacy, { special: new Map() }) + extended.special.set("parent", extended) + mock.mockImplementationOnce(async ({ messages }: { messages: Array<{ legacy: typeof extended }> }) => { + const saved = messages[0].legacy + expect(saved).not.toBe(extended) + expect(saved.special.get("parent")).toBe(saved) + extended.nested.chunks.push("changed while saving") + expect(saved.nested.chunks).toEqual(["initial"]) + return messages + }) + expect(await save()).toBe(true) + }) + }) + + it("API backoff retries snapshot nested history again after a failed attempt", async () => { + vi.useFakeTimers() + try { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "retry", + startTask: false, + }) + const toolInput = { chunks: ["initial"] } + task.apiConversationHistory.push({ + role: "assistant", + content: [{ type: "tool_use", id: "call", name: "write_to_file", input: toolInput }], + }) + const snapshots: unknown[][] = [] + mockSaveApiMessages.mockImplementationOnce(async ({ messages }: { messages: unknown[] }) => { + snapshots.push(messages) + toolInput.chunks.push("retry") + throw new Error("temporary write failure") + }) + mockSaveApiMessages.mockImplementationOnce(async ({ messages }: { messages: unknown[] }) => { + snapshots.push(messages) + return messages + }) + const saved = task.retrySaveApiConversationHistory() + await vi.runAllTimersAsync() + expect(await saved).toBe(true) + expect(snapshots[0]).toEqual([ + expect.objectContaining({ content: [expect.objectContaining({ input: { chunks: ["initial"] } })] }), + ]) + expect(snapshots[1]).toEqual([ + expect.objectContaining({ + content: [expect.objectContaining({ input: { chunks: ["initial", "retry"] } })], + }), + ]) + } finally { + vi.useRealTimers() + } + }) describe("saveApiConversationHistory", () => { it("returns true on success", async () => { From 64f11987d40c22152daa80b015a12d7ee0581218 Mon Sep 17 00:00:00 2001 From: cartridgebasic <68982521+cartridgebasic@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:17:19 -0700 Subject: [PATCH 2/2] Strengthen history snapshot regression tests --- .../__tests__/historySnapshot.spec.ts | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/core/task-persistence/__tests__/historySnapshot.spec.ts b/src/core/task-persistence/__tests__/historySnapshot.spec.ts index 6467c9eab68..106747b645b 100644 --- a/src/core/task-persistence/__tests__/historySnapshot.spec.ts +++ b/src/core/task-persistence/__tests__/historySnapshot.spec.ts @@ -41,11 +41,14 @@ describe("snapshotHistory", () => { ) }) - it("preserves null prototypes and safely copies an own __proto__ property", () => { + it.each([ + ["normal", Object.prototype], + ["null", null], + ] as const)("safely copies an own __proto__ property with a %s prototype", (_label, prototype) => { const original = JSON.parse('{"__proto__":{"polluted":true},"text":"legacy"}') as Record - Object.setPrototypeOf(original, null) + if (prototype === null) Object.setPrototypeOf(original, null) const snapshot = snapshotHistory(original) - expect(Object.getPrototypeOf(snapshot)).toBe(null) + expect(Object.getPrototypeOf(snapshot)).toBe(prototype) expect(Object.hasOwn(snapshot, "__proto__")).toBe(true) expect(snapshot["__proto__"]).toEqual({ polluted: true }) expect(snapshot["__proto__"]).not.toBe(original["__proto__"]) @@ -94,11 +97,11 @@ describe("snapshotHistory", () => { expect(getter).toHaveBeenCalledTimes(1) }) - it.each([() => {}, Symbol("uncloneable")])("preserves native clone errors for unsupported values", (value) => { - expect(() => snapshotHistory({ value })).toThrow() - }) - - it("does not treat a proxy as a plain serializable record", () => { - expect(() => snapshotHistory({ value: new Proxy({ text: "value" }, {}) })).toThrow() + it.each([ + ["function", () => {}], + ["symbol", Symbol("uncloneable")], + ["proxy", new Proxy({ text: "value" }, {})], + ] as const)("preserves DataCloneError for an unsupported %s", (_label, value) => { + expect(() => snapshotHistory({ value })).toThrow(expect.objectContaining({ name: "DataCloneError" })) }) })