Repository navigation
feat(kvflash): pager slices, step fences, deferred free and the KVFLASH2 blob - #932
Conversation
…SH2 blob KvFlashPager gains the interface the arena, scorer and recall work builds on, and nothing that only they use: - KvFlashConfig::row_base: the pool can be a slice of a larger KV allocation. Rows and block ids the backend sees are arena space (block_of, slot_of, fill_slot_pos, fill_slot_mask, arena_tokens); the serial pagers stay at base 0, where nothing changes. attach validates the slice against the tensors before it touches any state. - Step pins beside the hard pins (pin_step_range / end_step), generation() with page_out_checked so a page-out planned against a request that has since ended does nothing, and abort_step. - Deferred free: set_deferred_free, last_record, pending_free_blocks, complete. A paged-out block becomes allocatable only after the record that freed it completes. Off by default; the serial path keeps one fence per reused block. - set_external_page_stream / page_stream / set_batch_submit, lru_victims, reselect(tail_override) with ties keeping resident chunks, and an identity relayout when a truncate lands on a prefix that fits the pool. - fill_slot_mask(dst, valid_upto): rows at logical positions at or above the bound are masked off; the default keeps every resident row visible. - page_out refuses a pinned chunk, the way eviction already skipped it. serialize() keeps writing KVFLASH3, the pooled snapshot with the pool layout, byte for byte; snapshot_save_pooled_at and kvflash_restore_pooled do not change. KVFLASH2 is the same blob without the pool layout, produced in parts by serialize_to, blob_header, read_chunk and ledger_blob for a writer that keeps chunks apart. deserialize reads both by magic: KVFLASH3 restores the exact layout, KVFLASH2 restores residency in identity order, and the expected chunk count is checked before any state moves. kvflash_require_base_zero guards the two serial-only consumers in qwen35_backend.cpp (identity prefill sync, the single-mask upload), and the identity sync in layer_split_kvflash.h and the shard daemon refuses a slice. The mask and position buffers are arena-sized, which equals pool-sized at base 0. Tests: KvflashPagerSerde grows from 19 to 45 cases (a KVFLASH3 blob captured from main loads and reserializes byte for byte, KVFLASH2 parts, pins, deferred free, generation, row_base slices, and reselect() parity with main for the gemma4/laguna call shape, ties documented, the bounded slot mask), KvflashPagerCudaRace from 3 to 5.
There was a problem hiding this comment.
1 issue found across 8 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="server/src/common/fnv.h">
<violation number="1" location="server/src/common/fnv.h:9">
P2: `kFnvBasis` is not the FNV-1a 64 offset basis: the literal is missing its last digit. Use `14695981039346656037ULL` (or `0xcbf29ce484222325ULL`). Otherwise kvflash ledger and blob hashes will not match FNV-1a values computed by the cluster `fnv1a64` or the HTTP fingerprints.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Re-trigger cubic
|
|
||
| namespace luce::common { | ||
|
|
||
| constexpr uint64_t kFnvBasis = 1469598103934665603ULL; |
There was a problem hiding this comment.
P2: kFnvBasis is not the FNV-1a 64 offset basis: the literal is missing its last digit. Use 14695981039346656037ULL (or 0xcbf29ce484222325ULL). Otherwise kvflash ledger and blob hashes will not match FNV-1a values computed by the cluster fnv1a64 or the HTTP fingerprints.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At server/src/common/fnv.h, line 9:
<comment>`kFnvBasis` is not the FNV-1a 64 offset basis: the literal is missing its last digit. Use `14695981039346656037ULL` (or `0xcbf29ce484222325ULL`). Otherwise kvflash ledger and blob hashes will not match FNV-1a values computed by the cluster `fnv1a64` or the HTTP fingerprints.</comment>
<file context>
@@ -0,0 +1,19 @@
+
+namespace luce::common {
+
+constexpr uint64_t kFnvBasis = 1469598103934665603ULL;
+constexpr uint64_t kFnvPrime = 1099511628211ULL;
+
</file context>
| constexpr uint64_t kFnvBasis = 1469598103934665603ULL; | |
| constexpr uint64_t kFnvBasis = 14695981039346656037ULL; |
There was a problem hiding this comment.
Kept as is. 1469598103934665603ULL is the constant main already uses in six places, including the inline copy at kvflash_pager.h:596 that fnv.h replaces. Here it feeds only the pager's ledger hash in a log line. It is never compared with the cluster fnv1a64 (cluster_protocol.h uses 0xcbf29ce484222325) or with HTTP fingerprints. Changing it here would change the hash main logs, so this PR keeps it for parity. Correcting all six copies is a separate change.
davide221
left a comment
There was a problem hiding this comment.
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: 1c0cbcdee24f747fc468098eaef675cea6ece9c3
Verify the findings against the current code, run relevant checks for any fixes, and explain any findings you reject.
<file name="server/src/common/kvflash_pager.h">
<violation number="1" line="898" end_line="938">
serialize() omits deferred-free blocks from the pool layout, so the pager's own KVFLASH3 blob is rejected by deserialize
With `deferred_free_` on, a paged-out chunk's block is in `pending_free_`, i.e. neither `free_blocks_` nor any `chunks_[c].block`. `serialize()` builds `free_list` only from `free_blocks_` (line 898) plus dropped-tail blocks, so the blob's free-list count satisfies `n_resident + n_free = n_blocks_ - pending_free_.size()`. On load into a pool of the saved size, `deserialize()` takes the `exact` path and rejects the blob at `if (n_resident + n_free != (size_t)n_blocks_) return false;` (line 1068). So a pager with any pending deferred free cannot restore its own snapshot — the documented contract "the pager is exactly the one that was saved" silently fails (and `snapshot_save_pooled_at` consumers would lose the state instead of persisting it). `serialize_to()` inherits the same gap. Fix: include the `pending_free_` blocks in `free_list` (they are free, only not yet allocatable), e.g. append them after the live free list, matching what `complete()` would produce.
</violation>
</file>
Issue overview
-
serialize() omits deferred-free blocks from the pool layout, so the pager's own KVFLASH3 blob is rejected by deserialize · likely (
server/src/common/kvflash_pager.h:898-938)With
deferred_free_on, a paged-out chunk's block is inpending_free_, i.e. neitherfree_blocks_nor anychunks_[c].block.serialize()buildsfree_listonly fromfree_blocks_(line 898) plus dropped-tail blocks, so the blob's free-list count satisfiesn_resident + n_free = n_blocks_ - pending_free_.size(). On load into a pool of the saved size,deserialize()takes theexactpath and rejects the blob atif (n_resident + n_free != (size_t)n_blocks_) return false;(line 1068). So a pager with any pending deferred free cannot restore its own snapshot — the documented contract "the pager is exactly the one that was saved" silently fails (andsnapshot_save_pooled_atconsumers would lose the state instead of persisting it).serialize_to()inherits the same gap. Fix: include thepending_free_blocks infree_list(they are free, only not yet allocatable), e.g. append them after the live free list, matching whatcomplete()would produce.
Reviewed 1c0cbcde · 3 candidate issues checked, kept at ≥70% confidence · add the code-review label to review again
…attach checks every layer's slice serialize() left blocks waiting on their page-out record out of the free list, so deserialize() rejected the pager's own blob on a same-size pool. attach() validated the slice rows on the first K/V tensor only; it now checks every layer before any state changes. The truncate race test now asserts chunk 3 is dropped and its block returned.
|
On the code-review-bot finding ( The same commit also makes |
Why
KvFlashPageron main (server/src/common/kvflash_pager.h) is a pager for one pool that starts at row 0 of the KV allocation and frees a block the moment it is paged out. Work that needs more than that has nothing to build on:block_of,slot_of,fill_slot_posandfill_slot_maskall assume the pool begins at row 0, so two pools cannot share one allocation.page_outon main pushes tofree_blocks_directly). A caller that queues page-outs a step ahead and fences once per step has no way to hold the block until the copy has landed.page_out(c)on main does not checkis_pinned(c); only eviction skips pinned chunks (mainkvflash_pager.h:415-416).reselect()sorts by score alone (main:566,a.s > b.s), so on an exact tie across the resident/host boundary the order is whateverstd::sortleaves. A tie can cause a recall and an eviction for the same bytes.This PR adds the interface for those and nothing that only a later feature uses. With KVFlash off, no code path here runs. With KVFlash on and the serial path, the decisions are the same except for the three differences listed under Limits.
What it does
Line numbers are in
server/src/common/kvflash_pager.hat 2599780 unless a file is named.KvFlashConfig::row_base(:103) makes the pool a slice of a larger KV allocation. Rows and block ids the backend sees are arena space:block_of(:685),slot_of(:703),fill_slot_pos(:711),fill_slot_mask(:758),arena_tokens()(:695). The serial pagers stay at base 0, where these return what they returned before.attachchecks the slice against the tensors (:132-146) before it touches any state.pin_step_range/end_step(:459-461) sit beside the existingpin_range(:422).generation()(:558) withpage_out_checked(:555) makes a page-out planned against a request that has since ended do nothing.abort_step(:563).:635-638).set_deferred_free,last_record,pending_free_blocksandcomplete. With it on, a paged-out block goes to a pending list (:543) and becomes allocatable only aftercomplete(record)for the record that freed it. It is off by default; the serial path keeps one fence per reused block.set_external_page_stream(:581),page_stream(:573),set_batch_submit(:572).lru_victims(n)(:816).reselect(tail_override)(:775): a tail override of N protects only the last N chunks for that call, and a score tie keeps the resident chunk (:790). A truncate to a prefix that fits the pool callsrelayout_identity_(:284,:297) so the block map is the one a fresh pager would have; pool attention reduces over physical slots in order, so the layout is part of the result.fill_slot_mask(dst, valid_upto)(:758): rows at logical positions at or above the bound are masked off. The default,INT64_MAX, keeps every resident row visible, so existing callers are unchanged. A decode step at position p would pass p + 1.page_outrefuses a pinned chunk (:530).kvflash_require_base_zero(:1633) prints a message and callsstd::abort()when a pager has a nonzerorow_base. It guards the two serial-only consumers inserver/src/qwen35/qwen35_backend.cpp(identity prefill sync:2884, single-mask upload:2965).server/src/common/layer_split_kvflash.h:31makes the identity sync return false on a slice, and the shard daemon's identity-sync condition (server/src/qwen35/qwen35_target_shard_ipc_daemon.cpp:585) addsrow_base() == 0. No path in this PR creates a slice, so none of these fire here. The slot-position buffer inserver/src/qwen35/layer_split_forward.cpp:77is nowarena_tokens()long, which equals the pool size at base 0.server/src/common/fnv.hholds the FNV-1a step used by the pager's ledger hash in its log line (:846), replacing the inline constant main has at:596.KVFLASH2 and KVFLASH3
serialize()(:893) keeps writing KVFLASH3, the pooled snapshot with the pool layout, byte for byte.snapshot_save_pooled_atandkvflash_restore_pooledare not changed. KVFLASH2 is the same blob without the pool layout, produced in parts byserialize_to(:946),blob_header(:961),read_chunk(:972) andledger_blob(:996), for a writer that keeps chunks apart.deserialize(:1025) reads both by magic: KVFLASH3 restores the exact layout, KVFLASH2 restores residency in identity block order. The expected chunk count, when given, is checked against the header before any state moves.A test holds a KVFLASH3 blob captured from main's serializer (at 89fddc3, the geometry and seed are in the test). It loads, serializes back byte for byte, and equals what this pager writes for the same state (
test_kvflash_pager_serde.cpp:1120,kvflash3_blob_written_by_main_loads_and_reserializes_byte_for_byte).Left out of this PR
LUCE_KVFLASH_HOST_BACKING(kvflash_host_backing.h, its tests,set_host_backing). It has no caller until a later PR, so it ships with that caller. Here the pager keeps main'sset_pinned_host_backing(bool)(:205) and the singlecudaMallocHostpath.cudaMemcpy2DAsync/cudaMemset2DAsyncper layer and K|V instead of one call per head). This is a performance change with no test need and no benchmark yet, so it is not here: the per-headcudaMemcpyAsync/cudaMemsetAsyncloops are main's, andgpu_runtime_compat.his untouched.Callers that arrive in follow-ups
Used by a follow-up:
row_baseand the arena-space accessors, step pins, deferred free andcomplete,set_external_page_stream,set_batch_submit,page_out_checked,lru_victims, thereselecttail override,fill_slot_mask'svalid_upto, and the KVFLASH2 parts. Nothing insrccallsset_external_page_streamorset_batch_submitafter this PR, and the unit tests do not exercise them.The slice, fence, deferred-free and blob pieces are in one commit because they share the pager header and its tests.
Tests
test_server_unit, filtered to the two fixtures this PR changes:KvflashPagerSerdegoes from 19 to 47 cases,KvflashPagerCudaRacefrom 3 to 5 (CUDA only). The new cases cover: the KVFLASH3 blob from main, KVFLASH2 parts and the streamed blob, the expected-chunk-count check, pinnedpage_out, step pins, deferred free, stale generation,row_baserows, attach refusal and bytes at the offset rows, the reselect tail override and ties,reselect()parity with main for the gemma4/laguna call shape, the truncate layout contract and identity relayout (bytes move, a swap cycle resolves), the bounded slot mask, and a byte-exact page-out/page-in round trip with a partial-chunk truncate on the CUDA side.Full
test_server_unit, passed / failed / skipped, main c5179e4 vs this branch. The difference is 30 on CUDA: 28 newKvflashPagerSerdecases and 2 newKvflashPagerCudaRacecases. It is 28 on HIP, where the CUDA-only race cases do not run.The GPU was idle before each run and one suite ran at a time. Each HIP log names its device (
arch=gfx1201on hip:0,arch=gfx1151on hip:1).Engine run
Qwen3.8-27B (
Qwen3.8-27B-UD-IQ4_XS.gguf, md5 54db94b16b77e3fe024faa893cc4b80d), serial--kvflash 16384, two distinct prompts of 34583 and 37293 tokens, 128 max tokens, temperature 0, seed 1. The pool pages out on every arm, main and branch (pooled prefill: 34583 tokens through a 16384-token pool, and the same for 37293). Run on HIP only (gfx1201 and gfx1151); there is no CUDA engine run for this PR.Setup:
luce_server <model> --max-ctx 65536 --kvflash 16384 --no-kv-cache --cache-type-k q8_0 --cache-type-v q8_0, one server at a time, caches dropped before each arm, prompts sent one after the other.luce_servermd5: main e01ec7db3b155947fc93c00f2acb4a07, branch 1b88cf5be5310ff36189e626291259fc. Arms run in the order main, branch, main repeat on each GPU. All requests showprefix_len=0anddisk_hit=falseon all six arms, so no arm used a prefix or disk cache.The prompts were answered in 61 and 61 tokens on gfx1201 and in 61 and 63 on gfx1151 (finish=stop), the same counts on every arm of a GPU. With two requests, median equals mean, and best and min are the two requests.
Speeds are from the server's
chat DONElines, tokens per second; wall in seconds (best = fastest). The log prints prefill time in steps of 0.1 s, so two runs with the same prefill time show the same prefill tok/s.gfx1201 (hip:0):
gfx1151 (hip:1):
Branch vs the first main run, medians: on gfx1201 prefill 0.0%, decode 0.0%, wall +0.02%; main against its own repeat is -0.12%, 0.0% and +0.05%. On gfx1151 prefill -1.04%, decode 0.0%, wall +0.99%; main against its own repeat is -0.88%, 0.0% and +0.82%. On gfx1151 the first main run was the first after a server start and both later arms sit below it; against the main repeat the branch is -0.16% on prefill. This PR makes no speed claim and shows no speedup.
The tables above are for 1c0cbcd. The review fix 2599780 was run again with the same harness, main (same binary) then branch on each GPU, with no main repeat. Branch
luce_servermd5 562a325f83bbf8d310ae34d146af6546. Text is identical to main on both requests on both GPUs, and identical to the 1c0cbcd arms.prefix_len=0anddisk_hit=falseon all four arms, and every arm logspooled prefillfor both prompts. Branch vs main, medians: gfx1201 prefill 858.44 vs 865.69 tok/s (-0.84%), decode 29.20 vs 29.30 (-0.34%), wall 44.07 vs 43.76 s (+0.71%); gfx1151 prefill 291.51 vs 292.72 (-0.41%), decode 12.90 vs 12.90 (0.0%), wall 128.24 vs 127.74 s (+0.39%). The same main binary gave 865.69 tok/s prefill on gfx1201 in this run and 852.32 in the run above.The server has no logprobs, so near-tie margins between the two builds' token choices cannot be computed; text identity is the comparison.
Limits
--kvflashpath on the two HIP devices. No CUDA engine run, and no run with a sliced pager (nothing in this PR creates one).page_outon a pinned chunk is refused.reselectkeeps the resident chunk, where main's comparator left the order unspecified. The testreselect_score_ties_keep_resident_chunks_where_main_recalled_by_chunk_idrecords main's result for its case, a recall by chunk id.reselect()with no arguments and never pin a step.reselect_without_pins_matches_main_for_gemma4_and_lagunareplays that call shape and compares events, residency and block order with what main's pager produced at 89fddc3. There is no gemma4 or laguna engine run.kvflash_require_base_zeroaborts the process on a sliced pager. It is unreachable in this PR.set_external_page_streamandset_batch_submithave no caller and no test here.LUCE_KVFLASH_HOST_BACKINGare not in this PR (see above).