server: extend live-prefix rewind to Flash on Metal, bounded by raw-cache budget
Fixes #698.
Background
#668 added live-KV rewind for repeated exact-prefix prompts (retry/regenerate workflows), but gated it to GLM only via ds4_engine_is_glm_dsa(). #698 reports that DeepSeek V4 Flash on Metal still does a full cold prefill in the same scenario, even when the incoming prompt is an exact token-prefix of the live session (e.g. a 175K-token prompt re-prefilled from scratch after a client-side stream abort).
Why the gate exists (this isn't a small oversight)
Read metal_graph_encode_token_raw_swa() rather than guessing: Metal's raw SWA cache is a genuine ring buffer, raw_row = pos % raw_cap. ds4_session_rewind() only truncates checkpoint.len — it does not shift or revalidate that ring. GLM's dense KV cache has no such ring (ds4_session_glm_cap_dense_cache() keeps it consistent unconditionally on rewind), but naively enabling rewind for Flash risks reusing a raw row that the discarded continuation has already overwritten — silently conditioning the resumed generation on stale/wrong tokens. That's a correctness bug, not just a missed cache hit, so I didn't want to just flip the gate.
Fix
New ds4_session_raw_rewind_budget():
- Returns 0 for GLM (unaffected, still gated the existing way).
- For Flash, returns
raw_cap - raw_window— the margin the graph already reserves specifically so chunked prefill doesn't evict window-relevant rows mid-chunk. That existing margin turns out to be exactly the safe reuse budget for this too.
The rewind is only allowed when the discarded tail (old_pos - prompt_len) stays under that budget, which guarantees no raw row the rewound tail depends on has been overwritten.
Empirical validation, not just the theoretical argument
M5 Max, Metal, production Flash q2-q4 quant:
- Positive control: real
ctx=8192session, ~1000-token prompt, resend the exact same prompt after a short generation → log showsrewound Flash live prefix from N to M, continuation is byte-identical to the first generation. - Negative control: forced
raw_cap=300viaDS4_METAL_GRAPH_RAW_CAP(budget becomes an easy-to-exceed 44 tokens), with the budget check temporarily removed to confirm the failure mode is real and not just theoretical — generated 400 tokens (well past budget), resent the same prompt: continuation corrupted into a degenerate140,140,140,...repetition loop instead of the correct count, while the unmodified first generation was correct. Same forcedraw_cap, same over-budget scenario, with the guard in place: correctly falls through to a full re-prefill (reason=token-mismatchin the log) instead of rewinding, and stays correct. - A short within-budget retry under that same forced
raw_cap=300still rewinds and matches, confirming the guard isn't just conservative to the point of never firing.
Happy to re-run any of this against a different quant/ctx if useful — the scratch negative-control build was throwaway and not included here, only the guarded version in this diff.
🤖 Generated with Claude Code
I tried this on top of current main HEAD and found it drastically speeds up long context prefill on subsequent turns. Tried several clients.
Re-validated on current main (84cc882), i.e. after the recent Metal decode refactor (0ad494e make exact fast paths automatic, 42033ee pipeline DFlash verification, 0658dac fix long-context prefill/decode correctness). A clean textual rebase doesn't prove the raw-SWA ring semantics this PR depends on are unchanged, so I re-ran the controls rather than assume.
Rebased onto 84cc882 (no conflicts), make ds4-server ds4_test builds -Wall -Wextra with 0 warnings, and ./ds4_test --server passes (incl. test_live_prefix_rewind_target). Apple M5 Max, Metal, production Flash q2-q4, --ctx 8192 (raw_kv_rows=4352).
Positive control — same prompt sent twice, temp 0:
req1: cache_source=none cached_tokens=0 (cold, 29-tok prompt; live grows to 89)
req2: cache_source=memory-rewind cached_tokens=28
ds4-server: rewound Flash live prefix from 89 to 28; final prompt token will be reevaluated
Both completions byte-identical (cmp -s).
Negative control — forced DS4_METAL_GRAPH_RAW_CAP=300 (budget becomes ~44), generated 400 tokens (well over budget), resent the same prompt:
req2: memory_miss_reason=token-mismatch cache_source=none cached_tokens=0
(no "rewound ..." line — the budget guard declined and fell through to full re-prefill)
Completion still byte-identical — the guard correctly refuses to reuse a raw row the discarded tail may have overwritten, so correctness holds exactly where the earlier scratch build showed corruption without it.
GitHub reports this MERGEABLE / CLEAN against current main. Nothing else to rebase.
Verified on Mac Studio M3 Ultra (80-core GPU, 512 GB), Metal, MXFP4 Flash 0731 fully resident, merged on 84cc882 (stacked with #765, #611, #704, #767 — see note below).
Exact-prefix retry scenario
~5.3K-token prompt (16K chars), 42 tokens generated, then the identical request re-sent (streaming, temp 0):
| main | this PR | |
|---|---|---|
| retry log | live kv cache miss live=5356 prompt=5314 common=5314 reason=token-mismatch — common equals the whole prompt and it still cold-prefills |
rewound Flash live prefix from 5356 to 5313, then ctx=5313..5314:1 |
| retry TTFB | 5.05 s | 0.045 s |
| retry total (42 gen tokens) | 11.85 s | 1.19 s |
The baseline miss line is a nice self-contained proof of the gap this closes: common=5314 on a 5,314-token prompt, discarded anyway.
Generation after the rewind matched the first run's output. ./ds4_test --server passes, and a ds4-bench 2K–16K sweep is within ±1% of baseline (the ds4_session_raw_rewind_budget addition doesn't touch the hot path).
Rebase note for whoever lands this after #765
#765 moves the rewind probe into slot_probe_reuse_locked(). The port that worked here: compute can_rewind (GLM unconditional; Flash gated by ds4_session_raw_rewind_budget() and the discarded-tail bound, exactly as this PR's generate_job_inner hunk) inside the probe where live_prefix_rewind_target() is called, and generalize the rewound GLM live prefix log line to GLM/Flash. The ds4.c/ds4.h budget function applies unchanged.
Measured locally; an AI agent helped run the A/B harness. Log lines are ds4-server's own.