Skip to content

feat(server): state-only backups in the prefix cache for Qwen and DeepSeek, AgentX bench under the official rules (92.2% cache hit rate) - #989

Merged
davide221 merged 6 commits into
mainfrom
feat/prefix-state-backups
Nov 12, 2026
Merged

davide221 merged 6 commits into
mainfrom
feat/prefix-state-backups

Conversation

@davide221

@davide221 davide221 commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

What

The prefix cache now keeps the turns behind a conversation's newest snapshot as state-only backups instead of freeing them.

A superseded turn's snapshot repeats the per-position rows (attention K/V, compressed rows) of the snapshot that supersedes it. Only the state of its own position is its own. So the backup drops its rows and restores with the rows of the newer snapshot. For Qwen3.8-27B a backup is about 370 MB at any length, against about 4 GB for a whole snapshot at 100K tokens.

One policy, every supported model. Which turns to keep, thinning, eviction and donor choice live in the model-agnostic cache (KvCache::trim_superseded, PrefixCache), shared by single-sequence and concurrent serving. A backend only says what a backup holds and drops and borrows rows:

single-sequence concurrent (--max-concurrency) a backup keeps
Qwen3.5 / 3.6 / 3.8 dense and MoE yes yes (paged) recurrent + conv state, drafter features
Qwen3.8-Flash-Next yes yes recurrent, conv, PLE state, draft hidden, logits
DeepSeek V4 / V4.1 yes yes (staged text) raw window, compressor windows, HC state, logits

Contract: ModelBackend::snapshot_state_bytes_estimate / snapshot_drop_kv / GenerateRequest::restore_kv_slot, and SeqEngine::estimate_prefix_state_bytes / drop_prefix_kv / PrefixStorePlan::restore_kv. A restore validates the donor before it touches the live cache and falls back to a cold prefill when it cannot.

  • Backups thin out with distance: the previous turn, then one at least twice as far back, and so on. A prompt that departs d tokens before the end resumes within about 2d of it.
  • Eviction order: the backups of the conversation being served go after the leaves of other conversations.
  • Unchanged: KVFlash pools (Qwen already keeps state-only rungs of its own there), layer split and cluster serving, and the other backends, which keep the previous turn whole while the budget holds it.

Also in this PR, because they are what measures it:

  • request field ignore_eos (keep generating to max_tokens), documented in server/docs/API.md;
  • server/scripts/bench_agentx_cache.py, which runs the official AgentX harness (agentx-harness 1.0.13) in its agentx scenario unchanged and reports the cache hit rate, the harness's figure for a cache that never misses, and the harness's submission_valid verdict.

Why

Before, the previous turn was kept whole only "while the budget holds it", and the cache fills any budget with idle conversations' snapshots. A prompt that changed only its last message (a retry, an edit, a second request from the same point) then fell back to the session head and recomputed about half the context. A state-only backup costs a few hundred MB instead of a whole snapshot, so the turn it serves stays in the cache.

Result

The AgentX benchmark under its own rules, run with server/scripts/bench_agentx_cache.py from this PR:

python3 server/scripts/bench_agentx_cache.py run --url http://127.0.0.1:8090 \
    --model qwen3.8-27b --tokenizer Qwen/Qwen3.8-27B --sessions 1 --duration 900 --out results/agentx-1

The official harness (agentx-harness 1.0.13) in its agentx scenario, unchanged: recorded replies, no --unsafe-override, the scenario's timing, cache bust and warm-up, the official 256K corpus (semianalysis_cc_traces_weka_062126_256k), 15 minutes measured (the rules' minimum). Qwen3.8-27B with its drafter, --max-ctx 262144, default cache budget, one user, one H100, this PR's head.

