Repository navigation
agent: Materialize tool-call diffs lazily, on first view - #65444
Conversation
Restoring a thread eagerly built a diff for every edit in its history. `Diff::finalized` created a buffer holding the whole post-edit file, set a language and waited for a full tree-sitter parse (`parsing_idle().await`), and `EntryViewState` built a diff editor and terminal view for every tool call regardless of whether its card was shown. On long, tool-heavy threads this materialized the entire edit history on open, producing multi-GiB resident-memory spikes. Profiled on a real 44-thread store (debug build, sampling LD_PRELOAD heap profiler): ~1.26 GiB in tree-sitter syntax trees and ~3.0 GiB anonymous memory attributable to merely opening a thread, driven by `Buffer::reparse` / `SyntaxSnapshot::reparse` under `edit_session::replay_output -> Diff::finalized` (i.e. agent replay of past edits, not the UI widgets). Make tool-call content materialize only when its card is shown: - `EntryViewState::sync_entry` no longer builds diff/terminal views for tool calls whose content is not visible. A restored thread syncs its history with `sync_entry_initial`, which skips them; expanding a card re-syncs that entry to build its views on demand. - `acp_thread::Diff::finalized` now stores only the diff source (path + old/new text). The buffer, rope, multibuffer and tree-sitter parse are built by a new `Diff::resolve`, invoked from `AcpThread::resolve_tool_call_diffs` when the card first becomes visible. `Diff::resolve` is idempotent and accessors that can be reached before a diff is resolved (`to_markdown`, `has_revealed_range`) handle the unresolved case. Measured on the same profile: anonymous memory after load dropped from ~3.0 GiB to 478 MiB and tree-sitter from ~1.26 GiB to ~7 MiB; opening a second thread kept tree-sitter ~6 MiB (only the expanded card's diff parses, on demand). Covered by `cargo test -p acp_thread` (270) and `cargo test -p agent_ui` (515), all passing.
Resident-memory measurementChart: vanilla stable vs a build with both changes — this PR plus the companion
≈ 2.5× less resident, ≈ 2.9× less anonymous. File-backed is essentially This PR's own effect is the diff/tree-sitter half: tree-sitter allocations Both instances had the same project open when sampled. Companion PR
Related reportsagent/thread memory
same symptom, different root cause (not addressed here)
|
SomeoneToIgnore
left a comment
There was a problem hiding this comment.
Left a few comments on top of CI findings.
- A finalized diff that is built eagerly (`PendingDiff::finalize`) no longer retains the full file text: the deferred source (`new_text` + language registry) now lives in an `Option` consumed by `resolve`, and is `None` when the diff is already resolved. Previously every retained live edit kept a full copy of its new text (e.g. ~1 GiB for 128 edits of an 8 MiB file). - Expanding a tool-call card now materializes its views without re-running the terminal lifecycle, so expanding a card whose process is still running is no longer collapsed again by `TerminalMovedToBackground`. - Remove a redundant `path.clone()` (clippy::redundant_clone).
|
Addressed the review: You could no longer keep a running command's card open. Some tool cards are for a command that has finished but whose program is still running in the background, and Zed deliberately tucks those away. Because expanding a card re-ran the card's setup, that "tuck away finished background commands" rule fired again — so the card would slam shut the instant you opened it. Expanding now only builds the missing pieces and does not re-run that rule, so the card stays open. A full copy of each file version was kept for nothing. To show a diff, Zed sometimes keeps a copy of the "after" version of the file. For the diffs we now build immediately, we were still making that copy and then never using it — in your example, ~1 GB for 128 edits of an 8 MB file. That copy is now kept only while it's genuinely still needed and dropped the moment it's been used; diffs that are already built don't make it at all. Lint. Removed the pointless duplication Verified locally: |
SomeoneToIgnore
left a comment
There was a problem hiding this comment.
While we are at it, please also tidy up the comments as those are overly LLM-esque and verbose (unlike this repo's style).
|
Adding an independent heap-level measurement from macOS that lines up with your root cause. Environment: Zed Preview 1.24.2 (630334a), macOS 26.0.1, Apple Silicon, 24 GB RAM. One ACP agent thread (Claude Code), 3 projects open, 30 live worktrees. Peak: after ~5 h the Zed main process reached 75.6 GB physical footprint. At the same instant
Two size classes are ~98% of it, and no ObjC/Swift objects are involved (those total a few MB):
A single fixed-size allocation shape, not scattered leakage. Corroborating foreground hangs in the same session ( Those are the One caveat for your numbers: your profile is ~3.0 GiB anon for a 44-thread store; this instance reached 75.6 GB from a single thread. Either the edit history is far larger, or there is a second accumulation channel on top of the one this PR closes. Happy to re-run with |
|
@Baike12 Could you measure memory usage on fresh zed instance with historic threads opened? Does it still use 75GB? |
`Diff::to_markdown` exported the retained new text for a diff that had not been built, so a thread's markdown changed depending on whether its card had been opened. Reproduce the resolved output from the source text instead. Also shortens the comments added by the previous commit.
|
Done in Also shortened the comments. |
`BufferDiff::set_base_text` normalizes the base text, so line-ending-only edits are not hunks. The deferred export compared the normalized new text against the raw base, which made an unchanged CRLF file export its full text before resolution and nothing after it. Compare both sides normalized.
|
Tests caught a bug in line ending normalization. Please retrigger |
|
Some clarifications:
The ProblemRestoring a thread used to finalize every tool-call diff eagerly. A collapsed card really only needs two things: its path and its markdown text. Render state is only needed once an editor is actually shown. Live edits are a different case — The InvariantA restored diff keeps only the source text it needs to export. Render state is built on first view, and building it must not change the transcript.
flowchart LR
Start(( )) --> Live
Live["PendingDiff<br/>(live edit)"]
Unresolved["FinalizedDiff<br/>(unresolved)"]
Resolved["FinalizedDiff<br/>(resolved)"]
Unresolved -->|"Diff::resolve()<br/>on first view"| Resolved
Live -->|"PendingDiff::finalize()"| Resolved
Resolved --> End(( ))
classDef live fill:#2d2210,stroke:#e3b341,stroke-width:1.5px,color:#e3b341
classDef unresolved fill:#0d1b24,stroke:#39c5cf,stroke-width:1.5px,color:#39c5cf
classDef resolved fill:#0f2417,stroke:#3fb950,stroke-width:1.5px,color:#3fb950
class Live live
class Unresolved unresolved
class Resolved resolved
Note the one-way transition: once SequencesequenceDiagram
autonumber
participant T as AcpThread
participant D as Diff
participant E as EntryViewState
participant V as ThreadView
Note over T,D: Restore
T->>D: Diff::finalized(path, old_text, new_text)
D->>D: Store base_text and DeferredSource
V->>E: sync_entry_initial(index)
Note over E: Collapsed tool call skipped, view ids recorded
Note over V,D: Expand
V->>E: materialize_entry(index)
E->>T: resolve_tool_call_diffs(index)
T->>D: resolve()
D->>D: Buffer, MultiBuffer, language, BufferDiff
E->>V: create_editor_diff
Note over T,D: Export at any time
T->>D: to_markdown()
alt Unresolved
D->>D: export_before_resolve()
else Resolved
D->>D: multibuffer buffers
end
The Fix
Review follow-ups
|
Shorten the deferred-diff comments, rename the expansion materialization helper, and replace the two sync booleans with a three-mode enum.
Derive canceled-edit changes from the deferred diff instead of the editor, and resolve on discard so a restored collapsed card keeps its warning and discard action.
Track the view ids skipped during restore so a later sync materializes them without emitting NewDiff or NewTerminal.
Read the resolved new buffer until the async multibuffer build completes so has_changes and to_markdown cannot observe an empty pending state.





Summary
Restoring a thread materialized the diff of every edit in its history, whether or not the card had ever been shown. On long, tool-heavy threads that meant multi-GiB memory spikes just from opening a thread.
Two eager paths on restore:
EntryViewState::sync_entrybuilt a diffEditorand aTerminalViewfor every tool call in the history.acp_thread::Diff::finalizedcreated aBuffer::local(new_text)holding the whole post-edit file, set the language from the file path, and awaitedparsing_idle(), retaining the parsed buffer inFinalizedDiff.Profiling a real 44-thread store (debug build, isolated
LD_PRELOADheap profiler instrumenting only thezedprocess) attributed ~1.26 GiB to tree-sitter syntax trees and ~3.0 GiB anon to opening a thread, with the dominant stacks underBuffer::reparse/SyntaxSnapshot::reparse_with_rangesreached fromDiff::finalized. The diff-editor and terminal widgets were a negligible part of it.Diffs are now built on first view:
EntryViewState::sync_entryno longer builds diff and terminal content views for tool calls whose content is not visible. The history-restore loop callssync_entry_initial, and expanding a card re-syncs that entry to build its views.acp_thread::Diff::finalizedstores only the diff source (path,old_text,new_text). The buffer, rope, multibuffer and tree-sitter parse are built byDiff::resolve, called fromAcpThread::resolve_tool_call_diffs(index, cx)when the card first becomes visible.resolveis idempotent, and the accessors reachable before resolution (to_markdown,has_revealed_range) handle the unresolved case.Same isolated profile, same 44 threads,
MPROF_MIN=4096 MPROF_SAMPLE=64:Pss_Anonafter loadRssOpening a second thread kept tree-sitter at ~6 MiB, and expanding one card built only the diff for that card (~12 MiB), so the work is now proportional to what is shown.
Companion PR: #65470 parses thread markdown lazily, on first render. With both changes the same profile goes from 3003 to 1199 MiB
VmRSS, and anonymous memory from 2724 to 934 MiB.Still eager on restore, and left for follow-ups: markdown parsing of assistant messages (~245 MiB over two threads),
serde_jsondeserialize andValue::cloneof the thread payload (~276 MiB), mermaid rasterization (~59 MiB), and the same lazy treatment forDiffPatchhunks.Related reports: #65465, #62133, #63720, #59402, #60793, #57478, #57126, #61026, #50889.
Testing
cargo check -p agent_uicargo test -p acp_threadcargo test -p agent_uiRelease Notes: