Repository navigation
fix(prefix-cache): bound snapshot RAM for coding-agent loops - #775
Merged
Merged
Conversation
Collaborator
Author
|
@cubic-dev-ai review this PR |
Contributor
@Graffioh I have started the AI code review. It will take a few minutes to complete. |
Contributor
There was a problem hiding this comment.
All reported issues were addressed across 16 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Graffioh
force-pushed
the
fix/prefix-cache-agent-chain
branch
3 times, most recently
from
September 27, 2026 17:01
a871f1d to
35b91c9
Compare
Graffioh
marked this pull request as ready for review
September 27, 2026 20:26
Contributor
There was a problem hiding this comment.
All reported issues were addressed across 27 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Graffioh
force-pushed
the
fix/prefix-cache-agent-chain
branch
from
September 28, 2026 05:51
35b91c9 to
790d70b
Compare
Graffioh
force-pushed
the
fix/prefix-cache-agent-chain
branch
from
September 28, 2026 06:27
790d70b to
2921114
Compare
On discrete GPUs every prefix-cache snapshot lives in system RAM: the right-sized KV plus the full recurrent state and DFlash features, about 34 KiB per q8_0 token plus 350 MiB for Qwen3.8-27B. A coding agent grows one conversation turn by turn, the cache kept every turn's snapshot as an ancestor of the next, and single-sequence mode had no byte limit, only 32 slots. With pi as the client, RSS reached 37 GB in 7.5 minutes and client-side compaction freed nothing (Luce-Org#675). - Prune superseded snapshots. After a commit, free the strict-prefix ancestors of the new entry except the shallowest one (the shared system/tools head) and protected pins. Single-sequence only; the paged scheduler keeps its own budget and slot reuse. - Key single-sequence entries at the requested cut again. 3a981ce keyed them at Qwen's chunk-aligned saved position, so a PPP pin that was not chunk-aligned was re-targeted on every request and the restore point never moved past ~1K tokens: pi re-prefilled the whole conversation each turn (119 s at 71K). The disk/shutdown key keeps the saved position. - Only target cuts the backend can save. Qwen saves at prefill chunk starts past the restore point (ModelBackend::snapshot_granularity), so a system/tools head under 512 tokens was pinned, never saved, and retried every request: no snapshot was ever taken and every turn prefilled from zero. Such cuts are now skipped for the next reachable boundary. An agent-turn replay saves at the end of its prefill, which every backend can do, so it keeps no such floor. - Below capacity, take a free slot before a live one. Round-robin wrapped onto committed snapshots and evicted by slot position. - Enforce a resident budget in single-sequence mode: --prefix-cache-max-mib auto|MiB (LUCE_PREFIX_CACHE_MAX_MIB for the container entrypoint). auto keeps room for three snapshots at the backend's full context, at most a quarter of the memory available at startup (a readable cgroup v2 limit included; physical memory otherwise). Snapshots a capture supersedes, its restore source included, count as freed because pruning drops them when it commits; a failed capture prunes nothing. After each commit the cache evicts, oldest leaf first, until committed snapshots fit again, so a capture that lands shorter than it reserved cannot leave the cache over budget. Backends size snapshots through the new ModelBackend::snapshot_bytes_estimate: Qwen, DeepSeek4 and the DeepSeek4 layer-split adapter declare the exact tensors their save allocates and ask ggml for the allocation, plus host copies; a split shard only grows rows in the layers it runs. Startup rejects an explicit limit on a backend that cannot size snapshots (unless the prefix cache is off) and prints the enforced budget. /props now reports real resident_bytes. - Snapshot through trailing tool results. When the prompt ends with tool results the cut moves to the start of the generation prompt: clients only append after them, so the next agent turn reuses them. Prompts ending with a user message keep the old cut. Applies to both the single-sequence path and the scheduler; a test checks the prefix is stable for the Qwen, DeepSeek4 and Gemma templates. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Graffioh
force-pushed
the
fix/prefix-cache-agent-chain
branch
from
September 28, 2026 07:01
2921114 to
a6bc676
Compare
davide221
added a commit
that referenced
this pull request
Sep 30, 2026
/v1/messages kept only text blocks. An assistant turn of tool_use blocks rendered empty, and so did a user turn of tool_result blocks, so the model never saw its own call or its result and Claude Code re-issued the same first tool call forever. - tool_use ids go through tool memory like OpenAI tool_calls; ids the server no longer remembers fall back to the Qwen template's <tool_call> rendering. - Each tool_result becomes a tool message (string or text-block content); the user's own text in that turn follows them. - Claude Code ends every request with a system note, so a request "ends with a tool result" when the last message other than a system note is one. The agent-turn prefix snapshot (#775) depends on it.
davide221
added a commit
that referenced
this pull request
Sep 30, 2026
…nts, zero-copy restore (#792) * fix(server): convert Anthropic tool_use and tool_result blocks /v1/messages kept only text blocks. An assistant turn of tool_use blocks rendered empty, and so did a user turn of tool_result blocks, so the model never saw its own call or its result and Claude Code re-issued the same first tool call forever. - tool_use ids go through tool memory like OpenAI tool_calls; ids the server no longer remembers fall back to the Qwen template's <tool_call> rendering. - Each tool_result becomes a tool message (string or text-block content); the user's own text in that turn follows them. - Claude Code ends every request with a system note, so a request "ends with a tool result" when the last message other than a system note is one. The agent-turn prefix snapshot (#775) depends on it. * perf(prefix-cache): exact Qwen snapshot cuts, generated-turn checkpoints, zero-copy restore - Qwen starts a prefill chunk at every restore point, as DeepSeek does, so a snapshot lands on the chat boundary it was requested at instead of the 512-token chunk start before it, and a restore still reproduces a cold prefill. Between restore points chunks keep to the 512 grid, and no chunk in the middle of a prompt is shorter than 16 tokens (a 2-token chunk gave NaN logits on the R9700). The rule is qwen35_prefill_chunk_tokens(). - Masked prefill attention pads its KV span to a multiple of 256 for chunks of at least 32 tokens. Other spans fall back to the generic tile kernel on RDNA4 at head size 256: 12.5% slower and 7.6x further from the CPU reference at 33K tokens. - After a tool-call turn the server keeps the state the generation left as a checkpoint of prompt plus generated tokens, as far as the next request renders that turn with the same tokens. The backend may keep it live (snapshot_save_deferred) and copy it out only before other work would overwrite the live state; restoring the snapshot the live state holds copies nothing. Qwen3.5 dense implements both; Qwen3.5-MoE opts out. - An agent turn continued from such a checkpoint takes its own snapshot only every 2048 tokens of growth: the next request continues it the same way. - A lookup skips entries whose snapshot is gone instead of prefilling the whole prompt, and a consumed deferred snapshot drops its entry. The empty spec-decode retry prefills the prompt when the snapshot was consumed. * fix(prefix-cache): address review on generated-turn checkpoints - Qwen prefill raises LUCE_PREFILL_UBATCH to the 16-token chunk minimum. - The empty spec-decode retry that prefills the prompt reports no restored prefix. - Generated-turn checkpoints are always deferred; the disk cache's shutdown save copies a deferred snapshot out first (snapshot_flush_deferred()). - The throttle test covers a continued turn far from any other checkpoint. - Wording of the help text, a header comment and PREFIX_CACHE.md. * fix(prefix-cache): keep reachable cuts and failed restores consistent - Qwen reports its 64-token minimum first chunk after a restore as the snapshot granularity, so the cache no longer reserves a cut the chunk planner cannot save exactly. - A restore that fails validation no longer consumes the live generated-turn checkpoint; it is consumed only once prefill or decode changes the live state. - Tests: the generated-turn save keeps the request's own inline snapshot at capacity; clearer comment in the consumed-snapshot lookup test. * fix(prefix-cache): one source for Qwen chunk constants, no double snapshot copy - The prefill chunk constants (512 grid, 16-token minimum, 64-token lead after an off-grid restore) live in prefill_helpers.h, used by do_prefill, snapshot_granularity and the chunk-planning test alike. - snapshot_save into the slot a deferred snapshot holds keeps the copy materialization already made instead of copying twice. - PREFIX_CACHE.md: the 16-token minimum does not apply to the prompt's last chunk.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #675. On discrete GPUs every prefix-cache snapshot sits in system RAM: the right-sized KV plus the full recurrent state and DFlash features, about 34 KiB per q8_0 token + 350 MiB for Qwen3.8-27B (1.0 GiB at 20K tokens, 3.4 GiB at 94K, 8.5 GiB at 250K). A coding agent grows one conversation turn by turn, the cache kept every turn's snapshot as an ancestor of the next, and single-sequence mode had no byte limit, only 32 slots. Client-side compaction starts a new chain but frees nothing.
max_resident_bytesonly applied to concurrent paged mode;/propsreportedresident_bytes: 0--prefix-cache-max-mib auto|MiB(LUCE_PREFIX_CACHE_MAX_MIBin the container).auto= three snapshots at the backend's full context, at most ¼ of the memory available at startup (a readable cgroup v2 container limit included; physical RAM otherwise). Snapshots a capture supersedes, its restore source included, count as freed because pruning drops them when it commits; a failed capture prunes nothing and keeps the restore point. After every commit the cache evicts (oldest leaf first, never the new snapshot or a protected pin) until committed snapshots fit again, so a capture that lands shorter than it reserved cannot leave it over budget. Qwen, DeepSeek4 and the DeepSeek4 layer-split adapter report snapshot sizes (snapshot_bytes_estimate) by declaring the exact tensors their save allocates and asking ggml for the allocation, plus any host copies (DeepSeek4 logits and DSpark features; HC state and logits for the split). An explicit limit on a backend that cannot size snapshots is rejected at startup (unless the prefix cache is off), and the banner prints the budget the server enforces./propsreports real bytessnapshot_granularity) and the cache only targets cuts it can reach, moving on to the next reachable boundaryThe last change applies to both the single-sequence path and the scheduler.
test_tool_result_prompt_prefix_survives_next_agent_turnchecks the assumption against the Qwen, DeepSeek4 and Gemma templates (thinking on/off, parallel tool results). DeepSeek4 saves exactly at the cut; Qwen rounds down to a 512-token chunk.Measured on lucebox5 (R9700), pi 0.73.1 as the client
Reporter's flags: Qwen3.8-27B UD-IQ4_XS + DFlash2 q8_0, block 16,
--max-ctx 94072, q8_0 KV, default 32 slots. pi (driven over RPC, one prompt per file) audits the 18.cppfiles ofserver/src/serverwith auto-compaction around 20K tokens.autobudget, 2 budget replacements, no skipped capturesA client with a 266-token system/tools head (Qwen3.8 on Strix Halo, same flags): on
mainevery turn prefilled from zero (8.3 s, 15.1 s, 23.0 s at 3.3K, 5.7K, 8.4K tokens). With this PR the 5.7K and 8.4K turns restore 3,072 and 5,632 tokens and prefill in 7.4 s and 8.2 s.With
LUCE_PPP=0(no pin, so main's cache does slide), main grows to 20.6 GB after 3 compactions and 37.2 GB in a single 84K-token session. With--prefix-cache-max-mib 4096, tracked snapshots peaked at 4.26 GB (RSS 5.2 GB): 4 redirects, 1 capture skipped near 70K.test_deepseek4_unitpasses (new: estimate equals retained bytes aftersnapshot_save()for the monolithic backend, the layer-split adapter and a two-shard split where each shard runs one layer).test_server_unit612/612 (new: Qwen estimate equals the buffersnapshot_target_cache()allocates; budget counts superseded snapshots as freed and keeps the system/tools head; post-commit enforcement after a shorter commit; template prefix test now covers Laguna; unreachable cuts are skipped) (new: pruning, free-slot choice, requested-cut keying, finalize-and-free, budget resolution, trailing-tool-result cut, template prefix stability);test_entrypoint.shpasses (coversLUCE_PREFIX_CACHE_MAX_MIB).Limits
autostays unlimited there and an explicit--prefix-cache-max-mibis rejected at startup. DeepSeek4 sizing is covered bytest_snapshot_bytes_estimate_matches_saved_snapshot, which saves real snapshots and checks the estimate equals the retained buffer plus host copies; not by a live run.autoavoids this.Future
🤖 Generated with Claude Code