this PR
Cache hit rate 92.2%
A cache that never misses (the harness's figure) 95.2%
submission_valid (the harness's verdict) true
Requests / errors 60 / 0

One run. No state backup was restored in those 15 minutes, so the run shows where the engine stands on the benchmark, not the gain of the backups: that needs a longer run, where the cache fills up.

Checks

  • Exact, Qwen3.8-27B on one H100: a 4-turn conversation, then an edited last message and an edited earlier message, restored through state backups, give replies equal character for character to a fresh server that never saw the conversation (greedy). Single-sequence: 2/2 equal. Concurrent (--paged-attention --max-concurrency 2): 2/2 equal, with a backup thinned and a restore from a backup.
  • Unit tests, on the H100: backup kept, thinned, budget credit and eviction order (test_server_unit); a paged Qwen checkpoint, a Flash-Next snapshot and a DeepSeek snapshot each restore byte for byte from a backup plus a deeper donor, and refuse donors that cannot supply the rows (test_recurrent_snapshot, test_qwen4exp_prefix_cache, test_deepseek4_unit).
  • Real weights, DeepSeek V4.1 and Qwen3.8-Flash-Next on an R9700 + Strix Halo box, one user and concurrent (2 slots): same conversation and edits. The reply restored from a state-only backup equals the reply restored from the whole snapshot at the same position, 8/8 (the backup restore is logged as state backup slot=N ... restores with the rows of slot=M). Against a cold server with the cache off, Flash-Next concurrent is 2/2 equal; the other modes differ there for the whole-snapshot restore too, because a cold prefill without restore points runs other prefill chunks, so that is not from this PR.
  • Not done yet: a long agent-session replay on DeepSeek and Flash-Next; tensor-parallel and split-GPU Qwen keep whole snapshots because they could not be tested.
  • Failing on main too, not from this PR: test_props_memory_report fails in our CUDA test container; test_qwen4exp_prefix_cache segfaults on an H100 in its KVFlash part, after the snapshot tests pass.

🤖 Generated with Claude Code

@davide221 davide221 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Code review

Found 1 issue.

Copy to agent

Use the copy button in the top-right corner of the block, then paste into your agent.

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.

Repository: Luce-Org/lucebox
Reviewed commit: 3c7c4e695dd67839a14f2f32902c7e6831792275
Verify the findings against the current code, run relevant checks for any fixes, and explain any findings you reject.

<file name="server/scripts/bench_agentx_cache.py">

<violation number="1" line="149" end_line="150">
report() crashes with StopIteration when the client failed and wrote no export

`run()` calls `report(out, a.warm, a.duration)` *before* checking the client's return code (line 123–125), and `readings()` obtains the export with `next((out / "client").rglob("profile_export.jsonl"))` with no default. When the aiperf client exits non-zero without producing a `profile_export.jsonl` — a bad `--url` after `check_server`, a dataset/tokenizer fetch failure, an early client crash — `rglob` yields nothing and `next()` raises an unhandled `StopIteration`, so the user gets a traceback instead of the intended message `"the client exited with {rc}: see {out}/client.log"` that the code at line 124–125 was written to produce. Give `next` a default (`None`) and raise `SystemExit` pointing at `client.log`, or check `rc` before reporting.

<suggestion>
    path = next((out / "client").rglob("profile_export.jsonl"), None)
    if path is None:
        raise SystemExit(f"no profile_export.jsonl under {out}/client: see {out}/client.log")
    records = [json.loads(line) for line in path.open() if line.strip()]
</suggestion>
</violation>

</file>
Issue overview
  1. report() crashes with StopIteration when the client failed and wrote no export · confirmed (server/scripts/bench_agentx_cache.py:149-150)

Reviewed 3c7c4e69 · 1 candidate issue checked, kept at ≥70% confidence · add the code-review label to review again

Comment on lines +149 to +150
path = next((out / "client").rglob("profile_export.jsonl"))
records = [json.loads(line) for line in path.open() if line.strip()]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

report() crashes with StopIteration when the client failed and wrote no export · confirmed

run() calls report(out, a.warm, a.duration) before checking the client's return code (line 123–125), and readings() obtains the export with next((out / "client").rglob("profile_export.jsonl")) with no default. When the aiperf client exits non-zero without producing a profile_export.jsonl — a bad --url after check_server, a dataset/tokenizer fetch failure, an early client crash — rglob yields nothing and next() raises an unhandled StopIteration, so the user gets a traceback instead of the intended message "the client exited with {rc}: see {out}/client.log" that the code at line 124–125 was written to produce. Give next a default (None) and raise SystemExit pointing at client.log, or check rc before reporting.

Checked (90%): server/scripts/bench_agentx_cache.py:123-125 calls report() before checking rc, and readings() at line 149 uses next((out/'client').rglob('profile_export.jsonl')) with no default, so a client failure that produces no export (crash, fetch failure) yields an unhandled StopIteration traceback instead of the intended 'the client exited with {rc}' message at line 125. The only residual assumption is that aiperf can exit non-zero without writing the export, which is the normal failure behavior for a crashed profiling tool.

Suggested change
path = next((out / "client").rglob("profile_export.jsonl"))
records = [json.loads(line) for line in path.open() if line.strip()]
path = next((out / "client").rglob("profile_export.jsonl"), None)
if path is None:
raise SystemExit(f"no profile_export.jsonl under {out}/client: see {out}/client.log")
records = [json.loads(line) for line in path.open() if line.strip()]

davide221 and others added 5 commits November 11, 2026 17:08
…che hit rate bench

A superseded turn's snapshot repeats the attention rows of the snapshot that
supersedes it. Keep it as a state-only backup (recurrent state, decode seed,
drafter features) and restore it with the rows of the newer snapshot, so a
prompt that departs before the end of the conversation resumes near where it
departs instead of at the session head. Backups thin out with distance, and
the served conversation's backups are evicted after other conversations'
leaves. Qwen3.5 dense single-sequence serving; other paths are unchanged.

Also: request field ignore_eos, and scripts/bench_agentx_cache.py to measure
the cache hit rate on replayed agent sessions.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
One trimming routine for both serving paths (KvCache::trim_superseded). A
concurrent engine drops a checkpoint's rows through SeqEngine::drop_prefix_kv
and restores it with PrefixStorePlan::restore_kv; Qwen's paged engine and the
DeepSeek 4 single-sequence backend implement the split.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@davide221
davide221 force-pushed the feat/prefix-state-backups branch from 3c7c4e6 to 6a49611 Compare November 11, 2026 16:31
@davide221 davide221 changed the title feat(server): state-only backups in the prefix cache (cache hit rate 87.4% -> 93.4%) feat(server): state-only backups in the prefix cache for Qwen and DeepSeek (cache hit rate 87.4% -> 93.4%) Nov 11, 2026
The bench now runs the official harness (agentx-harness 1.0.13 from
PyPI) in its agentx scenario unchanged: recorded replies, no override,
the scenario's timing, cache bust and warm-up, and the official 256K
corpus by default. It reports the measured phase, the harness's hit
rate for a cache that never misses, and the harness's submission_valid
verdict. Qwen3.8-27B, one user, 15 minutes: 92.2% against 95.2%,
submission_valid true.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@davide221 davide221 changed the title feat(server): state-only backups in the prefix cache for Qwen and DeepSeek (cache hit rate 87.4% -> 93.4%) feat(server): state-only backups in the prefix cache for Qwen and DeepSeek, AgentX bench under the official rules (92.2% cache hit rate) Nov 11, 2026
@davide221
davide221 merged commit a088256 into main Nov 12, 2026
15 checks passed
@davide221
davide221 deleted the feat/prefix-state-backups branch November 12, 2026 14:57
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.

1 participant