Skip to content

feat(kvflash): DeltaNet state ladder and live restore of the running session - #851

Merged
davide221 merged 29 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/2.0a-D-live-restore
Oct 25, 2026
Merged

davide221 merged 29 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/2.0a-D-live-restore

Conversation

@dusterbloom

@dusterbloom dusterbloom commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #850. This PR's own commits are 73bbff7, 99e7342, 6573a85, 2dcf1e1, e6116c6, 2afbd31 and 784e521.

Why

A KVFlash conversation keeps its KV rows in the resident pool, but the DeltaNet (recurrent) state cannot be rebuilt from them. So every new turn re-prefilled the whole prompt unless a server snapshot covered it. This PR resumes from the live session instead.

What it does

  • State ladder. While a pooled prefill runs, state-only checkpoints are captured on the 512 grid: at the head cut, every 8192 tokens, and at the prompt end.
    • A checkpoint holds the SSM and conv state but no KV, plus the drafter feature ring when a drafter is loaded.
    • LRU eviction keeps them under LUCE_KVFLASH_STATE_LADDER_MIB (default 3072). The head checkpoint and the newest one are never evicted.
    • One checkpoint is 149.6 MiB on Qwen3.8-27B.
  • Live restore.
    • The longest common prefix of the prompt and the live token history picks the deepest checkpoint at or below it.
    • The pager is truncated to that point and the state is restored. Only prompt[C:] prefills, on the grid.
    • restore_and_generate compares the server snapshot's cut with the live cut and takes the larger (kvflash_pick_resume).
    • A dense snapshot that fits in the pool is adopted by the pager as identity-mapped chunks instead of failing. A longer one is handled as described under "Dense snapshots longer than the pool" below.
  • History bookkeeping. Spec decode appends accepted tokens to the live history. A consuming restore or a cold prefill drops the previous session's ladder.
  • One switch. LUCE_KVFLASH_SESSION is on by default; 0 disables the ladder and live restore. It does not gate the 512 grid from feat(kvflash): pooled prefill on an absolute 512-token grid #850, and it only acts with KVFlash on.
  • ModelBackend::restorable_prefix reports the cut a restore would take. The server logs the backend's own cut as prefix_len.
  • PFlash admission (3a045de). HttpServer::ram_restorable_prefix_tokens counted only the RAM snapshot the prefix cache would restore. It now passes that snapshot's slot and length to restorable_prefix. So a KVFlash live session counts as restorable, and a snapshot the backend would drop counts for nothing. The default implementation returns the snapshot length, so other backends are unchanged.
  • Dense snapshots longer than the pool (9d8fe975). A dense snapshot that holds more rows than the pool always re-prefills from token 0. Such a snapshot can only come from the disk cache, written by a server that ran without --kvflash or with a larger pool. Before this commit, the adopt path in this PR aborted on it by writing past the end of the pool tensor.
  • prefix_len after a re-prefill (60d98ef2). The prefix_len on the chat DONE log line is now the backend's own cut, so it is 0 after a re-prefill. Before, it showed the length of the snapshot the server had offered, even when the backend dropped it. The chat CACHE line still shows the disk-hit position.
  • Empty disk cache per gate arm (725e6299). Each gate arm now starts on its own empty disk KV cache, so one arm cannot get hits from the other's entries.
  • Gate scripts in optimizations/kvflash/tests/gate/. Paths and the model come from the environment.
    • run_gate.sh runs a 10-turn chat twice, with the session off and on, and checks the answers are byte-identical turn by turn.
    • run_scenarios.sh covers: a pooled restore past the pool; a restore at a 512-token boundary; an image prompt.
  • Docs. ENVIRONMENT.md rows and PREFIX_CACHE.md paragraphs.

Checks

Gate A, RTX 3090, at the top of the stack (09bde623).

  • Setup: Qwen3.8-27B UD-Q4_K_M, default KV type, --max-ctx 131072, --kvflash 8192, temperature 0, seed 1. Same binary on both arms. The first turn is about 12.5K tokens, followed by 9 short turns. Each arm had its own empty disk KV cache, and every request logged disk_hit=false.
