Skip to content

fix(prefix-cache): bound snapshot RAM for coding-agent loops - #775

Merged
davide221 merged 1 commit into
Luce-Org:mainfrom
Graffioh:fix/prefix-cache-agent-chain
Sep 28, 2026
Merged

davide221 merged 1 commit into
Luce-Org:mainfrom
Graffioh:fix/prefix-cache-agent-chain

Conversation

@Graffioh

@Graffioh Graffioh commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

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.

Problem Before After
Snapshots pile up One snapshot per agent turn, kept until 32 slots are full (37 GB RSS after 7.5 min of pi) After each commit, older snapshots of the same conversation are freed; the shallowest one (shared system/tools head) and protected pins stay
No RAM limit max_resident_bytes only applied to concurrent paged mode; /props reported resident_bytes: 0 --prefix-cache-max-mib auto|MiB (LUCE_PREFIX_CACHE_MAX_MIB in 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. /props reports real bytes
Restore point stuck at ~1K tokens (regression from 3a981ce) Entries keyed at Qwen's chunk-aligned saved position, so a PPP pin that isn't chunk-aligned (1462 for pi) was re-targeted every request: 119 s prefill per turn at 71K Entries keyed at the requested cut again; the disk/shutdown key keeps the saved position
Short system/tools head never cached Qwen saves only at 512-token prefill chunk starts past the restore point. A head under 512 tokens was pinned, never saved and retried every request, so no snapshot was ever taken The backend reports its save granularity (snapshot_granularity) and the cache only targets cuts it can reach, moving on to the next reachable boundary
Live slots overwritten below capacity Round-robin wrapped onto committed snapshots (evicts by slot position) Free slots are taken first
Last tool result re-prefilled every turn Snapshot cut before the newest message: 43% of prefill was tokens the previous request already had When the prompt ends with tool results, the cut moves to the generation prompt (clients only append after them). Prompts ending with a user message keep the old cut, so edits still hit

The last change applies to both the single-sequence path and the scheduler. test_tool_result_prompt_prefix_survives_next_agent_turn checks 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 .cpp files of server/src/server with auto-compaction around 20K tokens.

Default config main this PR
Prompt tokens reused from cache 3.4% 75.5%
Median prefill per request 20.5 s 1.9 s
Worst prefill at ≥40K tokens 118.7 s 24.9 s
Files audited 4 in 15 min 18 in 19 min (8 compactions)
Peak RSS 1.5 GB (cache effectively unused) 11.2 GB; snapshots held at 9.9 GB against the 10.9 GB auto budget, 2 budget replacements, no skipped captures

A client with a 266-token system/tools head (Qwen3.8 on Strix Halo, same flags): on main every 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_unit passes (new: estimate equals retained bytes after snapshot_save() for the monolithic backend, the layer-split adapter and a two-shard split where each shard runs one layer). test_server_unit 612/612 (new: Qwen estimate equals the buffer snapshot_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.sh passes (covers LUCE_PREFIX_CACHE_MAX_MIB).

Limits

  • Size reporting covers Qwen, DeepSeek4 and DeepSeek4 layer splits. DeepSeek4 mixed-backend splits (part of each snapshot in a remote process), layer-split Qwen, Gemma and Laguna still get pruning, free-slot selection and the tool-result cut, but no byte limit: auto stays unlimited there and an explicit --prefix-cache-max-mib is rejected at startup. DeepSeek4 sizing is covered by test_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.
  • During a replacement the new snapshot and its victim coexist briefly, so RSS can exceed the budget by one snapshot, as in concurrent mode.
  • With a tight budget the victim order can drop the system/tools head, and captures near full context are skipped (restore point stops moving). auto avoids this.
  • Not in this PR: counting to-be-pruned ancestors as freed in the budget check; PFlash-compressed prompts (being reworked).

Future

  • Do it also for continuous batching.

🤖 Generated with Claude Code

@Graffioh

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai review this PR

@cubic-dev-ai

cubic-dev-ai Bot commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

@cubic-dev-ai review this PR

@Graffioh I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 16 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread variables.md Resolved
Comment thread server/src/server/http_server.cpp Resolved
Comment thread server/src/server/http_server.cpp Resolved
Comment thread server/docs/PREFIX_CACHE.md Resolved
Comment thread server/src/server/server_main.cpp Resolved
@Graffioh
Graffioh force-pushed the fix/prefix-cache-agent-chain branch 3 times, most recently from a871f1d to 35b91c9 Compare September 27, 2026 17:01
@Graffioh
Graffioh marked this pull request as ready for review September 27, 2026 20:26

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 27 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread server/README.md Resolved
Comment thread server/src/server/prefix_cache.cpp Resolved
Comment thread server/docs/PREFIX_CACHE.md Resolved
Comment thread server/test/test_server_unit.cpp Resolved
Comment thread server/src/server/prefix_cache.cpp Resolved
Comment thread server/src/server/http_server.cpp Resolved
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
Graffioh force-pushed the fix/prefix-cache-agent-chain branch from 2921114 to a6bc676 Compare September 28, 2026 07:01
@davide221
davide221 merged commit b5dc840 into Luce-Org:main Sep 28, 2026
13 of 15 checks passed
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unexpected system RAM growth during long-context inference on r9700 GPU

2 participants