[Bug] [Analysis and Suggested Remediation] Multi-second stalls between agent steps — 3× snapshot git scans + full session re-load/re-serialize run after every tool round-trip
Component
VS Code extension
Summary
After every agentic step — especially following tool calls — the session engine performs a large
amount of blocking work before the next LLM request is built: two snapshot.track() calls plus
one snapshot.patch() per step (each running 4-5 git subprocesses including full-worktree scans,
serialized behind a cross-process file lock), a full reload of the entire session from SQLite, a
rebuild of all provider messages, and two full JSON.stringify passes over the payload. On Windows
and larger worktrees this adds seconds of dead time per step, which compounds on tool-heavy turns.
Environment
- Kilo Code (opencode session engine,
packages/opencode) - Observed on Windows (process-spawn + worktree-scan costs are amplified there), large worktrees worst
- Every agent/mode; grows with session length and number of tool calls per turn
Reproduction
- Open a session in a reasonably large repository.
- Prompt the agent to do anything requiring several tool calls (e.g. "explore the repo, then edit three files").
- Watch the gap between a tool result appearing and the next request actually being sent — the UI shows the tool finished, then stalls before the model continues.
- The stall repeats after every tool round-trip, and again between user turns.
Root cause (with source references)
All paths below run once per step of the loop in packages/opencode/src/session/prompt.ts
(runLoop → handle.process → cleanup → next iteration).
1. Snapshot git operations — 3× per step (dominant cost)
snapshot.track()atstep-start:packages/opencode/src/session/processor.ts:822-827snapshot.track()again atstep-finish:processor.ts:862-866(the comment literally says "pass turn context for slow-snapshot UI/policy handling")snapshot.patch()incleanup():processor.ts:1098
Each track/patch calls add() (packages/opencode/src/snapshot/index.ts:251-319):
git diff-files --name-only -z -- .— full worktree scangit ls-files --others --exclude-standard -z -- .— full untracked-file scangit check-ignore --stdinover all candidatesgit add --pathspec-from-filestaging- plus a
fs.statper candidate file (index.ts:294-310) andgit write-treeintrack - optionally seed/materialize/pin git ops on first run
Everything serializes behind a cross-process flock on the snapshot gitdir
(snapshot/index.ts:216-217), so CLI/extension processes contend further.
Net: ~14-18 git spawns + 2-3 full-worktree scans per model step, all after the model stops
streaming and before the next request. On Windows, each spawn carries shell/Defender overhead;
on large worktrees the two scans dominate.
2. Full-history reprocessing per step
MessageV2.filterCompactedEffect(sessionID)re-loads the entire session from SQLite every loop iteration (prompt.ts:1498;MessageV2.streampages of 50,message-v2.ts:604-625, JSON-parsing every part viahydrate), even though only the post-summary tail is used.MessageV2.toModelMessagesEffect(msgs, model)rebuilds all provider messages over the full history each step (prompt.ts:1743).Buffer.byteLength(JSON.stringify(modelMsgs))— full payload stringify per step (prompt.ts:1746, thresholdREQUEST_PRUNE_BYTES = 1_250_000, re-stringified if pruned).KiloSessionOverflow.measure()— a second fullJSON.stringifyof messages + tool schemas per request (session/llm.ts:143-144; runs on essentially every request becauseKiloLLM.needsEstimateis true whenevermaxOutputTokensis configured —packages/opencode/src/kilocode/session/llm.ts:36-38; implementation atpackages/opencode/src/kilocode/session/overflow.ts:46-75).
3. Per-step system reassembly (uncached)
instruction.system()re-walksfindUpfor AGENTS.md/CLAUDE.md, globs config instructions, and re-reads every file each step — no cache (packages/opencode/src/session/instruction.ts:129-199).sys.environment()(KiloReference.sync + Reference list),sys.skills()(skill.available), andSessionTools.resolve()(full tool record incl. MCP wrapping + permission merges) re-run per step (prompt.ts:1691-1742). The existingenvCache/memoryCacheonly cover editor-context and memory injection.- Minor: doom-loop detection re-reads all parts from the DB per tool call
(
processor.ts:655-668); tool-future awaits capped at 250 ms in cleanup (processor.ts:1131).
Why it matches "stalls after tool calls"
Tool-heavy turns execute more steps, and each step pays the full pipeline above. The snapshot work
is the worst offender because it runs inside the stream-event handlers and cleanup — i.e., in
the critical path between "tool finished" and "next request sent".
Proposed fixes (highest leverage first)
-
Snapshot once per step, off the critical path
- Drop the
step-finishtrack()—step-startalready holds the before-hash and thecleanup()patch captures the end state. Or fork it detached and publish the patch asynchronously (the part write already tolerates late arrival viaupdatePart). - Deduplicate
add()betweentrackandpatch(same worktree state within one step). - Replace the per-file
fs.statloop with size checks only for untracked candidates, or a singlegit ls-filesvariant that reports sizes.
- Drop the
-
Cache instruction/system reassembly per instance
systemSources()should memoize paths + file contents with watcher-based invalidation instead offindUp/glob/read per step.
-
Reuse history across steps
- Append new messages to the previous slice instead of full
stream()reload + rebuild per iteration (invalidate on compaction/revert/steer). - Share a single stringify between the
REQUEST_PRUNE_BYTESsize check andKiloSessionOverflow.measure()(or reuse provider-reported token counts, already plumbed viareportedContextTokens).
- Append new messages to the previous slice instead of full
-
Extend
envCache(per runLoop) to cover environment/references/skills/tool resolution.
Impact
- Every tool round-trip and every user turn pays a fixed multi-second tax that scales with worktree size and session length.
- Worst on Windows (process spawn cost) and monorepo-scale worktrees.
- Fixing #1 alone removes the bulk of the stall; #2-#4 remove the per-step CPU overhead that grows with session length.
Verification ideas
- Log per-phase timings around
handle.process/cleanup(snapshot vs history reload vs message build) — one run before/after the fixes should show snapshot phases drop from seconds to milliseconds. - Benchmark
snapshot.add()on a 10k+ file worktree before/after de-duplication.
Kilo version
7.8.27
No response
Steps to reproduce
No response
Screenshot and/or share link
No response
Operating System
No response
Terminal
No response
@rome-xi
Thanks for the ping. #16147 looks like a larger performance change (the repeated snapshot git scans and full session reload after every step) than the aborted-turn fix in #16140. I don't want to take that on as a drive-by without a maintainer pointing at a preferred slice. Happy to revisit if you'd like a smaller, testable cut.
Any of them would be good, point 1 in the analysis per the agent should have the largest impact
Thanks for the follow-up. Point 1 (snapshot once per step, off the critical path) still looks like a larger performance change than I should take on without a maintainer pointing at that direction. Happy to pick it up if the team wants it.
I took a look at point 1 and measured it with a git shim that counts snapshot calls in a real prompt.loop. One step on main runs 3 worktree scans: the before-state track in create(), the step-finish track, and patch, which re-runs add() over the same state.
Deriving the step patch from the two recorded trees removes the third scan (3 → 2 per step). But it opens a gap: changes made after the step-finish track, while the step is being persisted, land in no patch, so revert can miss them. Closing that gap safely needs one scan after the last persistence work. Since each agent-loop step is its own assistant message, that brings a typical message back to 3 scans.
The real saving would come from carrying the last step-finish tree into the next message's before-state within one prompt.loop, which drops one scan per message. That changes which patch user or tool edits made between messages land in, so I'd like a maintainer's view before doing it. Happy to implement it, or another of the points in the analysis, if you point me at the direction you prefer.
Host-measurement data for the "full-history reprocessing per step" section, measured on a live Kilo 7.8.32 deployment (WSL2, 16 cores, 20 GB guest, Bun 1.4.4). This is not a new issue — it is evidence for the existing analysis, plus one code path that was not listed and one finding that changes where the memory goes.
Measured cost of the per-step history reload
/proc/<kilo serve pid>/io sampled over 90 s while the daemon was stepping normally:
| Metric | Value |
|---|---|
read_bytes (physical disk reads) |
4186 MiB / 90 s = 46.5 MiB/s |
rchar |
2561 MiB / 90 s = 28.5 MiB/s |
| RSS oscillation | 1.9 GiB -> 7.2 GiB, ~30 s period, each growth phase followed by a ~1.5 GiB swap-out burst in 3 s |
Two active sessions held 29.7 MiB and 53.4 MiB of part JSON. Replaying the exact page() + hydrate() query pair the server uses (message-v2.ts:223-248, pages of 51) against one of them:
| Messages | Parts | Hydrated bytes | Query time | |
|---|---|---|---|---|
| before | 8406 | 31664 | 62.20 MiB | 4.34 s |
| after removing the pre-compaction tail | 8406 | 23936 | 27.81 MiB | 0.33 s |
rchar < read_bytes (28.5 vs 46.5 MiB/s) indicates a large share of the traffic is page-cache re-reads rather than fresh disk reads, i.e. the working set is being re-hydrated rather than the DB being scanned cold.
A second full-session read per step, not listed in the issue
compaction.prune({ sessionID, reason: "normal" }) is forked at prompt.ts:2004 and, because input.messages is not passed, it calls session.messages({ sessionID }) (compaction.ts:317-321) — a second complete hydration of every message and part in the session, every step, in addition to the filterCompactedEffect reload. With the measurements above, that is ~2x the read volume per step. It is gated on config.compaction.prune === true for the "normal" reason (compaction.ts:313), so it is a configuration-dependent second pass rather than an unconditional one.
Where the multi-GiB RSS actually goes (changes the conclusion for GC tuning)
With BUN_JSC_logGC=1 enabled, 428 GC events show the JavaScriptCore heap is bounded: heap median 690 MiB, max 712 MiB, 87% of collections above 500 MiB, median collection 3.5 MiB, 102 collections freeing >10 MiB (max 427 MiB). The JS heap never approaches 7 GiB.
/proc/<pid>/smaps_rollup at the same time: Anonymous 1.87 GiB, Pss_File 31 MiB, and PRAGMA mmap_size is 0 — so the file-backed mapping of the DB is not the cause either. The multi-GiB RSS is native/anonymous memory: allocator arenas, the SQLite page cache inside the process, and the Bun runtime, with the per-step hydration churn driving it.
Practical consequence: BUN_GC_TIMER_DISABLE / idle-GC tuning cannot fix this symptom, because the growth is not retained JS objects. (Bun #48013 measures a real but much smaller effect: ~60 MB higher RSS.) The lever that worked was removing the rows the server reads and then throws away.
The rows that are read and then discarded are the bulk of the traffic
filterCompacted (message-v2.ts:667-719) keeps only a window of history for the model, but the hydration that feeds it loads every row first. For the session above, 30746 of 31664 parts (97%) sit older than the compaction tail and are never sent to the model.
We shipped an out-of-tree mitigation that archives those rows to zstd-compressed JSONL and deletes them, then re-runs the upstream filterCompacted simulation to prove the model-facing message list is unchanged:
| Metric | Before | After |
|---|---|---|
| daemon physical reads | 46.5 MiB/s | 7.0 MiB/s |
| daemon RSS range over 60 s | 1.9 - 7.2 GiB | 1.5 - 4.7 GiB |
| per-step hydration, one session | 62.20 MiB | 27.81 MiB |
This is a workaround, not a fix — it only helps sessions that have already been compacted and are idle. The fix belongs where the issue says: reuse history across steps, and hydrate only what filterCompacted will keep.
One detail for the "reuse history across steps" proposal
The retained set is bounded by the compaction tail, not by age: upstream walks messages newest-first and stops at the first completed compaction, whose tail_start_id marks the first message of the retained window (a compaction whose summary assistant has no finish does not anchor a tail). Any cache keyed on (sessionID, compaction boundary) therefore needs the boundary to mean that exact tail_start_id, and it has to be invalidated when a new compaction lands — including the case where a compaction fails and leaves the previous boundary in place.
Reproduced on Windows 11 x64, Kilo Code 7.8.32 (latest, 2026-11-20). Adding concrete measured data confirming the full session re-load/re-serialize is the dominant cost — on my machine the git-scan part is minor.
Setup: 425 sessions · 30,492 messages · 128,984 parts · 184,549 event rows; 14 git worktrees; ~7 concurrent sessions.
Measured (reproducible):
kilo session list(all 425 sessions, metadata only): 2.52 s- Full materialized-store read + JSON-serialize (event 610 MB + part 441 MB + message 133 MB ≈ 1.18 GB): fetch ~3.2 s + serialize ~4.9 s = ~8 s
- Single-session reload (9 msgs / 40 parts): 6 ms
The cost scales with session count, not transcript size — one small session is 6 ms, but the full-store load is multi-second. That matches the reported 5–10 s UI stall on each tool round-trip.
git ruled out as the primary cause here: across all 14 worktrees, git status avg 51 ms / max 93 ms and git diff avg 43 ms / max 60 ms — so the "3× snapshot scans" of one worktree ≈ 280 ms, a small fraction of the stall. The DB load + JSON serialize dominates.
Also observed during the stall: IPC-dependent controls go unresponsive (stop / continue, new chat) — consistent with #16497.
Notes for remediation:
- No user-facing setting scopes the Agent Manager load or lazy-loads sessions (audited the full
contributes.configuration). - The expensive path runs in the bundled
kilo.exeruntime, not the extension JS. - Store file size is not the factor — I compacted 6.9 GB → 1.15 GB with no change in lag; it's the materialized row count (O(N) over all sessions).
- Size is uniform (top 235 sessions hold 90% of parts), so it's not one oversized session.
Happy to share raw query timings or a kilo export capture if useful.
Thanks for the numbers. One distinction: the per-step history reload in this issue reads a single session, and your 6 ms single-session measurement suggests that part isn't your bottleneck. The ~8 s full-store figure is your own read of every row. Do you know which Kilo call does that during the stall? From the extension side, the session list is refetched when a project opens or activates, not on each tool round-trip.
Your session-count scaling (2.52 s for kilo session list with 425 sessions across 14 worktrees) does match #15874. #16244 replaces the worktree session list's load-everything-then-filter with one limited query. If you can, it would help to know whether the stall lines up with the Agent Manager being open or switching projects, and whether a CPU profile of kilo serve during a stall shows listGlobal.