Session Prefill s Decode tok/s Wall s
off (LUCE_KVFLASH_SESSION=0) 9.85 44.5 10.45
on (default) 0.55 44.5 1.40

Medians over 10 turns, server side.

  • The answers are byte-identical on 10/10 turns.
  • With the session off, prefix_len is 0 on every turn. With it on, it is 0 on turn 1 and then goes from 11,602 to 14,201, and each turn resumes at the previous turn's last assistant header (the cuts come from feat(kvflash): turn checkpoints, generation-end rung and turn cuts #852; with D alone, a turn resumes at the 512-grid checkpoint below it).
  • Scenarios 1 and 2 pass. Scenario 3 was skipped because no mmproj file was given.

PFlash admission gap, R9700 (lucebox6). Measured before the last rebase, on fc5563d (the previous top of the stack, on main af64ae9). On that tree the PFlash admission commit was d11ba7a; it is 6573a85 now. This run was not repeated on the current stack.

  • Setup: a 5-turn chat that reaches 39,456 tokens, with --kvflash 16384, PFLASH_ADMISSION=cache, the PFlash heads, and ggml-org's Qwen3.5-0.8B BF16 drafter. Three arms built from the top of the stack.
  • Turn 5 by arm:
Arm Restorable Uncached droppable Decision Served
PFlash admission commit reverted (d11ba7a on that tree) 13,819 (last RAM snapshot) 20,028 compress 39,456 → 6,688 tokens; the live session is thrown away
this PR 31,063 (live cut) 2,843 under threshold 39,456 raw; live restore L=31063 C=31063 replay=8393
compression off (reference) — — — 39,456 raw; same restore
  • This PR's answers are byte-identical to the reference on 5/5 turns. The reverted arm differs on turn 5.
  • Medians over 5 turns, this PR vs the reference: prefill 845.5 vs 844.8 tok/s, decode 24.5 vs 24.5 tok/s, wall 11.1 vs 11.1 s. One run per arm.

KVFlash off, RTX 3090. Main 6f2b179 vs the top of the stack (09bde623), same 10-turn chat without --kvflash, --no-kv-cache on both (Qwen3.8-27B UD-Q4_K_M, --max-ctx 131072, temperature 0):

  • Two runs per arm, in the order main, stack, main, stack. Answers byte-identical on 10/10 turns in both pairs.
  • prefix_len identical turn for turn on all four runs (0, then 11600 to 14199), and disk_hit=false on every request.
  • Medians over 10 turns, main vs stack: run 1 prefill 722 vs 685 tok/s, decode 43.70 vs 43.40 tok/s, wall 1.30 vs 1.30 s; run 2 prefill 722 vs 722 tok/s, decode 43.75 vs 43.75 tok/s, wall 1.30 vs 1.25 s. Pooled over both runs (20 turns): prefill 722 vs 720 tok/s, decode 43.75 vs 43.45 tok/s, wall 1.30 vs 1.30 s.
  • The server log times prefill to 0.1 s, so prefill tok/s on these short prefills is coarse. The gaps are within the spread between the two runs of the same arm, so this is no speed claim either way.

Tests

  • test_kvflash_live_restore.cpp, test_kvflash_resume.cpp, test_kvflash_state_ladder.cpp, and new cases in test_kvflash_restore_plan.cpp.
  • test_ram_restorable_prefix_defers_to_the_backend and test_ram_restorable_prefix_default_is_the_snapshot_tokens in test_server_unit.cpp.
  • test_server_unit (CUDA build): 1094 passed, 0 failed, 7 skipped.

