Repository navigation
fix(kvcache): decode vLLM map-format KV events; tier-aware prefix scoring - #2587
Conversation
There was a problem hiding this comment.
Code Review
This pull request adds compatibility with newer vLLM wire formats (including msgspec map encoding) and introduces tier-aware scoring (GPU, CPU, STORAGE) for prefix cache routing. Feedback on the changes highlights a potential decoding failure in decodeBatchArray due to a strict float64 type assertion on the timestamp, as well as issues where a pod's storage medium is not updated when the pod already exists in the prefix store, leading to stale tier information.
| tsFloat, ok := arr[0].(float64) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid batch timestamp type: %T", rawBatch[0]) | ||
| return nil, fmt.Errorf("invalid batch timestamp type: %T", arr[0]) | ||
| } |
There was a problem hiding this comment.
In decodeEventArray, the switch statement accepts various numeric types for the timestamp (e.g., int, int64, float32, etc.). However, inside decodeBatchArray, there is a strict type assertion to float64 (tsFloat, ok := arr[0].(float64)). If the timestamp is decoded as any other numeric type, this assertion will fail, resulting in a decoding error. We should use a type switch to robustly convert any of the accepted numeric types to float64.
var tsFloat float64
switch x := arr[0].(type) {
case float64:
tsFloat = x
case float32:
tsFloat = float64(x)
case int:
tsFloat = float64(x)
case int8:
tsFloat = float64(x)
case int16:
tsFloat = float64(x)
case int32:
tsFloat = float64(x)
case int64:
tsFloat = float64(x)
case uint:
tsFloat = float64(x)
case uint8:
tsFloat = float64(x)
case uint16:
tsFloat = float64(x)
case uint32:
tsFloat = float64(x)
case uint64:
tsFloat = float64(x)
default:
return nil, fmt.Errorf(\"invalid batch timestamp type: %T\", arr[0])
}| } else { | ||
| pods[podName] = &PodInfo{ | ||
| SourcePod: podName, | ||
| Medium: medium, |
There was a problem hiding this comment.
When the pod already exists in the pods map (the if block of this conditional, which is outside this diff), we only update its LastAccessTime but do not update its Medium. If a prefix is migrated to a different storage tier, the tier information will remain stale. Please ensure that podInfo.Medium = medium is also updated when the pod already exists.
| } else { | ||
| pods[podName] = &PodInfo{ | ||
| SourcePod: podName, | ||
| Medium: medium, |
39be9ed to
059fe5e
Compare
There was a problem hiding this comment.
Pull request overview
This PR restores compatibility with current vLLM KV-event msgpack wire formats (including the post-#42892 map encoding) and improves prefix-routing correctness by carrying tier/adaptor/group metadata end-to-end and weighting prefix match scores by storage tier.
Changes:
- Extend KV-event decoding to accept map-encoded single events, legacy tag-first arrays, and
[ts, events]batch wrappers; decode additional vLLM fields (medium,lora_name,group_idx,extra_keys, etc.). - Add tier-aware prefix scoring by recording
mediumper (prefix, pod) and weightingMatchPrefixscores (GPU/CPU/STORAGE). - Plumb
medium/lora_name/group_idxthrough the kvevent handler and store-provider adapter into the sync prefix indexer; add focused compatibility and scoring tests.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| pkg/utils/syncprefixcacheindexer/sync_hash.go | Record per-pod storage tier for prefixes and weight MatchPrefix scores by tier; add APIs to add prefixes with medium. |
| pkg/utils/syncprefixcacheindexer/medium_scoring_test.go | New tests validating tier weighting via both direct prefix insertion and event ingestion. |
| pkg/utils/syncprefixcacheindexer/events.go | Extend sync event structs to carry medium, lora_name, and group_idx. |
| pkg/kvevent/interfaces.go | Extend kvevent interfaces to include tier/adaptor/group metadata. |
| pkg/kvevent/handler.go | Populate and forward medium/lora_name/group_idx from decoded KV events into sync events. |
| pkg/cache/store_providers.go | Plumb new metadata through the sync indexer adapter. |
| pkg/cache/kvcache/msgpack_decoder.go | Decode vLLM map-format events and legacy single-event arrays; broaden decoding to all supported shapes and fields. |
| pkg/cache/kvcache/event_types.go | Extend KV event types with additional optional fields retained during decode. |
| pkg/cache/kvcache/decoder_vllm_compat_test.go | New byte-exact fixtures ensuring decoder compatibility with real vLLM payload shapes. |
Suppressed comments (1)
pkg/utils/syncprefixcacheindexer/sync_hash.go:583
- addPrefixToPodLocked has the same issue as AddPrefixWithMedium: when the pod entry already exists, it doesn't update PodInfo.Medium. That can leave tier info stale across repeated BlockStored events and skew MatchPrefix weighting.
if podInfo, exists := pods[podName]; exists {
podInfo.LastAccessTime.Store(now)
} else {
pods[podName] = &PodInfo{
SourcePod: podName,
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| func toExtraKeys(v any) ([][]interface{}, error) { | ||
| if v == nil { | ||
| return nil, nil | ||
| } | ||
| raw, ok := v.([]interface{}) | ||
| if !ok { | ||
| return nil, fmt.Errorf("expected []interface{}, got %T", v) | ||
| } | ||
| out := make([][]interface{}, len(raw)) | ||
| for i, x := range raw { | ||
| if x == nil { | ||
| out[i] = nil | ||
| continue | ||
| } | ||
| entry, ok := x.([]interface{}) | ||
| if !ok { | ||
| return nil, fmt.Errorf("extra_keys[%d]: expected []interface{}, got %T", i, x) | ||
| } | ||
| out[i] = entry | ||
| } | ||
| return out, nil | ||
| } |
| // 0: batch timestamp | ||
| tsFloat, ok := rawBatch[0].(float64) | ||
| tsFloat, ok := arr[0].(float64) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid batch timestamp type: %T", rawBatch[0]) | ||
| return nil, fmt.Errorf("invalid batch timestamp type: %T", arr[0]) | ||
| } |
| if podInfo, exists := pods[podName]; exists { | ||
| podInfo.LastAccessTime.Store(now) | ||
| } else { | ||
| pods[podName] = &PodInfo{ | ||
| SourcePod: podName, |
|
Thanks for the PR. The tier-aware scoring and format compatibility improvements look solid, but there are a few edge cases involving state updates and logic duplication that need addressing:
|
|
1. Stale Currently, This breaks the feature this PR is adding. ZMQ is at-least-once, and vLLM CPU offload can emit another Please update the medium on the existing path, ensuring an empty value doesn't overwrite a known tier: if podInfo, exists := pods[podName]; exists {
podInfo.LastAccessTime.Store(now)
if medium != "" {
podInfo.Medium = medium
}
}Suggestion: Add a test that stores the same 2. "Current vLLM" fixtures do not match the real ZMQ shape ( The live The new tests cover:
They never cover Suggestion: Add a fixture encoded as a real |
|
Bumping this. Running into the same issue |
bolubo
left a comment
There was a problem hiding this comment.
I went through the current head (059fe5ec) and the follow-up commit. The map-format decoding and the fixtures look right; three things are still open.
1. lint is red because of the duplicated optional-field parsing.
lint is the only failing check on this PR, and the annotation says:
pkg/cache/kvcache/msgpack_decoder.go:159: cyclomatic complexity 38 of func `parseEventArray` is high (> 30) (gocyclo)
I think most of that complexity sits in the eight optional-field blocks for BlockStored (lines 229-268). They account for about 16 of the 38 decision points, and they are the same duplication the earlier review asked to consolidate. Pulling them into one helper shared by parseEventArray (line 159) and parseEventMap (line 320) should bring the function back under the threshold. Job log: https://github.com/vllm-project/aibrix/actions/runs/32333976535/job/96326109310
2. A repeat BlockStored does not update the tier (reproduced on 059fe5ec).
Both addPrefixToPodLocked (line 579) and AddPrefixWithMedium (line 438) write Medium only when the (prefix, pod) entry is created; on an existing entry they only refresh LastAccessTime. So a same-pod GPU then CPU report for the same block keeps scoring 100 instead of 50. With store(m) wrapping ProcessBlockStored for the same block and pod:
store(MediumGPU) // creates the entry with GPU
store(MediumCPU) // repeat BlockStored, same block/pod
matched, _ := table.MatchPrefix(model, -1, block1, readyPods)
// got matched["p1"] == 100, expected 50The tests in this PR give each tier its own pod, which is why this one stays green. Two notes for the fix: only write the tier when the event carries one, and the write needs to land in addPrefixToPodLocked too, since that is the path the ZMQ events take (the AddPrefix callers never pass a tier).
3. A question about the new max-weighting in MatchPrefix.
MatchPrefix now keeps the maximum weighted value per pod (sync_hash.go:241), so a shorter GPU match can outrank a longer CPU match: 50% on GPU gives 50, 60% on CPU gives 30, and 50 wins. Before this change the value was simply the longest matched prefix as a percent. If the intent is still "longest match, discounted by its tier", I think the code should pick the longest matched prefix first and weight that, instead of maxing across prefixes. Since ScoreAll feeds these numbers straight into routing (prefix_cache.go:616), could you confirm which one is intended?
|
@wuyan-zs could you please resolve the linter issue? We are getting close to cut v0.8.0 release, it would be great to have this fix merged |
|
Since 0.24, the event was changed from array to map. now, aibrix only supports array, which is definitely an issue to resolve |
…ring - DecodeEventBatch now accepts the msgspec map encoding vLLM switched to in vllm-project/vllm#42892 (single event per ZMQ message, flat map with a `type` key), the legacy tag-first array encoding, and the [ts, events] batch wrapper. Previously every map payload failed to unmarshal, so kv-events prefix routing was broken against current vLLM. - BlockStored/BlockRemoved now parse all fields: lora_id, medium, lora_name, extra_keys, group_idx, kv_cache_spec_kind, kv_cache_spec_sliding_window, locality (map and array forms). - syncprefixcacheindexer records the storage medium per (prefix, pod) and weights MatchPrefix scores (GPU=1.0, CPU=0.5, STORAGE=0.25; unspecified keeps full score) so pods holding a prefix only on a slower tier are not over-credited. - Plumb medium/lora_name/group_idx through the kvevent handler and the store provider adapter (previously dropped at the handler). Fixes vllm-project#2285 Signed-off-by: wuyan-zs <[email protected]>
Signed-off-by: Jiaxin Shan <[email protected]>
fa332a4 to
1cba3c6
Compare
|
I add a commit 1cba3c6 to resolve the CI issues. Let's get this merged and rest feedback can be handled in another PR |
Design simplification reviewScope: Unblock kv-events against current vLLM (map-encoded events after vllm#42892), parse the optional BlockStored/BlockRemoved fields from #2285, and weight prefix-match scores by storage What works
Simpler / clearer alternatives
Verdict: nitsShape is proportionate for a wire-compat + scoring fix. Main design follow-ups are consolidation of duplicated parse/update paths and clarifying MatchPrefix’s max-vs-longest rule — not redesigning the feature. |
Code reviewHead: Correctness
if podInfo, exists := pods[podName]; exists {
podInfo.LastAccessTime.Store(now)
if medium != "" {
podInfo.Medium = medium
}
}Please add a same-pod GPU→CPU regression (expect 100→50). The ZMQ path goes through
Tests / compatibility
RiskDecoder path is high value for v0.8.0 (kv-events dead against current vLLM). Tier scoring is only as correct as medium updates + removal scoping; shipping decoder-only would still be a win if scoring follow-ups are tracked. Noted Jeffwan’s intent to merge and defer remaining feedback — calling out the stale-medium bug so it is not lost. Verdict: concernsMap/array decode + plumbing look sound and CI is green, but the unrepaired stale- |
varungup90
left a comment
There was a problem hiding this comment.
The decoder accepting the map, tag-first array and [ts, events] batch shapes looks sound. Two inline comments on the tier-aware scoring: the recorded Medium is never updated on an existing entry, and BlockRemoved.Medium is plumbed through but not used when removing. One inline question about the vLLM wire-format claim. I read the code and did not run the tests.
Generated by Claude Code
| } else { | ||
| pods[podName] = &PodInfo{ | ||
| SourcePod: podName, | ||
| Medium: medium, | ||
| } | ||
| pods[podName].LastAccessTime.Store(now) | ||
| } |
There was a problem hiding this comment.
The storage tier is only recorded when a pod's entry for a prefix is first created.
When pods[podName] already exists (the branch just above), only LastAccessTime is refreshed, so Medium never changes. The same applies to AddPrefixWithMedium.
Scenario: a pod stores a block on GPU (entry is GPU), then the block is offloaded and vLLM emits BlockStored(medium=CPU) for the same hash. The entry stays GPU, so the pod keeps full credit for a slower tier. The reverse also happens: a CPU entry is never promoted when the block comes back to GPU, so the pod is under-credited.
Suggestion: update Medium on the existing entry, or keep the best tier per pod.
Generated by Claude Code
There was a problem hiding this comment.
the problem still exist. While, this is the scope of this PR. it should be separate one. the latest commit just fix the CI issue. the remaining problem will be handled separately
| LoraID int64 // -1 for no adapter | ||
|
|
||
| // Medium is the storage tier the blocks live on ("GPU"/"CPU"/"STORAGE"). | ||
| Medium string |
There was a problem hiding this comment.
BlockRemoved.Medium is plumbed through the handler and adapter but nothing uses it.
ProcessBlockRemoved (sync_hash.go, around line 411) still does delete(pods, event.SourcePod) whatever tier was evicted.
Scenario: a block is cached on both GPU and CPU and the CPU copy is evicted (BlockRemoved(medium=CPU)). The pod is dropped from the index even though the GPU copy is still there. In the other direction, when the GPU copy goes while a CPU copy remains, the pod is also dropped entirely, so the CPU = 0.5 credit never applies.
Suggestion: make removal tier-aware (only remove the entry if the removed tier matches the recorded one, or track per-tier presence), or document that the field is reserved for a follow-up.
Generated by Claude Code
| "k8s.io/klog/v2" | ||
| ) | ||
|
|
||
| // DecodeEventBatch parses a raw msgpack batch of events. | ||
| // DecodeEventBatch parses a raw msgpack payload of KV cache events. | ||
| // The subscriber must supply batch timestamp + model/pod name. | ||
| // | ||
| // The real vLLM ZMQ publisher emits ONE event per message, encoded with | ||
| // msgspec: | ||
| // | ||
| // - vLLM >= #42892 (2026-06): map encoding, a flat map with a "type" key: | ||
| // {"type": "BlockStored", "block_hashes": [...], ...} | ||
| // - vLLM < #42892: positional array encoding with the tag first: | ||
| // ["BlockStored", block_hashes, parent_block_hash, token_ids, block_size, ...] |
There was a problem hiding this comment.
Question: could you link vllm-project/vllm#42892, or the captured payloads the new tests are built from? The doc comment says the real publisher emits one event per message, as a map since #42892 and as a tag-first array before it. I can't verify that wire change from this repo. Because the decoder also accepts the [ts, events] batch shape, it is a superset either way, so this is only about making the compatibility claim checkable for reviewers.
Generated by Claude Code
There was a problem hiding this comment.
The follow-up will also correct the wire-format doc comment (the publisher sends one array-like EventBatch per message, [ts, [map events], dp_rank]) and add a fixture of that shape.
The CI takes too long to finish now and there's a waiting queue. Let's merge this author's PR first so I can file separate improvements
|
I cut vllm-project/aibrix#2947 to track unfinished items |
Summary
Fixes #2285. While investigating, I found a larger compatibility break:
vLLM switched KV event encoding from positional arrays to msgpack maps in
vllm-project/vllm#42892
(merged 2026-06-09).
DecodeEventBatchstill expected[ts, events]arrays,so every KV event payload from current vLLM fails to unmarshal
(
msgpack: invalid code=0x88 decoding array length) — kv-events prefixrouting is effectively dead against current vLLM. The legacy publisher also
sent one event per ZMQ message (tag-first array), which the batch-shaped
decoder never handled either.
Changes
pkg/cache/kvcache/msgpack_decoder.go: accept all three wire shapes —map single event (current vLLM), tag-first array single event (legacy
vLLM), and
[ts, events]batch (older code paths / test encoder).BlockStored/BlockRemovedfield:lora_id,medium,lora_name,extra_keys,group_idx,kv_cache_spec_kind,kv_cache_spec_sliding_window,locality.pkg/utils/syncprefixcacheindexer: record the storagemediumper(prefix, pod) and weight
MatchPrefixscores (GPU=1.0, CPU=0.5,STORAGE=0.25; unspecified keeps full score for backward compatibility)
so pods holding a prefix only on a slower tier are not over-credited.
medium/lora_name/group_idxthrough thekveventhandler andstore_providersadapter (previously dropped at the handler).Tests
New
decoder_vllm_compat_test.goverifies decoding against byte-exactpayloads generated with the real msgspec encoder for both current map and
legacy array formats (single-event and batch shapes). New
medium_scoring_test.gocovers tier weighting viaAddPrefixWithMediumandthe event ingestion path. All existing
kvcacheandsyncprefixcacheindexertests keep passing.Follow-up
The
(model, lora_name, group_idx)index keying part of #2285 needs arequest-side adapter id (
RoutingContexthas no LoRA field today); see theissue thread.