The whole thread is re-serialized and written to SQLite several times per second while a response streams
Reproduction steps
Agent panel: the whole thread is re-serialized and written to SQLite several times per second while a response streams
Category: Agent / Performance
TL;DR
While the agent is streaming a response, NativeAgent snapshots the entire thread, serializes it to JSON, zstd-compresses it and rewrites the SQLite row on nearly every UI notify of the Thread entity. The streaming text is not even part of that snapshot (it sits in pending_message until the message completes), so every one of those mid-stream writes is byte-identical to the previous one. For a 4 MB thread that is roughly 20 MiB of allocations per write and a 1 MB SQLite write, repeated as fast as the DB thread can keep up. On long threads with a local model this shows up as constant allocator churn, disk writes and a slowly worsening RAM profile during generation.
I am thinking about how this could be fixed .. it does not seem to be a well behaving so far.
What I observed
I run Zed with a local llama.cpp backend, so threads get long and generation is slow (30-40 tok/s). On long threads I noticed RSS creeping up during generation and a lot of write traffic on the disk that hosts threads.db. I added an allocation-attributing counting allocator to my build to find out where the churn comes from. During a 60 s window of pure streaming on a ~4 MB thread:
| what | allocated in 60 s |
|---|---|
thread persistence write path (ThreadsDatabase::save_thread) |
~925 MB - 1.1 GB |
| markdown reveal / re-parse | ~4.5 MB |
| the streamed text itself | ~10 KB |
That was already with a 1.5 s debounce in front of the save worker, i.e. about 40 saves per minute. Upstream has no debounce at all, so the real number is higher.
Why it happens
Everything below is from crates/agent/src/agent.rs and crates/agent/src/thread.rs on current main (v1.23).
The save is driven by
cx.observe, not by a "something durable changed" signal. When a session is created, the agent registerscx.observe(&thread_handle, move |this, thread, cx| { this.save_thread(thread, cx) }),so every
cx.notify()on theThreadentity turns into a save request.The turn loop notifies on every batch of completion events.
handle_text_event/handle_thinking_eventthemselves do not notify, but the loop inrun_turndrains the events that are currently available, processes them in onethis.update(...), and ends that update with an unconditionalcx.notify(). With a provider that delivers one SSE chunk per token that is one notify per token; with any batching it is one notify per batch. Either way it is many per second for the whole duration of the response.Each save request snapshots the whole thread.
save_thread->thread_save_payload->Thread::to_dbbuilds aDbThreadwithmessages: self.messages.clone()and puts it into a single "latest wins" slot for the save worker. The worker takes the slot and callsThreadsDatabase::save_thread, which doeslet json_data = serde_json::to_string(&SerializedThread { thread, version })?; let compressed = zstd::encode_all(json_data.as_bytes(), COMPRESSION_LEVEL)?; // INSERT ... ON CONFLICT(id) DO UPDATE SET data = excluded.data ...i.e. full JSON string of the whole message log, then a second full buffer for the compressed blob, then the SQLite upsert. Afterwards it also calls
thread_store.reload(cx), which re-reads the thread list from the DB.The slot coalesces requests that arrive while a write is in flight, so the effective write rate is
min(notify rate, DB throughput). It is not literally one write per token, but it is "as many whole-thread writes as the DB thread can do", for the entire generation.The snapshot does not contain what is being streamed. The text being generated lives in
Thread::pending_messageand is only pushed intoself.messagesbyflush_pending_messagewhen the message ends (stop, tool use, nextStartMessage).to_dbreadsself.messagesonly.updated_atis also only bumped inflush_pending_message. So between two flushes, every snapshot serializes to exactly the same bytes as the one before it. All of that work produces nothing.Cost per write. For a 4 MB thread I measured ~22 MiB of allocations per save: the
Stringfromserde_json::to_stringgrows by doubling, thenzstd::encode_allallocates the output buffer, then theVec<u8>is moved into the SQLite binding. Multiply by the write rate and you get the numbers above.
What can be done short-term?
I would keep the current "snapshot the whole thread" model (an incremental schema is a much bigger change) and fix the two things that are clearly wrong.
Current vs. Expected behavior
Current vs. Expected behavior
Current behavior
While the agent is streaming a response, NativeAgent snapshots the whole Thread, serializes it to JSON, zstd-compresses it and rewrites the row in threads.db on every UI notify of the thread entity. The turn loop in Thread::run_turn calls cx.notify() once per batch of completion events, so this happens many times per second for the entire duration of the response. The save worker coalesces requests that arrive while a write is in flight, so the effective rate is "as many whole-thread writes as the DB thread can complete", not one per token, but on a 4 MB thread that is still several per second.
None of those writes carry new information. The text being generated lives in Thread::pending_message and is only pushed into Thread::messages by flush_pending_message when the message completes (stop, tool use, or the next StartMessage). Thread::to_db reads self.messages only and updated_at is also only bumped in flush_pending_message. Between two flushes every snapshot serializes to exactly the same bytes as the previous one.
Measured with an allocation-attributing counting allocator in a local build, 60 s of pure streaming on a ~4 MB thread (local llama.cpp model, ~35 tok/s):
| Path | Allocated in 60 s |
|---|---|
ThreadsDatabase::save_thread (JSON + zstd + SQLite upsert) |
~925 MB to 1.1 GB |
| Markdown reveal / re-parse in the panel | ~4.5 MB |
| The streamed text itself | ~10 KB |
That run already had a 1.5 s debounce in front of the save worker (about 40 saves per minute). Upstream has no debounce, so the real number is higher. Each save allocates roughly 22 MiB for a 4 MB thread: the String from serde_json::to_string grows by doubling, then zstd::encode_all allocates a second full buffer, then the blob is moved into the SQLite binding. After each save the worker also calls thread_store.reload(cx), which re-reads the thread list from the DB.
Visible effect: constant allocator churn and disk writes during generation, RSS creeping up over long threads, and the persistence path dwarfing everything else the panel does while streaming.
Expected behavior
The thread should only be persisted when something durable changed: a message completed, a tool result landed, the title, draft prompt, scroll position or model settings changed, or the app is quitting. Streaming deltas should not trigger a save at all, because the snapshot cannot contain them anyway. When a save does happen, it should not need an intermediate multi-megabyte JSON string; the serializer can stream straight into the zstd encoder.
Steps to reproduce
- Open the agent panel with any provider. A slow local model (llama.cpp, Ollama) makes it easiest to see, but the mechanism is provider-independent.
- Build up a thread of a few MB (long conversation, a few large tool results).
- Send a prompt that produces a long response and watch
%LOCALAPPDATA%\Zed\db\...\threads.db(or the platform equivalent) and process RSS while it streams. The DB file's modification time updates continuously and write volume tracks generation time, not message count. - Optionally add a counter in
ThreadsDatabase::save_threadand log it: it increments throughout the stream, and a hex dump of the stored blob is identical between consecutive writes until the message completes.
Where in the code
All on current main (64406cc2a8, v1.23.0):
crates/agent/src/agent.rs: the session subscriptioncx.observe(&thread_handle, |this, thread, cx| this.save_thread(thread, cx))turns every notify into a save request.save_thread->thread_save_payload->Thread::to_dbbuilds theDbThread(clonesself.messages) and stores it in the single "latest wins" slot;run_save_workerdrains the slot and callsThreadsDatabase::save_thread, thenthread_store.reload.crates/agent/src/thread.rs: the batch loop inrun_turnends eachthis.update(...)with an unconditionalcx.notify();handle_text_event/handle_thinking_eventappend topending_message, whichto_dbdoes not read.crates/agent/src/db.rs:save_thread_syncdoesserde_json::to_stringof the wholeDbThread, thenzstd::encode_allon the resulting string, then the upsert.
Proposed fix
I have this working in my fork and can open a PR:
- Add a
durable_generation: u64toThread, bumped via amark_durable_change(cx)helper only at the sites that mutate persisted state (flush_pending_message,process_tool_result, the user-message push insend,set_title, compaction insertion,truncate,set_draft_promptwhen the value differs,set_ui_scroll_position, model/profile/thinking/effort/speed setters).NativeAgent::save_threadcompares it with the last enqueued generation for the session and returns early whileis_running_turn()is true and the generation is unchanged. Idle saves and the quit flush behave exactly as today. - In
save_thread_sync, replaceto_string+encode_allwithserde_json::to_writerinto azstd::Encoder. The stored format does not change. - Tests: fake model streams N text chunks without a stop event, assert zero DB saves; send the stop, assert exactly one. The existing
write_gatetest hook indb.rsis the right seam. Existing persistence tests (draft prompt, quit flush, subagent, compaction) unchanged.
Zed version and system specs
Zed version and system specs
Zed: v1.23.0 (main 64406cc2a8, local build; also reproduced on the fork this was measured with)
OS: Microsoft Windows 11 Pro 10.0.26200 (64-bit)
CPU: Intel Core Ultra 9 275HX (24 cores)
Memory: 191 GiB
GPU: NVIDIA GeForce RTX 5090 Laptop GPU (driver 32.0.16.1074), Intel Graphics (driver 32.0.101.6629)
Agent provider: llama.cpp (OpenAI-compatible, local), ~35 tok/sAttach Zed log file
Zed.logRelevant Zed settings
settings.jsonRelevant Keymap
keymap.json(for AI issues) Model provider details
No response
If you are using WSL on Windows, what flavor of Linux are you using?
None
Source: zed-industries/zed