Limits

  • Live restore covers one running session; KVFlash still requires --max-concurrency 1.
  • Pooled snapshots stay in RAM. A session evicted from the RAM prefix cache prefills from scratch.
  • Main itself aborts on the same oversized disk entry, with a "tensor write out of bounds" assertion, when the server runs with --kvflash and the entry holds more rows than the pool. fix(qwen35): refuse a dense snapshot longer than the KV cache rows #847, now merged, fixes main. With this stack, the entry is not used and the prompt prefills from token 0.
  • With --draft, every ladder rung also stores the drafter's target-feature ring (4096 rows × 25600 BF16, 200 MiB on the 27B models). Rungs grow from 149.6 MiB to 349.6 MiB, so the 20-rung ladder pins about 6.8 GiB of host memory instead of 2.9 GiB. This costs memory and copy time, not correctness.

…score ledger

Library additions to KvFlashPager, header and unit tests only; nothing in the
backends calls them yet.

- serialize(max_chunks) / deserialize(): a position-addressed blob of the first
  N chunks (resident rows, host copies, per-chunk score ledger), so a pager can
  be rebuilt later. A failed pinned-host allocation in deserialize frees the
  buffers already allocated.
- truncate(P): drop every logical position >= P, as if the pager had only seen
  P tokens. The chunk containing P keeps its block with rows >= P zeroed; the
  pool is refilled from host copies like a fresh pager (recency, or score with a
  scorer) and the LRU clock is renumbered in logical order.
- pin_range / unpin_all (reset clears pins), per-chunk score ledger accessors,
  floor_to_chunk, and memset of host-resident blocks.
@davide221

Copy link
Copy Markdown
Contributor

CI failed on 60d98ef2

New KVFlash pager tests fail because they page KV on a runner with no GPU driver

Twelve new pager unit tests from this pull request fail in the CPU test step. The build links the CUDA runtime, so the pager tries to allocate pinned host memory through CUDA, but the runner has no GPU driver (only a stub library), the allocation fails, and every test that pages a chunk out of the pool errors out. The change under test is at fault in the sense that these new tests cannot run on a GPU-less runner; the pager code itself is unchanged in behavior on real GPU machines.

How to fix: Use plain host memory for pager backing when the pool tensors are CPU-resident

  1. In server/src/common/kvflash_pager.h, add a host_backing_is_pinned_ flag set in attach() to !attn_k.empty() && !is_host_tensor_(attn_k[0]).
  2. In page_out(), deserialize() and release_host_(), allocate/free with cudaMallocHost/cudaFreeHost only when that flag is set; otherwise use a std::vector<uint8_t> fallback (e.g. a host_data_vec member) and memcpy.
  3. Keep copy_chunk's existing is_host_tensor_() memcpy path unchanged.
  4. Rebuild and run ctest -R 'KvflashPager(Serde|Truncate)' to confirm the 12 tests pass.

failing unit tests on gpu-less runner · high confidence · run

Details and evidence

Failed: Build (cmake + uv sync --extra megakernel) › Build and run C++ CPU unit tests

Job Build (cmake + uv sync --extra megakernel), step Build and run C++ CPU unit tests (check-cpu). 12 tests fail, all in the two fixtures added by this PR: KvflashPagerSerdeFixture (9 tests, #1046-1054) and KvflashPagerTruncateFixture (after_eviction_and_page_out, serialize_truncate_serialize_roundtrip, truncate_leaves_the_resident_set_a_fresh_pager_reaches, #1058/1061/1062).

Root cause: the CI build enables CUDA (CUDA host compiler is GNU 13.3.0 in the log), so KVFLASH_HAS_ASYNC_DMA is defined (server/src/common/kvflash_pager.h:66-69). The runner has no GPU driver, so cudaMallocHost fails with CUDA driver is a stub library (log line [kvflash] cudaMallocHost failed: CUDA driver is a stub library). page_out() then returns false (server/src/common/kvflash_pager.h:377-383), so no block is freed; the next alloc_span past the 8-block pool finds no evictable block and fails with [kvflash] no pool slot at pos 512 (pool 512 exhausted). The tests' must()/REQUIRE wrappers turn that into the thrown errors kvflash serde helper precondition failed (server/test/unit/test_kvflash_pager_serde.cpp:69) and kvflash truncate helper precondition failed (server/test/unit/test_kvflash_pager_truncate.cpp:64).

Why only the new tests fail: they are the first unit tests that exercise page_out on CPU-resident tensors. The PR already added the is_host_tensor_() memcpy fallback for the copy path (kvflash_pager.h:727-733), but the host-backing allocation in page_out() still unconditionally uses cudaMallocHost whenever KVFLASH_HAS_ASYNC_DMA is compiled in, even when the pool tensors live in host memory. Older pager tests (e.g. test_kvflash.cpp) run against a real GPU and are not in this CPU ctest set.

Not a runner flake: the failure is deterministic and tied to the new tests' assumptions.

Other things to try

  • Reproduce locally without a GPU: configure with -DGGML_CUDA=ON and run ctest -R KvflashPager on a machine with the CUDA stub only; the tests fail the same way.
  • Alternative: skip these fixtures when cudaMallocHost is unavailable (e.g. probe once in the harness and report skipped), but the fallback is preferable since it actually tests the paging logic on CPU.
  • Longer term, consider compiling the pager's async-DMA path only when a real device is present (runtime check), so CPU-backend servers built with CUDA support also get working paging.
Prompt for a coding agent
A GitHub Actions run failed in Luce-Org/lucebox. Please fix it.

- Pull request #851 (branch `kvflash/2.0a-D-live-restore`), commit 60d98ef2aa6fc90aa38277db87755f6d1887816c
- Workflow: CI (https://github.com/Luce-Org/lucebox/actions/runs/38761846271)
- Failed: Build (cmake + uv sync --extra megakernel) › Build and run C++ CPU unit tests

Diagnosis:
Job `Build (cmake + uv sync --extra megakernel)`, step `Build and run C++ CPU unit tests` (`check-cpu`). 12 tests fail, all in the two fixtures added by this PR: `KvflashPagerSerdeFixture` (9 tests, #1046-1054) and `KvflashPagerTruncateFixture` (`after_eviction_and_page_out`, `serialize_truncate_serialize_roundtrip`, `truncate_leaves_the_resident_set_a_fresh_pager_reaches`, #1058/1061/1062).

Root cause: the CI build enables CUDA (`CUDA host compiler is GNU 13.3.0` in the log), so `KVFLASH_HAS_ASYNC_DMA` is defined (server/src/common/kvflash_pager.h:66-69). The runner has no GPU driver, so `cudaMallocHost` fails with `CUDA driver is a stub library` (log line `[kvflash] cudaMallocHost failed: CUDA driver is a stub library`). `page_out()` then returns false (server/src/common/kvflash_pager.h:377-383), so no block is freed; the next `alloc_span` past the 8-block pool finds no evictable block and fails with `[kvflash] no pool slot at pos 512 (pool 512 exhausted)`. The tests' `must()`/`REQUIRE` wrappers turn that into the thrown errors `kvflash serde helper precondition failed` (server/test/unit/test_kvflash_pager_serde.cpp:69) and `kvflash truncate helper precondition failed` (server/test/unit/test_kvflash_pager_truncate.cpp:64).

Why only the new tests fail: they are the first unit tests that exercise `page_out` on CPU-resident tensors. The PR already added the `is_host_tensor_()` memcpy fallback for the *copy* path (kvflash_pager.h:727-733), but the *host-backing allocation* in `page_out()` still unconditionally uses `cudaMallocHost` whenever `KVFLASH_HAS_ASYNC_DMA` is compiled in, even when the pool tensors live in host memory. Older pager tests (e.g. test_kvflash.cpp) run against a real GPU and are not in this CPU ctest set.

Not a runner flake: the failure is deterministic and tied to the new tests' assumptions.

Proposed fix: Use plain host memory for pager backing when the pool tensors are CPU-resident
1. In `server/src/common/kvflash_pager.h`, add a `host_backing_is_pinned_` flag set in `attach()` to `!attn_k.empty() && !is_host_tensor_(attn_k[0])`.
2. In `page_out()`, `deserialize()` and `release_host_()`, allocate/free with `cudaMallocHost`/`cudaFreeHost` only when that flag is set; otherwise use a `std::vector<uint8_t>` fallback (e.g. a `host_data_vec` member) and `memcpy`.
3. Keep `copy_chunk`'s existing `is_host_tensor_()` memcpy path unchanged.
4. Rebuild and run `ctest -R 'KvflashPager(Serde|Truncate)'` to confirm the 12 tests pass.

Check out that commit, confirm the diagnosis, make the fix (adjust it if the diagnosis is wrong), and re-run the failing step locally before pushing.

Reply with /ci-fix and what to change to get a revised diagnosis.

…is unavailable

The CPU-backend serde and truncate cases that page chunks out allocate
their host backing with cudaMallocHost on GPU builds. On the CPU-only
check-cpu runner the driver is a stub and that allocation fails, so 12
cases failed. Skip them there; the GPU runners still run them.

@davide221 davide221 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.

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: b03fd7acb71c51c9d523c04f5199e6854af8f0e3
Verify the findings against the current code, run relevant checks for any fixes, and explain any findings you reject.

<file name="optimizations/kvflash/tests/gate/scripts/gate4_live.py">

<violation number="1" line="43" end_line="46">
Mode C negative test is dead code: the documented message edit is guarded by `if False`

The module docstring (line 4) advertises mode `C` as a negative control: "B setup, turns 1-5 as A, turn 6 with a middle message edited". The code that performs that edit is inside `if False:` (line 43), so it never runs: mode C replays arm A's prompts verbatim, exactly like mode B, and will always report byte-identical answers. Anyone running `gate4_live.py C` as the documented negative control gets a run that cannot detect a restore that wrongly ignores a mid-history edit — it passes vacuously. The disabled block also contradicts the docstring on which message it edits (turn 3's user message vs the docstring's turn 6). Remove the `if False:` guard (and reconcile the edit target with the docstring) or drop mode C and its docstring line.
</violation>

</file>
Issue overview
  1. Mode C negative test is dead code: the documented message edit is guarded by if False · likely (optimizations/kvflash/tests/gate/scripts/gate4_live.py:43-46)

Reviewed b03fd7ac · 4 candidate issues checked, kept at ≥70% confidence · add the code-review label to review again

Comment on lines +43 to +46
if False: # q38spec: C = live arm without drafter, replays A verbatim
# edit the user message of turn 3 (a middle message); keep everything else
idx = [i for i, m in enumerate(msgs) if m["role"] == "user"][2]
msgs[idx]["content"] = msgs[idx]["content"].replace("Update 3.0", "Update 3.0 (EDITED)", 1)

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.

Mode C negative test is dead code: the documented message edit is guarded by if False · likely

The module docstring (line 4) advertises mode C as a negative control: "B setup, turns 1-5 as A, turn 6 with a middle message edited". The code that performs that edit is inside if False: (line 43), so it never runs: mode C replays arm A's prompts verbatim, exactly like mode B, and will always report byte-identical answers. Anyone running gate4_live.py C as the documented negative control gets a run that cannot detect a restore that wrongly ignores a mid-history edit — it passes vacuously. The disabled block also contradicts the docstring on which message it edits (turn 3's user message vs the docstring's turn 6). Remove the if False: guard (and reconcile the edit target with the docstring) or drop mode C and its docstring line.

Checked (85%): At gate4_live.py:43 the edit block is inside if False:, so mode C never edits any message and replays arm A verbatim, exactly like mode B; the docstring at line 4 still documents C as a negative control with a mid-history edit (and even disagrees with the dead block on which turn is edited). Only caveat: the inline comment suggests the author intentionally repurposed mode C, so this may be a stale docstring/dead code rather than a functional regression, but the documented negative control is indeed vacuous.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in d5e4a35f. Mode C was a leftover: run_gate.sh only runs A and B and nothing checks a C result, so re-enabling the edit would only add an unchecked run. Mode C is gone from the docstring and the code, and any mode other than A or B now exits with the usage. The same commit is in #852 as 342f22d.

…ing the rest

refill_after_truncate_ ranked host chunks by score alone, so with a scorer
older high-score chunks could take every free block and leave the sink, tail
window and pinned chunks non-resident, unlike a pager that only saw P tokens.
Recall the protected chunks first, then rank the discretionary ones.
…VFLASH2

The header recorded only the K dtype, so a V cache switched from F16 to BF16
passed the byte-geometry checks and its values were reinterpreted. Record the
V dtype as a ninth header field, validate it, and bump the magic to KVFLASH2
so blobs written by the previous layout are refused.
attach() reset the mappings but kept the pin vector, so pins set against a
larger pool survived re-attaching to a smaller one and protected every chunk,
starving allocation. Clear them with the other per-attach state.
A position at chunk index 2^31 narrowed to a negative int, skipped the resize
and wrote pinned_ out of bounds (segfault in the unit test). Check the range in
64 bits first: refuse spans longer than the pool and chunk indices past 4M,
which also bounds the range scan and the pin-flag allocation.
… as recallable zero KV

deserialize marked every entry on_host, so a chunk that was never written (a
hole left by a failed allocation or a position jump) became recallable zero KV
that reselect could pick. Write a materialized byte in the ledger (same
KVFLASH2 layout bump as the V dtype), restore holes as holes without a host
copy, and refuse a blob that marks a never-materialized chunk resident.
…ents are caught

The pattern repeated every 256 bytes but a segment is 512, so whole K/V/head/layer
segments were interchangeable and swapping them went undetected (28 of 28 pair
swaps passed the old check). Hash the byte offset within the chunk instead, in
both the serde and truncate tests, and add a case that swaps every segment pair.
…geable host backing

Fifteen CPU-backend cases skipped on the check-cpu runner because the pager's
pinned host backing (cudaMallocHost) fails under the stub driver, so CI never
ran them. Add KvFlashPager::set_pinned_host_backing(false) (pageable memory,
each chunk remembers how its buffer was allocated) and a TestPager that picks
it when pinned allocation is unavailable. None of these cases exercise DMA
ordering (their tensors are host memory), so none stay GPU-gated.
The wire format was documented as little-endian but integers and floats are
written in host byte order. Add a static_assert for little-endian hosts, fix
the comment, and pin the byte layout with a test. No encoder is added.
With KVFlash on, a prefix snapshot used to be refused as soon as the live cache
outgrew the resident pool, because dense snapshots copy KV rows assuming the
identity layout that pooled prefill breaks. This saves such a snapshot as a
pager blob and restores it without re-prefilling the prefix.

- PrefixSnapshot carries the pager blob (is_pooled, kvflash_blob); the state
  snapshot skips the dense KV tensors (skip_kv). Pooled snapshots are taken at
  a chunk boundary of a pooled prefill and at the end of a prompt.
- Restore, behind LUCE_KVFLASH_RESTORE_CONSUME=1 (default off, behavior then
  unchanged): the pager and QK pool are rebuilt from the blob and only the
  suffix prefills, with real token ids for the restored prefix. Without it, or
  when the cut is not chunk aligned, a pooled snapshot is dropped and the whole
  prompt prefills from 0 (kvflash_restore_plan, pure and unit tested).
- A pooled snapshot is never handed to the SSD tier: an OwnedSnapshot cannot
  carry the pager blob, so a file written from it would restore with no KV
  (Luce-Org#839 hazard). disk_persistable() and SnapshotRef::pooled guard the save and
  the layout learning.
- A dense prefill resets the pager, so a boundary snapshot never serializes
  the previous request's mapping.
- LUCE_KVFLASH_DEBUG_RESIDENT logs the resident chunk ranges and a score-ledger
  hash after each prefill.
- optimizations/kvflash/tests/pooled_restore_identity.sh checks restored and
  cold answers match at 20K/35K/64K.
- Docs: ENVIRONMENT.md rows and a KVFlash session restore section in
  PREFIX_CACHE.md.
…ot to the disk writer

The Qwen3.5 backend overrides snapshot_detach and already frees a pooled
snapshot. The default implementation copies snapshot_ref() to host, which for a
pooled snapshot would carry tensors without the KV held in the pager blob.
Return an empty snapshot instead, and cover it with a unit test.
…session

A KVFlash conversation keeps its KV rows in the resident pool, but the DeltaNet
(recurrent) state cannot be rebuilt from them, so every new turn re-prefilled
the whole prompt unless a server snapshot covered it. This resumes from the
live session instead.

- State ladder: while a pooled prefill runs, state-only checkpoints (SSM and
  conv state, no KV; the drafter feature ring only with a drafter) are captured
  on the 512 grid at the head cut, every 8192 tokens and at the prompt end. LRU
  eviction keeps them under LUCE_KVFLASH_STATE_LADDER_MIB (default 3072); the
  head and newest rung are never evicted.
- Live restore: the longest common prefix of the prompt and the live token
  history picks the greatest rung at or below it. The pager is truncated to that
  rung, the state restored, and only prompt[C:] prefills on the grid.
  restore_and_generate compares the server snapshot cut with the live cut and
  takes the larger (kvflash_pick_resume); a dense snapshot that outgrows the pool
  is adopted by the pager as identity-mapped chunks instead of failing, and a
  live cut survives the pool boundary.
- Spec decode appends accepted tokens to the live history. A consuming restore
  or a cold prefill (image or not) drops the previous session's ladder.
- LUCE_KVFLASH_SESSION is the one switch (default on, 0 disables the ladder and
  live restore; it does not gate the 512 grid). Only active with KVFlash on.
- ModelBackend::restorable_prefix reports the cut a restore would take; the
  server reports the backend's own cut as prefix_len.
- Docs: ENVIRONMENT.md rows and PREFIX_CACHE.md paragraphs.
run_gate.sh runs the same 10-turn chat twice against a fresh server, with
LUCE_KVFLASH_SESSION=0 (cold arm) and default (restore arm), and cmp_gate.py
checks the answers are byte-identical turn by turn. run_scenarios.sh covers
pooled restore past the pool, an unrelated session in between, and an edit
mid-history. Paths and the model come from the environment, nothing is hardcoded.
HttpServer::ram_restorable_prefix_tokens counted only the tokens of the RAM
snapshot the prefix cache would restore. It now remembers that snapshot's slot
and returns backend.restorable_prefix(prompt, slot, slot_tokens), with slot -1
and 0 tokens when none matched, so a KVFlash live session counts as restorable
and a snapshot the backend would drop counts for nothing. The default
implementation returns slot_tokens, so other backends are unchanged.
A dense snapshot restored from the disk cache can hold more rows than the
KVFlash pool tensor (written by a server with no pool or a larger one). The
plan let it through as Dense on an exact hit and as AdoptDense with live
restore on, and restore_target_cache wrote past the pool tensor and aborted.
kv_offset > pool_tokens now plans FullReprefill (Reject without a prompt),
whatever adopt_dense says; AdoptDense applies only when the rows fit.
The chat DONE line printed the server's snapshot or disk-hit position as
prefix_len whenever a restore was attempted, so a snapshot the backend dropped
for a full re-prefill still showed its length. The Qwen3.5 backend now marks
the cut it made (restore_cut_reported) and reported_prefix_len() prefers it,
including 0. Other backends keep their numbers. The chat CACHE line keeps
printing the disk-hit position: pooled_restore_identity.sh parses it.
Pooled prefill used min(ubatch, remaining) batches counted from wherever the
request started, so where a batch ended depended on the earlier history of the
session and a restored run could cut differently from a cold one.

Batches now end on multiples of 512 (a multiple of the 64-token pager chunk):
only the first batch after an off-grid resume and the end-of-prompt remainder
are short. kvflash_prefill_batch_end / kvflash_prefill_batches are pure and unit
tested; the non-pooled prefill path is unchanged. Documented in PREFIX_CACHE.md.
…se and replayed arm A verbatim

Nothing ran mode C (run_gate.sh runs A and B), and with the edit disabled it
passed vacuously. Any mode other than A or B now exits with the usage.
@dusterbloom
dusterbloom force-pushed the kvflash/2.0a-D-live-restore branch from d5e4a35 to 784e521 Compare October 23, 2026 16:41
davide221 and others added 3 commits October 24, 2026 02:07
…er branch

kvflash_pager.h reset(): keep Luce-Org#854's sync_page_stream_() (checked wait that
clears page_work_queued_) and this branch's free_host_buffer_() helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…led snapshot branch

Via the Luce-Org#848 branch merge. server/CMakeLists.txt keeps both new unit tests
(test_kvflash_restore_plan.cpp and main's test_dflash_window.cpp).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…led grid branch

Via the Luce-Org#849 branch merge; no new conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
davide221 and others added 5 commits October 24, 2026 02:08
…sion restore branch

Via the Luce-Org#850 branch merge. server/CMakeLists.txt keeps this branch's live
restore and resume tests plus main's test_dflash_window.cpp.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
deserialize() put resident chunks back in identity block order with a fresh
LRU order. A cold prefill has the same chunks resident but in rotated blocks,
so attention summed the same rows in a different order: rounding-level logit
differences that flipped near-tie tokens. On the R9700 pooled_restore_identity.sh
failed at 35K and 64K (turn 3 differs between CONSUME=0 and =1).

KVFLASH3 adds a pool layout section: block and LRU rank per chunk, the use
clock and the free-list order. Into a pool of the saved size every chunk gets
its own block back and evictions pick the same victims; another pool size
keeps the KVFLASH2 behavior (residency only, identity order). LRU stamps are
saved as dense ranks, which evict exactly like the raw clock, so pagers that
behave alike serialize alike.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…estore) into kvflash pooled grid branch

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…estore) into kvflash session restore branch

Co-Authored-By: Claude Opus 5.5 <[email protected]>
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 24, 2026
…t pool layout restore) into kvflash turn checkpoints branch

Luce-Org#852 carried the pre-10-23 Luce-Org#848-Luce-Org#851 chain, which conflicted with the
rebased Luce-Org#851 in 10 files. This tree is the new Luce-Org#851 branch plus this PR's
own commits (046516e, d664068, 0e2ff1b, b3ebe9b) re-applied, all clean;
342f22d duplicates Luce-Org#851's 784e521 and is already there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@davide221

Copy link
Copy Markdown
Contributor

Merged the updated base (main #886 + the #849 restore-layout fix, see #849) into this branch; your commits are unchanged. The stack (main + #848-#851) passes on lucebox2: restore identity at 20K/35K/64K, gate 10/10 identical, scenarios 1-3, unit 1125/0.

…lash DeltaNet ladder branch

Clean 3-way merge against the tested Luce-Org#850 head: Luce-Org#851 changes and the
main-side changes (Luce-Org#876 sampler seeding, Luce-Org#863 PFlash cleanup) are both
kept exactly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@davide221
davide221 merged commit 5121fcf into Luce-Org:main Oct 25, 2026
7 of 8 checks passed
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 25, 2026
…rg#850, Luce-Org#876, Luce-Org#863) into kvflash turn checkpoints branch

Clean 3-way merge against the tested Luce-Org#851 head: Luce-Org#852 changes and the
main-side changes are both kept exactly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 25, 2026
Main equals the tested Luce-Org#851 head, so the tree is the tested Luce-Org#852 tree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

2 participants