no-hit-lru-scorer decides in Score whether a request is cold, meaning no candidate reports a matched block, and kept that one verdict per request ID (Fixes #4747).What type of PR is this?
/kind bug
What this PR does / why we need it:
no-hit-lru-scorer decides in Score whether a request is cold, meaning no candidate reports a matched block, and kept that one verdict per request ID. In P/D one instance sits in both the decode and the prefill profile and scores each request twice, each time with that profile's candidates, so the second call replaced the first. PreRequest then applied the last verdict to both targets. A cold decode stage next to a cached prefill stage never entered the LRU, and a decode pod that served a cached stage was recorded as cold. The README says a pod joins the LRU "when it serves a cold request, not when it serves a cached one".
The two stages disagree when only one pool is credited with a prompt's prefix. precise-prefix-cache-producer seeds a disaggregated request on the prefill endpoint only (#4403), and approx-prefix-cache-producer does the same with excludeDecodeWhenDisaggregated (#3760), so a repeat sees a cached prefill stage and a cold decode stage. The reverse happens when prefix-based-pd-decider keeps a short turn decode-only and then sends a longer turn with the same prefix to prefill.
Score now adds the candidates of each cold call to a set in the request's state, and PreRequest moves a target only when it is in that set, so each target follows the verdict of the profile that scored it, in both stage orders. A prefill-decode pod that is a candidate in both profiles stays in the set when only one call was cold, because that call shows the pod had no matched block. A warm call writes no state, so a request without a cold call takes the existing missing-state path in PreRequest. The diff is coldRequestState, Score, a new recordColdCandidates helper, PreRequest (its early return for a warm verdict goes) and the check in moveTargetPodToFront, all in no_hit_lru.go, plus the tests below in no_hit_lru_test.go. No parameter or config changes.
Which issue(s) this PR fixes:
Fixes #4747
Release note _(write NONE if no user-facing change)_:
Fixed no-hit-lru-scorer in P/D deployments: the decode and prefill pods each join the cold-request LRU only when their own scheduling profile found no prefix-cache hit, instead of both following the profile that was scored last.
Test plan:
prefill-decode pod picked by the cold decode stage stays recorded when the prefill stage, which also had it as a candidate, finds a hit on another pod.The three cases fail on main caab1619 and pass with this change:
$ GOTOOLCHAIN=auto go test -race -p 2 -count=1 -run 'TestNoHitLRUPrefillDecodeTracking|TestNoHitLRUEndpointInBothProfiles' ./pkg/epp/framework/plugins/scheduling/scorer/nohitlru/
# main caab1619
--- FAIL: TestNoHitLRUPrefillDecodeTracking (0.00s)
--- FAIL: TestNoHitLRUPrefillDecodeTracking/cold_decode_cached_prefill (0.00s)
no_hit_lru_test.go:565: LRU after P/D request (-want +got):
[]string{
- "default/decode-a",
}
--- FAIL: TestNoHitLRUPrefillDecodeTracking/cached_decode_cold_prefill (0.00s)
no_hit_lru_test.go:565: LRU after P/D request (-want +got):
[]string{
+ "default/decode-a",
"default/prefill-a",
}
--- FAIL: TestNoHitLRUEndpointInBothProfiles (0.00s)
no_hit_lru_test.go:595: LRU after P/D request (-want +got):
[]string{
- "default/pd-a",
}
FAIL
# with this change
ok github.com/llm-d/llm-d-router/pkg/epp/framework/plugins/scheduling/scorer/nohitlru 1.550s
$ GOTOOLCHAIN=auto go test -race -p 2 -count=20 ./pkg/epp/framework/plugins/scheduling/scorer/nohitlru/
ok github.com/llm-d/llm-d-router/pkg/epp/framework/plugins/scheduling/scorer/nohitlru 1.592s
go test -race -p 2 -count=1 ./pkg/epp/framework/plugins/scheduling/... ./pkg/epp/scheduling/... passes in all 42 packages that have tests, and go vet ./pkg/epp/framework/plugins/scheduling/... and gofmt -l on the package report nothing.
A throwaway harness on the real scheduler (not in this PR) shows the effect on placement. It uses the disagg profile handler, the role filters, max-score-picker, and prefix-cache-scorer (weight 3) next to one no-hit-lru-scorer (weight 2) in both profiles, with 4 decode and 4 prefill pods, 12 requests with a 100-token prompt, 50 blocks cached on pod 0 of one pool, no load signal, and the scorer's PreRequest after each request:
$ GOTOOLCHAIN=auto go test -p 2 -count=1 -run TestZZNoHitLRUPDHarness -v ./pkg/epp/framework/plugins/scheduling/scorer/nohitlru/
# main caab1619
decode_first_cold_decode_cached_prefill: cold decode stage on 1 of 4 pods (busiest 12 of 12)
decode_first_cached_decode_cold_prefill: default/decode-0, which served only cached stages, in the LRU after 12 of 12 requests
prefill_first_cold_prefill_cached_decode: cold prefill stage on 1 of 4 pods (busiest 12 of 12)
prefill_first_cached_prefill_cold_decode: default/prefill-0, which served only cached stages, in the LRU after 12 of 12 requests
# with this change
decode_first_cold_decode_cached_prefill: cold decode stage on 4 of 4 pods (busiest 3 of 12)
decode_first_cached_decode_cold_prefill: default/decode-0, which served only cached stages, in the LRU after 0 of 12 requests
prefill_first_cold_prefill_cached_decode: cold prefill stage on 4 of 4 pods (busiest 3 of 12)
prefill_first_cached_prefill_cold_decode: default/prefill-0, which served only cached stages, in the LRU after 0 of 12 requests
These are four of the harness's eight lines; in the other four (the pod that served only cached stages in the first and third cases, and the cold stage's spread in the second and fourth) main and this change print the same values.
make -k presubmit passes every target except verify-review-playbook, which fails the same way on main caab1619 for two files this PR does not touch (#4616 routes them):
$ make -k presubmit
All commits are cryptographically signed and have DCO sign-offs.
==== Running go fmt ====
==== Running linting ====
0 issues.
==== Running security linting ====
0 issues.
==== Running govulncheck ====
Your code is affected by 0 vulnerabilities.
BUNDLE ERROR: playbooks/review_a_pull_request.md: unrouted production Go file 'pkg/epp/framework/common/duration/seconds.go' matches no production routing row
BUNDLE ERROR: playbooks/review_a_pull_request.md: unrouted production Go file 'pkg/epp/framework/plugins/requesthandling/forwardtokens/plugin.go' matches no production routing row
make: *** [verify-review-playbook] Error 1
Not run: make test-unit, which runs every package in the module inside the builder container, and the e2e suites, which need a KIND cluster. The -race run above covers this package and the scheduler code that calls it.
Fixes no-hit-lru-scorer in P/D deployments so decode and prefill targets independently join the cold-request LRU only when their own scoring pass found no KV cache hit. Previously, Score overwrote a single isCold boolean per request ID, causing the last scored profile's verdict to govern both targets in PreRequest. The scorer interface, configuration parameters, and LRU ranking logic remain unchanged.
isCold bool on coldRequestState (pkg/epp/framework/plugins/scheduling/scorer/nohitlru/no_hit_lru.go:71-73) with coldEndpoints sets.Set[fwkdl.ID].Score (no_hit_lru.go:303-316), warm calls return neutral 0.5 scores without writing or overwriting pluginState, while cold calls invoke recordColdCandidates (no_hit_lru.go:320-330) to insert all scored candidate IDs for that call into coldEndpoints.PreRequest (no_hit_lru.go:334-359) and moveTargetPodToFront (no_hit_lru.go:361-376), each profile's chosen TargetEndpoints[0] is added to lruCache only if its ID is present in coldEndpoints (missing state continues to return early).req-1 runs the decode profile with cold candidates [decode-a, decode-b]: Score sees no matched blocks and inserts decode-a and decode-b into coldEndpoints.req-1 runs the prefill profile with [prefill-a (5 matched blocks), prefill-b]: Score detects a cache hit, returns 0.5 for all candidates, and leaves coldEndpoints untouched.PreRequest receives targets decode-a and prefill-a: decode-a is in coldEndpoints and joins the LRU, while prefill-a is not in coldEndpoints and is skipped.session_id strategy a binding expires evictionTtlSeconds after its last dispatch, also when that request is still running. so after a turn longer than the ttl (300s by default) the next turn is placed like a new... (Fixes #4760)What type of PR is this?
/kind bug
What this PR does / why we need it:
with the session_id strategy a binding expires evictionTtlSeconds after its last dispatch, also when that request is still running. so after a turn longer than the ttl (300s by default) the next turn is placed like a new session, with the bound pod still a candidate.
this counts the requests running for a session on a pod. the sweep keeps a binding that has one, and the ttl restarts when a request on the bound pod ends. a request left on the pod a session migrated away from doesn't hold or refresh the new binding.
the end of the request is the end of the ext_proc stream context, same lifetime inflight-load-producer binds to (#2313), through context.AfterFunc like RequestEvictor. i tried a ResponseBody hook first, like session-state-producer. it made the filter and the scorer streaming plugins for both strategies, about 0.3us per chunk per instance in a director bench, and if no other streaming plugin is configured also the per response queue. with the context it's about 0.4us more in PreRequest, 2.1us more per request in total, and around 600 bytes while it runs, only for requests with a session id.
i went through the paths from PreRequest to the end of the request (normal end, trailers, aborts, upstream errors, failing PreRequest plugin, 412, skipped response processing, eviction, panics) with the real handler and director, none leaves a count behind. the time in the flow control queue is before PreRequest and not covered.
300 sessions on 4 pods, think time at most 60s, follow-ups more than 310s after the previous start: 2271 of 2987 moved before, 0 after.
(ai-assisted, checked by me)
Which issue(s) this PR fixes:
Fixes #4760
Release note _(write NONE if no user-facing change)_:
Session affinity with the `session_id` strategy keeps a session's binding while one of its requests is running. `evictionTtlSeconds` counts from the end of the last request on the bound pod.Prevents active session_id affinity bindings from expiring while a request is still running on the bound pod, and restarts evictionTtlSeconds when the request stream ends rather than when it was dispatched. SessionIDHeader tracks per-(sessionID, podName) in-flight counts tied to the ext_proc stream context lifetime via context.AfterFunc. Choose, ResponseHeader, encoded_endpoint_header behavior, and all plugin configuration schemas remain unchanged.
(sessionID, podName) placement in SessionIDHeader.running (map[placement]int), guarded by s.mu (session_id.go#L140-L163, session_id.go#L214-L218).PreRequest, when ctx.Done() != nil, increments s.running[{sessionID, podName}] under s.mu and registers context.AfterFunc(ctx, func() { s.requestDone(p) }) (session_id.go#L342-L347).requestDone, decrements and deletes the zero-count running entry under s.mu, and refreshes lastSeen only if s.bindings still maps sessionID to p.podName (session_id.go#L385-L401).runEviction, checks s.running[placement{sessionID, b.podName}] == 0 under s.mu before calling s.bindings.CompareAndDelete (session_id.go#L460-L466).s1 is routed to pod-a at t = 0s with evictionTtlSeconds = 300; PreRequest binds s1 -> pod-a and increments running[{s1, pod-a}] to 1.t = 320s, runEviction sees lastSeen is past 300s, acquires s.mu, observes running[{s1, pod-a}] == 1, and skips eviction.t = 320s, Turn 1's ext_proc stream closes; requestDone decrements and deletes {s1, pod-a} from running and updates lastSeen to 320s.t = 610s (290s after Turn 1 ended) still routes to pod-a; if idle until t = 620s+, the next sweep evicts the binding.parameters block (Fixes #4907).What type of PR is this?
/kind bug
What this PR does / why we need it:
The config loader passes a nil decoder to a plugin factory when the plugin entry has no parameters block. The request-attribute-reporter factory decoded into it without a check, so such a config crashed the EPP with a nil pointer panic at startup and under --validate-config.
The factory returns request-attribute-reporter: parameters are required, matching the other factories whose parameters are mandatory.
Which issue(s) this PR fixes:
Fixes #4907
Release note _(write NONE if no user-facing change)_:
The EPP reports a configuration error instead of crashing when a request-attribute-reporter plugin entry has no parameters.
Test plan:
go test -race ./pkg/epp/framework/plugins/requesthandling/requestattributereporter/...gofmt -l and go vet clean; make git-branch-check signed-commits-check verify-boilerplate pass; make presubmit not run locally (Docker unavailable)Prevents a startup and --validate-config nil-pointer panic in RequestAttributeReporterPluginFactory when an EndpointPickerConfig plugin entry omits parameters. The factory now rejects a nil *json.Decoder with request-attribute-reporter: parameters are required before decoding, while behavior for configurations with parameters (including empty {} validated by New) remains unchanged.
instantiatePlugins, which passes fwkplugin.StrictDecoder(spec.Parameters) (nil when len(raw) == 0) to RequestAttributeReporterPluginFactory.RequestAttributeReporterPluginFactory checks rawParameters == nil first and returns fmt.Errorf("%s: parameters are required", RequestAttributeReporterType) before calling rawParameters.Decode(&pluginConfig).TestFactoryWithoutParameters exercises the nil decoder path directly.EndpointPickerConfig declares - name: reporter / type: request-attribute-reporter with no parameters field.StrictDecoder(spec.Parameters) returns nil and passes it to RequestAttributeReporterPluginFactory.rawParameters == nil triggers early return with request-attribute-reporter: parameters are required, which instantiatePlugins wraps as a configuration error instead of panicking.SessionIDHeader.Choose records, per request, whether the session's bound pod was a candidate; PreRequest is its only reader and did not delete it, so the record of every bound-session request stayed in the PluginState until... (Fixes #4017)What type of PR is this?
/kind bug
What this PR does / why we need it:
SessionIDHeader.Choose records, per request, whether the session's bound pod was a candidate; PreRequest is its only reader and did not delete it, so the record of every bound-session request stayed in the PluginState until the janitor reaped it five minutes later. PreRequest now releases the record on every exit, after the migration path has read it. Choose keys the record by request ID, and PreRequest registers the release before it resolves the session ID, so the release also runs when an earlier PreRequest plugin has removed or rewritten the session header. The filter and the scorer share this code, so both instances are covered.
Which issue(s) this PR fixes:
Fixes #4017
Release note:
`session-affinity-filter` and `session-affinity-scorer` (session_id strategy) release their per-request state in PreRequest instead of leaving it to the PluginState janitor.
Testing
TestSessionIDHeader_PreRequest_ReleasesPresenceRecord: after Choose and PreRequest the request has no entry left in the PluginState and the binding is as before, for a bound pod that was present and picked, a bound pod that was absent (the session migrates), a scheduling result without the profile, and a session header removed between Choose and PreRequest. All four fail on the base commit with the record still present. Releasing only once the session ID resolves makes the fourth fail, and releasing only below the profile check makes the third fail as well.
go test for the util, filter and scorer packages and the TestSessionAffinity* integration tests, go vet, gofmt -l, golangci-lint run with the repo config, go test -race for the util package: clean.
Releases the per-request bound-pod presence record in SessionIDHeader.PreRequest on every exit path, including nil-safe handling and cases where an earlier PreRequest plugin removes or rewrites the session header before PreRequest runs. Unbound requests still skip PluginState writes in Choose, and requests that abort before PreRequest continue to rely on the five-minute PluginState janitor.
request at SessionIDHeader.PreRequest and immediately registers defer s.pluginState.Delete(request.RequestID) before resolveSessionID and pickedPodName.session-affinity-filter and session-affinity-scorer instance owns a private s.pluginState storing only s.pluginKey, Delete safely clears both storage and requestToLastAccessTime without affecting other plugins.defer ordering runs s.mu.Unlock() before Delete, after any migration check reads ReadPluginStateKey at session_id.go:358.x-session-id: s1 enters Choose while s1 is bound to pod-a, writing &boundPodPresence{podName: "/pod-a", present: true} to s.pluginState under req.RequestID.Director.runPreRequestPlugins, an earlier PreRequest plugin deletes or rewrites x-session-id, or SchedulingResult omits the target profile.SessionIDHeader.PreRequest returns early after resolveSessionID or pickedPodName, the deferred s.pluginState.Delete(request.RequestID) removes both the presence record and LastAccessTime entry immediately.What type of PR is this?
/kind bug
What this PR does / why we need it:
The vLLM HTTP render transport kept idle connections for 90 seconds, and vLLM's HTTP server closes an idle keep-alive connection after 5 seconds. A render request written to a connection the server is closing failed with EOF or a broken pipe. postJSON retries only on a different endpoint, so with a single render sidecar the request failed.
This sets the render transport's idle timeout to 4 seconds and marks render requests idempotent (Idempotency-Key with a nil value, so no header is sent). The transport then resends a render request on a new connection when the server closed a reused one. Render has no side effects.
Tests:
EOF without the change.The tokenizer package tests pass with the host Go toolchain, and golangci-lint v2.14.0 (the builder's version) with .golangci.yml reports no issues in the package and no formatting changes. I could not run make presubmit, which needs the builder container.
Which issue(s) this PR fixes:
Fixes #4230
Release note _(write NONE if no user-facing change)_:
The vLLM HTTP tokenizer resends a render request on a new connection when the render server has closed an idle keep-alive connection, instead of failing the request.Prevents spurious EOF and broken-pipe failures when vLLM closes an idle HTTP/1.1 keep-alive connection (default 5s) while the EPP tokenizer render client reuses it. The change lowers the render transport idle pool timeout to 4s and marks outbound POST render requests as idempotent for Go's transport layer without emitting an Idempotency-Key header on the wire. Endpoint-level retry logic, response decoding, and request payload construction stay unchanged.
t.IdleConnTimeout to renderIdleConnTimeout (4 * time.Second), below vLLM's 5s VLLM_HTTP_TIMEOUT_KEEP_ALIVE default so idle sockets are closed client-side first.httpReq.Header["Idempotency-Key"] = nil in postJSONAttempt. Because http.NewRequestWithContext wraps bytes.NewReader(payload) (GetBody != nil), net/http treats the request as replayable (isReplayable() checks key presence) while Header.writeSubset writes zero header lines for a nil slice.Render transparently resends on a second connection.r.Render -> postJSONAttempt sends POST /v1/completions/render on connection conn-1 and receives 200 OK; conn-1 returns to the idle pool.4s elapses, vLLM's 5s keep-alive timer races and closes conn-1 while Request 2 writes its payload to conn-1 and receives EOF (errServerClosedIdle).net/http.Transport sees conn-1 was reused and httpReq.isReplayable() is true (via GetBody + Idempotency-Key map entry), rewinds the body, dials conn-2, and succeeds without failing the single-endpoint postJSON call.What type of PR is this?
/kind bug
What this PR does / why we need it:
The models data source buffers an entire model-server response before parsing JSON. Limit reads to the same 8 MiB cap used by the metrics source. Move the existing cap to source/http so both parsers use one constant; metrics behavior is unchanged. DCGM and transport behavior remain outside this change.
Which issue(s) this PR fixes:
Fixes #4733
Release note _(write NONE if no user-facing change)_:
The models data source reads at most 8 MiB from each model-server response, limiting memory use when a server returns an oversized body.
Validation:
make presubmit exits 2 solely at verify-review-playbook: unchanged pkg/epp/framework/common/duration/seconds.go and pkg/epp/framework/plugins/requesthandling/forwardtokens/plugin.go have no routing row. The same errors reproduce on untouched main a4e84c4e in the same builder. No check was skipped and no unrelated policy file is changed.AI assistance: Codex assisted with the patch, review, local checks, and PR preparation. No GPU, model service, cluster, or end-to-end runtime/RSS measurements were performed.
Prevents unbounded memory buffering when polling /v1/models on inference pods by capping parseModels reads at 8 MiB. Promotes the existing 8 MiB maxResponseBytes constant from the metrics source to http.MaxResponseBytes so both parsers share one limit. Metrics scraping, DCGM scraping, and HTTP transport configuration remain unchanged.
pkg/epp/framework/plugins/datalayer/source/http/datasource.go:52): Exports MaxResponseBytes = 8 << 20 (8 MiB) in the shared HTTP source package.pkg/epp/framework/plugins/datalayer/source/metrics/datasource.go:174): Replaces its local maxResponseBytes constant with http.MaxResponseBytes inside newMetricsParser.pkg/epp/framework/plugins/datalayer/source/models/datasource.go:112): Wraps the response io.Reader with io.LimitReader(data, http.MaxResponseBytes) before io.ReadAll and json.Unmarshal, covering both explicit models-data-source configs and the default source created by models-responder (pkg/epp/framework/plugins/requesthandling/responder/models/plugin.go:110).json.Unmarshal and surface a poll error.HTTPDataSource.Poll receives an HTTP 200 /v1/models body larger than 8 MiB (for example, 8 MiB + 4 KiB) and passes resp.Body to parseModels (pkg/epp/framework/plugins/datalayer/source/models/datasource.go:111).io.ReadAll(io.LimitReader(data, http.MaxResponseBytes)) reads at most 8,388,608 bytes and hits io.EOF without reading the trailing bytes.json.Unmarshal returns an error and Poll fails instead of buffering the full oversized body.approximateprefix plugin: During Produce(), prompt hashes are derived using blockSize := p.GetBlockSize(pods), and this block size is stored in SchedulingContextState.BlockSize (Fixes #4721).What type of PR is this?
/kind bug
What this PR does / why we need it:
This PR resolves two related bugs in the approximateprefix plugin:
PreRequest block size recalculation for metrics:During Produce(), prompt hashes are derived using blockSize := p.GetBlockSize(pods), and this block size is stored in SchedulingContextState.BlockSize. Later, in PreRequest(), prefix cache match byte metrics (matchedLength and totalLength) recalculated block size via p.GetBlockSize(primaryProfileResult.TargetEndpoints) instead of using state.BlockSize. If the scheduled endpoint has no metrics yet (GetMetrics() == nil), GetBlockSize falls back to minBlockSizeTokens (64), causing the byte calculations to mismatch the block counts derived during Produce(). PreRequest() now reuses state.BlockSize.
SchedulingContextState.Clone() missing BlockSize:SchedulingContextState.Clone() omitted copying BlockSize, resetting it to 0 when state was cloned. Clone() now explicitly copies BlockSize: s.BlockSize.
Which issue(s) this PR fixes:
Fixes #4721
Release note _(write NONE if no user-facing change)_:
Fixed inaccurate prefix cache match byte metrics in the approximateprefix plugin by reusing the scheduling state's block size instead of recalculating from target endpoints.Fixes a block-size mismatch in approximateprefix metrics and completes SchedulingContextState cloning. PreRequest now reuses state.BlockSize computed during Produce when recording prefix cache hit and total byte metrics instead of calling GetBlockSize on the scheduled target endpoints, and SchedulingContextState.Clone now copies BlockSize. Block hashing in Produce, continuation tracking in PreRequest, and scorer attributes remain unchanged.
Produce (https://github.com/llm-d/llm-d-router/blob/51af89f498b7294296341e3dd4bd4e838bcad3c1/pkg/epp/framework/plugins/requesthandling/dataproducer/approximateprefix/plugin.go#L374-L417) computes blockSize once via GetBlockSize(pods), derives PerPromptHashes at that block size, and persists BlockSize in SchedulingContextState.PreRequest (https://github.com/llm-d/llm-d-router/blob/51af89f498b7294296341e3dd4bd4e838bcad3c1/pkg/epp/framework/plugins/requesthandling/dataproducer/approximateprefix/plugin.go#L690-L692) reuses state.BlockSize alongside matchLen and total block counts from state.PerPromptHashes when emitting byte metrics, matching trackContinuation at line 650.SchedulingContextState.Clone (https://github.com/llm-d/llm-d-router/blob/51af89f498b7294296341e3dd4bd4e838bcad3c1/pkg/epp/framework/plugins/requesthandling/dataproducer/approximateprefix/types.go#L107-L128) copies all five struct fields including BlockSize.AutoTune: true and BlockSizeTokens: 64, Produce observes an endpoint reporting CacheBlockSize: 128 and hashes a 256-token prompt into 2 blocks, storing BlockSize: 128.PreRequest runs with a target endpoint whose GetMetrics() is nil (which would fall back to 64 in GetBlockSize).state.BlockSize (128), recordPrefixCacheMatch records 2 * 128 * 4 = 1024 matched bytes instead of 512 bytes.cache_salt, like the prefill request already does (copyPrefillCacheFields).What type of PR is this?
/kind feature
What this PR does / why we need it:
The encode step's encoder requests now carry the client's cache_salt, like the prefill request already does (copyPrefillCacheFields). This covers both builders that let the encoder hash media itself:
NewEncoderPrimingBody (chat completions, responses, messages): cache_salt joins the passthrough fields, next to mm_processor_kwargs and media_io_kwargs, which are forwarded for the same reason.buildEncodeContentPartsBody (generate format under mm_payload: none).The generate-format body that carries features is unchanged: it sends the render hash, so the encoder does not hash anything.
Why: vllm-project/vllm#70850 mixes cache_salt into the cache identity of multimodal items, so tenants with different salts share no processor or encoder cache entries. With that change, an encoder primed without the salt stores its output under a hash the salted prefill request never looks up, and every encoder hand-off misses. Against a vLLM without that change, the forwarded salt only salts the encoder request's own KV blocks, which nothing reads, so this PR is safe to merge on its own.
Tests (go test -race -count=1 ./pkg/common/request/ ./pkg/coordinator/steps/, both ok):
TestNewEncoderPrimingBody now expects cache_salt in the responses and messages bodies.TestEncodeAndPrefill_MMPayloadNoneForwardsCacheSalt: encode and prefill requests carry the same cache_salt.content.go and encode.go reverted.make presubmit targets: format, lint (0 issues), lint-security (0 issues), govulncheck (no vulnerabilities), go-mod-check and verify-telemetry pass. verify-boilerplate and verify-review-playbook fail on files this PR does not touch (.github/scripts/merge-pr-onto-base*.sh; pkg/epp/framework/common/duration/seconds.go and pkg/epp/framework/plugins/requesthandling/forwardtokens/plugin.go unrouted), as on main.
docs/communication.md states which encoder requests carry cache_salt.
Which issue(s) this PR fixes:
None filed; companion to vllm-project/vllm#70850.
Release note _(write NONE if no user-facing change)_:
Encoder requests in encode-disaggregated serving now carry the client's `cache_salt`, so encoder outputs stay reachable by prefill on vLLM versions that scope multimodal cache keys to `cache_salt`.Encoder sub-requests previously omitted cache_salt, so on vLLM versions that scope multimodal item cache keys to cache_salt (vllm-project/vllm#70850), a salted prefill request would miss encoder entries stored without the salt. This change adds FieldCacheSalt to encoderPassthroughFields and messagesEncoderPassthroughFields for NewEncoderPrimingBody and copies cache_salt into buildEncodeContentPartsBody for generate-shaped content_parts encode requests. The generate features encoder path, RenderStep, PrefillStep, and gRPC vllmwire framing remain unchanged because they already forward cache_salt or use precomputed render hashes.
pkg/common/request/content.go): Adds FieldCacheSalt to encoderPassthroughFields (Chat Completions and Responses) and messagesEncoderPassthroughFields (Messages, which still omits mm_processor_kwargs and media_io_kwargs), updating both coordinator EncodeStep and sidecar fanoutEncoder (NIXL, shared storage, and Mooncake) together.content_parts encoder leg (pkg/coordinator/steps/encode.go): Copies reqCtx.Body[reqcommon.FieldCacheSalt] into the sub-request body when mm_payload omits tensors (reqCtx.MMPayload != ""), matching copyPrefillCacheFields in pkg/coordinator/steps/prefill.go.DecodeRequestBody leaves cache_salt as json.RawMessage so its JSON representation passes through unchanged; the features branch of buildEncodeBody continues sending render-computed mm_hashes without re-hashing."cache_salt": "salt" to a coordinator configured with mm_payload: none.RenderStep forwards reqCtx.Body (including cache_salt) to /render, receiving token_ids and salted mm_hashes without tensors.EncodeStep.buildEncodeContentPartsBody builds the /inference/v1/generate encode sub-request with content_parts and sets body["cache_salt"] = "salt" so the encoder stores its output under the same salted hash.PrefillStep copies cache_salt: "salt" via copyPrefillCacheFields (or maps.Clone under use_openai_format: true), matching the encoder's cache entry.BenchmarkGetBlockHashesMultiModal showed that 99.85% of allocations came from mmBlockExtra allocating and growing an intermediate []byte slice on every block that overlaps multimodal features, only to pass those...What type of PR is this?
/kind performance
What this PR does / why we need it:
Profiling BenchmarkGetBlockHashesMultiModal showed that 99.85% of allocations came from mmBlockExtra allocating and growing an intermediate []byte slice on every block that overlaps multimodal features, only to pass those bytes immediately into xxhash.Digest.Write and discard the slice.
This PR replaces mmBlockExtra with writeMMBlockExtra, streaming the 16-byte block prefix and each overlapping feature's length-prefixed hash and clamped block-relative offset directly into a reused stack xxhash.Digest via the existing writeLengthPrefixedString helper. The resulting hash bytes are bit-for-bit identical.
pkg/epp/framework/plugins/requesthandling/dataproducer/prefixhash/hashing.go: Replace mmBlockExtra with streaming writeMMBlockExtra, reuse the stack xxhash.Digest and lenBuf, compute blockStart/blockEnd once per block, and skip calling writeMMBlockExtra when len(features) == 0.pkg/epp/framework/plugins/requesthandling/dataproducer/prefixhash/hashing_reference_test.go: Add TestGetBlockHashesMultiModalAllocs to cap multimodal hashing allocations (4 actual, ceiling 10).pkg/epp/framework/plugins/requesthandling/parsers/vllmgrpc/vllmgrpc.go: Update comment referencing prefixhash.mmBlockExtra to prefixhash.writeMMBlockExtra.go test -run='^$' -bench='BenchmarkGetBlockHashes' -benchmem -count=10 ./pkg/epp/framework/plugins/requesthandling/dataproducer/prefixhash/ (medians, Linux amd64 Xeon):
| Benchmark | Before (ns/op) | After (ns/op) | Speedup | Before (B/op) | After (B/op) | ฮ Bytes | Before (allocs/op) | After (allocs/op) | ฮ Allocs |
|---|---|---|---|---|---|---|---|---|---|
MultiModal/single | 66,351.5 | 66,649.5 | 1.00x | 16,592 | 16,416 | -1.1% | 7 | 3 | -57.1% |
MultiModal/small | 966.2 | 681.9 | 1.42x | 992 | 288 | -71.0% | 20 | 4 | -80.0% |
MultiModal/sparse | 100,436.0 | 85,075.5 | 1.18x | 75,040 | 29,984 | -60.0% | 1,028 | 4 | -99.6% |
MultiModal/nested | 223,784.5 | 139,654.5 | 1.60x | 291,808 | 29,984 | -89.7% | 4,610 | 4 | -99.9% |
GetBlockHashes (text-only) | 15,871.5 | 15,909.0 | 1.00x | 4,128 | 4,128 | 0.0% | 3 | 3 | 0.0% |
go test -race -v ./pkg/epp/framework/plugins/requesthandling/dataproducer/prefixhash/... (including 2,000-iteration TestGetBlockHashesMatchesReference fuzz comparison and TestGetBlockHashesMultiModalAllocs) โ PASSgo test -race ./pkg/epp/framework/plugins/requesthandling/parsers/vllmgrpc/... โ PASSgolangci-lint run ./pkg/epp/framework/plugins/requesthandling/dataproducer/prefixhash/... ./pkg/epp/framework/plugins/requesthandling/parsers/vllmgrpc/... โ 0 issuesWhich issue(s) this PR fixes:
N/A (discovered via hot-path profiling).
Release note _(write NONE if no user-facing change)_:
NONEEliminates per-block intermediate slice allocations when hashing multimodal prompts in prefixhash. Replaces mmBlockExtra with writeMMBlockExtra to stream the 16-byte block prefix, length-prefixed feature hashes, and clamped entry offsets directly into a single stack-allocated xxhash.Digest reused across the seed and block loop. Exported signatures, hash outputs, and featureless block handling stay unchanged.
xxhash.Digest (d) and [8]byte length buffer (lenBuf) from seed computation across all block iterations in computeBlockHashes.blockStart and blockEnd once per block and skips writeMMBlockExtra when len(features) == 0.writeMMBlockExtra, resets d and writes blockPrefix lazily only when the first overlapping, non-empty-hash feature is seen; otherwise returns false so the caller falls back to xxhash.Sum64(buf[:]) without touching d.TestGetBlockHashesMultiModalAllocs capping allocations at 10 per run (expected 4 for output slices and sorted feature copy).computeBlockHashes; d and lenBuf are initialized once for (TargetModel, CacheSalt).i overlapping a hashed feature, len(features) > 0 calls writeMMBlockExtra, which resets d, writes the 16-byte buf[:], streams each overlapping feature via writeLengthPrefixedString plus clamped offset, and returns true so d.Sum64() becomes prevBlockHash.features is empty or holds only hashless/non-overlapping entries, writeMMBlockExtra leaves d untouched and returns false (or is skipped), so xxhash.Sum64(buf[:]) produces the featureless block hash.fwkdl.ID, and reuse immutable scheduling metrics snapshots during streamed requests (Fixes #4776).What type of PR is this?
/kind performance
What this PR does / why we need it:
Guard per-endpoint DEBUG and TRACE logging, key in-flight snapshots by fwkdl.ID, and reuse immutable scheduling metrics snapshots during streamed requests. This removes avoidable logging, string, and metrics clone allocations from the predicted latency and latency scorer hot paths.
Which issue(s) this PR fixes:
Fixes #4776
Release note _(write NONE if no user-facing change)_:
NONEEliminates per-endpoint and per-token heap, string, and logger allocations across the predictedlatency data producer, request-control hooks, and latency scorer hot paths. It guards DEBUG/TRACE logs behind hoisted .Enabled() checks, keys inFlightLoadForEndpoints directly by fwkdl.ID (types.NamespacedName), and reuses the immutable scheduling *fwkdl.Metrics snapshot captured once in PreRequest instead of cloning on every streamed token. Prediction math, SLO headroom validation, and training feature values remain unchanged.
Produce, generatePredictions, scoreBucket, and compositeScores resolve V(DEBUG)/V(TRACE) loggers and .Enabled() booleans once before looping over endpoints; validatePredictionWithLogger avoids log.FromContext(context.Background()) per endpoint while keeping validatePrediction intact for unit tests.predictedLatencyCtx.inFlightLoadForEndpoints changes from map[string]inFlightLoadSnapshot (keyed by ID.String()) to map[fwkdl.ID]inFlightLoadSnapshot across Produce, generatePredictions, and PreRequest.refreshLastSeenMetrics now runs only once in PreRequest and stores profileResult.TargetEndpoints[0].GetMetrics() directly without .Clone(), relying on the read-only snapshot contract of fwksched.Endpoint (pkg/epp/framework/interface/scheduling/types.go:85-89). Per-token hooks processFirstTokenForLatencyPrediction and processTokenForLatencyPrediction no longer refresh metrics, and processTokenForLatencyPrediction computes now.Sub(lastTokenTimestamp) only on token 2 when DEBUG logging is enabled.Produce for a request with 16 candidate endpoints at DEFAULT log level (DEBUG/TRACE off), PredictedLatency skips all DEBUG/TRACE Info calls and meta.String()/metrics.String() formatting, and stores inFlightLoadForEndpoints[meta.ID] without allocating ID.String().LatencyScorer.Score calls scoreBucket (or compositeScores on fallback) with traceEnabled == false, bypassing all per-endpoint TRACE log allocations.PreRequest, refreshLastSeenMetrics records TargetEndpoints[0].GetMetrics() pointer once into lastSeenMetrics[profileName] without cloning ActiveModels/WaitingModels maps.ResponseBody chunks, processFirstTokenForLatencyPrediction and processTokenForLatencyPrediction update timestamps and token counts with zero refreshLastSeenMetrics clones and zero DEBUG duration allocations.kv_cache_report_mode=full inside vllm_xargs or sampling_params.{extra_args,vllm_xargs} on HTTP routes, vLLM re-announces already-cached KV blocks on subsequent requests (Fixes #4770).What type of PR is this?
/kind bug
What this PR does / why we need it:
When an untrusted client sends kv_cache_report_mode=full inside vllm_xargs or sampling_params.{extra_args,vllm_xargs} on HTTP routes, vLLM re-announces already-cached KV blocks on subsequent requests. Because eventDedupFilter reference-counts every BlockStored announcement to handle overlapping chunks from vLLM's OffloadingConnector, those extra announcements leave positive reference counts after a block is evicted. Subsequent BlockRemoved events are suppressed and prefix-cache-scorer keeps crediting the evicted worker.
This change adds FieldKVCacheReportMode (kv_cache_report_mode) to the shared nested request-body sanitization list (pkg/common/request/sanitize.go) so both EPP and Coordinator sanitize client-supplied copies in vllm_xargs, sampling_params.extra_args, and sampling_params.vllm_xargs:
strip (default): removes kv_cache_report_mode from vllm_xargs and sampling_params.{extra_args,vllm_xargs} on text, token, and other non-render JSON routes, including JSON-escaped and duplicate keys, while preserving sibling keys.reject: returns HTTP 400 on external text routes and strips on other non-render routes.trustCaller: preserves caller-supplied fields (still sanitized when the Coordinator marks passthrough traffic with x-llm-d-unsanitized-body: true), and EPP plugins running after sanitization can still set kv_cache_report_mode.docs/architecture.md and docs/coordinator_architecture.md.Test plan:
kv_cache_report_mode in decoded and raw vllm_xargs, sampling_params.extra_args, and sampling_params.vllm_xargs, including escaped and duplicate keys, with zero allocations on clean raw objects.strip, reject, and trustCaller policies across chat completions, string completions, token-array completions, /inference/v1/generate, and other non-render JSON routes.strip and reject policies across text and token routes.Which issue(s) this PR fixes:
Fixes #4770
Release note:
EPP and Coordinator now sanitize client-supplied `kv_cache_report_mode` in `vllm_xargs`, `sampling_params.extra_args`, and `sampling_params.vllm_xargs` according to `bodyFieldsSanitizationPolicy`, preventing clients from triggering full KV-cache re-announcements that retain evicted blocks in the prefix-cache index.Client-supplied kv_cache_report_mode=full inside vLLM extra-arg maps causes vLLM to re-announce already-cached KV blocks on subsequent requests, inflating eventDedupFilter reference counts (pkg/kvevents/event_dedup_filter.go:118-139) so later BlockRemoved events are suppressed and evicted blocks stay in the prefix-cache index. This change adds FieldKVCacheReportMode ("kv_cache_report_mode") to the shared nestedTransferParams table (pkg/common/request/sanitize.go:103-117) so both Coordinator and EPP strip or reject it alongside kv_transfer_params and ec_transfer_params. Top-level sanitization fields, /render request exemptions, and trustCaller passthrough behavior remain unchanged.
FieldKVCacheReportMode (pkg/common/request/constants.go#L96) is added to nestedTransferParams (pkg/common/request/sanitize.go#L103-L117) under vllm_xargs, sampling_params.extra_args, and sampling_params.vllm_xargs.FindExternalTextFields/StripExternalTextFields and FindTransferParams/StripTransferParams all iterate nestedTransferParamsIn, so Coordinator ingress (pkg/coordinator/server/handlers.go:140-173) and EPP Director.sanitizeClientFields (pkg/epp/requestcontrol/director.go:517-545) automatically enforce strip, reject (400 on external text routes), and trustCaller (overridden by x-llm-d-unsanitized-body: true from Coordinator passthrough).nestedKey (pkg/common/request/sanitize.go:123-171) skips unmarshaling clean json.RawMessage objects with zero heap allocations, decodes and deletes keys when literal or \-escaped keys appear, and leaves RenderRequest routes and post-sanitization EPP plugin mutations untouched.POST /v1/chat/completions with {"vllm_xargs":{"kv_cache_report_mode":"full","k":"v"}}.strip policy, StripExternalTextFields calls nestedKey, removes kv_cache_report_mode (including escaped or duplicate keys), and forwards {"vllm_xargs":{"k":"v"}}.reject policy on external text routes, FindExternalTextFields returns "vllm_xargs.kv_cache_report_mode" and Coordinator/EPP returns HTTP 400 before producers or workers see the request; on token routes (/inference/v1/generate, token-array /v1/completions), StripTransferParams strips the key instead of rejecting.requesthandling.PriorityKey, and another may publish a resolved band through agentlineage.ResolvedBandKey (Fixes #4728).What type of PR is this?
/kind bug
What this PR does / why we need it:
A RequestHeader processor may declare a request's priority through requesthandling.PriorityKey, and another may publish a resolved band through agentlineage.ResolvedBandKey. The Director applied the resolved band after the RequestHeader phase unconditionally, so with qos-contract in enforce-limits mode and agent-lineage enabled, a request carrying x-parent-session-id had its downgrade replaced by the parent's band:
The request was then served at the committed class while holding no concurrency slot and paying no daily charge, so a team could run past its commits.
This PR makes a declared priority a ceiling on a resolved band: when a RequestHeader processor declared a priority through PriorityKey, the Director applies min(resolved band, declared priority). A resolved band can lower a declared priority but never raise it.
The rule covers every declared priority, not only downgrades. In enforce-limits mode qos-contract declares the served class on every request, in contract or downgraded, so the team's class becomes the highest band any of its requests can get:
When no priority was declared, for example with qos-contract in report-only mode or not enabled, the resolved band still replaces the seeded objective priority, so agent-lineage inheritance can still raise a child above its own objective as designed.
The qos-contract README limitation "do not combine enforce-limits with agent-lineage" is removed, and both plugin READMEs document the precedence.
Which issue(s) this PR fixes:
Fixes #4728
Release note:
A priority declared by a RequestHeader plugin through `request-priority` is now a ceiling on the band `agent-lineage` resolves: the Director applies the lower of the two, so band inheritance can lower a declared priority but no longer raise it. `qos-contract` in `enforce-limits` mode declares a class on every request, so no request is served above its team's class: a downgraded request keeps its lower class instead of inheriting its parent's committed class, and an in-contract request is not raised above its class. `qos-contract` in `enforce-limits` mode can now be combined with `agent-lineage`.Caps any band resolved via agentlineage.ResolvedBandKey by a RequestHeader-declared fwkrh.PriorityKey in Director.HandleRequest (min(resolvedBand, declared)). This stops agent-lineage band inheritance from undoing a qos-contract downgrade when qos-contract runs in enforce-limits mode alongside agent-lineage. When no PriorityKey is declared (such as in report-only mode or when qos-contract is disabled), ResolvedBandKey still replaces the seeded objective priority unchanged.
pkg/epp/requestcontrol/director.go:386-398): Before Admit, if both agentlineage.ResolvedBandKey and fwkrh.PriorityKey are present on reqCtx.SchedulingRequest, Director.HandleRequest computes resolvedBand = min(resolvedBand, declared) and writes it to priority, reqCtx.Priority, reqCtx.SchedulingRequest.Objectives.Priority, and the request_prio OTel span attribute.agent-lineage still records the uncapped inherited band on the child node in agent_lineage.go, so a later in-contract grandchild does not inherit a sibling/parent's temporary downgrade; each child is capped independently by its own PriorityKey declaration.qos-contract produces TenantKey alongside PriorityKey, and agent-lineage consumes TenantKey optionally, so OrderPlugins orders qos-contract before agent-lineage.pkg/epp/framework/interface/requesthandling/keys.go:28-32 documents PriorityKey as a ceiling on resolved-band, and both agentlineage/README.md and qoscontract/README.md document the precedence and lift the incompatibility limitation.R under tenant-1 is within_contract for critical (priority 100): qos-contract sets PriorityKey=100, and agent-lineage records R at band 100.C arrives with x-parent-session-id: R and exceeds team-1 concurrency, so qos-contract downgrades it to standard (PriorityKey=10, no slot or charge).agent-lineage resolves C from R's live node and publishes ResolvedBandKey=100.Director.HandleRequest reads resolvedBand=100 and declared=10, applies min(100, 10) = 10, and admits/schedules C at priority 10 instead of 100.RequestHeaderProcessor changes a request's priority or tenant by declaring requesthandling.PriorityKey or requesthandling.TenantKey in Produces() (Fixes #4729).A RequestHeaderProcessor changes a request's priority or tenant by declaring requesthandling.PriorityKey or requesthandling.TenantKey in Produces(). The Director copies the declared value onto the request after each processor runs (applyDeclaredOverrides). With two producers, the last one in plugin order wins, and nothing reports the overwrite, so reordering plugins silently changes the result.
This adds Config.Validate() and calls it from the runner's config-load path. It rejects a configuration in which more than one RequestHeaderProcessor declares the same override key, naming the plugins in execution order:
failed to load the configuration - requesthandling.PriorityKey is declared in Produces() by more than one RequestHeaderProcessor (qos-a/qos-contract, qos-b/qos-contract); at most one may produce it
TenantKey gets the same check, since it has the same last-wins behavior.
agentlineage.ResolvedBandKey sets the priority through a separate path; its precedence over PriorityKey stays tracked in #4728.
The check reads the Produces() declaration, not what a plugin writes at runtime. qos-contract declares both keys in every mode, but in report-only mode it writes neither. So the EPP also rejects two report-only instances, or a report-only instance next to an enforcing one (for example, to trial a new contract beside the live one), even though they would not overwrite each other. This PR keeps the strict rule. Allowing those setups would mean making qos-contract's Produces() depend on its mode, which can follow if the setup turns out to be needed.
The EPP now rejects at startup a configuration in which more than one RequestHeaderProcessor declares requesthandling.PriorityKey or requesthandling.TenantKey in Produces(). Previously the last producer in plugin order silently won.
pkg/epp/requestcontrol/request_control_config.go: add Config.Validate, checking Produces() of each RequestHeaderProcessor.cmd/epp/runner/runner.go: call Validate after OrderPlugins so the reported order matches execution order. All startup paths (Kubernetes, file discovery, --validate-config) go through this function.pkg/epp/framework/interface/requesthandling/keys.go: document the one-producer rule.TestConfig_Validate_RequestOverrideProducers: unit matrix for duplicate PriorityKey, duplicate TenantKey, both duplicated, one producer per key, one plugin producing both, unrelated key, no producers.TestTwoPriorityProducersRejectedAtStartup: two qos-contract instances fail through the production config path. The instances are report-only because that is the smallest valid configuration; the test exercises the declaration check described under Limitation, not a runtime overwrite.TestSinglePriorityProducerAcceptedAtStartup: one qos-contract instance still loads.go test ./pkg/epp/requestcontrol/... ./cmd/epp/runner/... ./pkg/epp/datalayer/...
go vet ./pkg/epp/requestcontrol/... ./cmd/epp/runner/...
Fixes #4729
Prevents silent last-writer-wins overwrites when multiple RequestHeaderProcessor plugins declare requesthandling.PriorityKey or requesthandling.TenantKey in Produces(). Adds (*requestcontrol.Config).Validate() and invokes it at startup in (*Runner).parseConfigurationPhaseTwo right after topological ordering (OrderPlugins), failing config load with the conflicting plugins listed in execution order. agentlineage.ResolvedBandKey precedence (#4728), datalayer.BuildRegistry multi-producer rules for namespaced keys, and qos-contract's unconditional Produces() in report-only mode remain unchanged.
request_control_config.go:133-165):** Config.Validate() checks c.requestHeaderPlugins for fwkrh.PriorityKey and fwkrh.TenantKey via requestHeaderProducers, joining errors with errors.Join when more than one processor declares either key.runner.go:1017-1024):** parseConfigurationPhaseTwo calls r.requestControlConfig.Validate() immediately after r.requestControlConfig.OrderPlugins(dag), covering K8s setup, --validate-config, and runWithFileDiscovery while ensuring error output reflects execution order rather than map-iteration order.keys.go:24-29):** Documents the single-producer invariant on PriorityKey and TenantKey.EndpointPickerConfig configures two qos-contract plugins (qos-a and qos-b), both implementing RequestHeaderProcessor and declaring PriorityKey and TenantKey in Produces().parseConfigurationPhaseTwo builds the registry and DAG (BuildRegistry passes because both declare the same Go types), then OrderPlugins(dag) orders the unranked plugins alphabetically as qos-a/qos-contract, qos-b/qos-contract.r.requestControlConfig.Validate() detects two producers for both keys and returns joined errors, failing startup with failed to load the configuration - requesthandling.PriorityKey is declared in Produces() by more than one RequestHeaderProcessor (qos-a/qos-contract, qos-b/qos-contract); at most one may produce it (and likewise for requesthandling.TenantKey).--kv-connector nixlv2 --moriio-write-mode and the default --moriio-dp-size 1, the sidecar keeps the x-data-parallel-rank headers the EPP (or a gateway) set on each request, but writes remote_dp_rank: 0 with... (Fixes #4792)What type of PR is this?
/kind bug
What this PR does / why we need it:
With --kv-connector nixlv2 --moriio-write-mode and the default --moriio-dp-size 1, the sidecar keeps the x-data-parallel-rank headers the EPP (or a gateway) set on each request, but writes remote_dp_rank: 0 with remote_dp_rank_override: true into both kv_transfer_params bodies. vLLM's MoRI-IO connector reads the decode body's remote_dp_rank as the prefill rank to send the "blocks ready" notify to, and with remote_dp_rank_override only the decode rank equal to it sends that notify. When the prefill request runs on rank 1, the decode side notifies prefill rank 0, or does not notify at all.
At --moriio-dp-size 1 the sidecar picks no rank, so this PR leaves the headers as they are (the contract from #3821 and docs/disaggregation.md) and makes the bodies follow them:
remote_dp_rank, or 0 when the prefill request has no rank header. This is the EPP's x-llm-d-prefiller-data-parallel-rank, or the client's x-data-parallel-rank when the EPP sends none.remote_dp_rank returned by the prefill response in place of that rank on the decode body. vLLM's MoRI-IO prefill returns the rank it ran on. At size 1 the sidecar used to replace it with 0.is_request_leader: true, as it already did above size 1 and as the parallel decode body already does. The EPP picks the decode and prefill ranks separately, so they can differ.Behavior with --moriio-dp-size above 1 is unchanged. MORIIO_README.md documents the size-1 behavior, and says that the prefill request's remote_dp_size of 1 makes the connector connect only to decode rank 0, so decode workers with more ranks still need --moriio-dp-size.
Which issue(s) this PR fixes:
Fixes #4792
Release note _(write NONE if no user-facing change)_:
pd-sidecar: with `--moriio-write-mode` and `--moriio-dp-size` 1, `kv_transfer_params.remote_dp_rank` on both MoRI-IO requests names the rank the prefill request is sent to, instead of 0, and serial decode requests carry `is_request_leader: true`.
Test plan
none sentinel, and a gateway rank on both legs each produce bodies naming the prefill request's rank, with the headers unchanged and the decode leader flag set.resolveDecodeDPRank accepts a returned rank at size 1 and falls back to the caller's rank otherwise.go test -race ./pkg/sidecar/...make presubmit: format, lint, security lint, govulncheck and telemetry pass. verify-boilerplate (.github/scripts/merge-pr-onto-base*.sh from #4598) and verify-review-playbook (unrouted forwardtokens/duration files) fail on main as well.Real-stack check
Stack: two Tesla T4s, vLLM 0.34.1rc1.dev450, NIXL 1.5.2, Qwen/Qwen3-0.6B. The prefill and decode engines each run vllm serve --data-parallel-size 2 across both GPUs. EPP file discovery lists their ranks as rank endpoints (rankByHeader: true), and Envoy, the EPP and the sidecar route each request. The sidecar runs with --moriio-write-mode --moriio-dp-size 1, serial and parallel, built from 3d81f830c and from this branch. Logging proxies in front of both engines capture each request, and engine metrics show which rank ran each leg. Each run sent 8 requests through Envoy.
3d81f830c, both bodies carry remote_dp_rank: 0 on every request. On this branch they carry the rank the prefill request was sent to, and the serial decode body carries is_request_leader: true. Every leg ran on the rank its header named.MoRIIOConnectorScheduler.update_state_after_alloc at the decode rank that ran it. Results for "notify goes to the prefill rank that ran the request":| Dispatch | 3d81f830c | This branch |
|---|---|---|
| Serial | 2 of 8 (5 send no notify) | 8 of 8 |
| Parallel | 3 of 8 (the requests whose prefill ran on rank 0) | 8 of 8 |
The engines run NixlConnector, which ignores these fields. Serial requests returned 200 and moved the prompt KV over NIXL on both builds. In parallel runs the decode proxy answered the decode request itself, because stock NixlConnector asserts on a write-parallel decode body (do_remote_prefill with empty remote_block_ids) and the engine exits. Without any rank header, the parallel bodies and the NIXL serial decode body name rank 0 even when the prefill engine's frontend picked another rank. A MoRI-IO prefill response returns its rank, which serial dispatch uses.
Fixes MoRI-IO WRITE-mode (--kv-connector nixlv2 --moriio-write-mode) at the default --moriio-dp-size 1 so kv_transfer_params.remote_dp_rank names the prefill request's data-parallel rank instead of 0 and serial decode always sets is_request_leader: true. Serial dispatch also preserves any valid non-negative remote_dp_rank returned by the prefill engine at size 1. Request x-data-parallel-rank headers, READ-mode behavior, and --moriio-dp-size > 1 routing remain unchanged.
prefillDPRank resolves the effective prefill rank matching setPrefillDPRank: reads prefillDPRankKey from context (populated from x-llm-d-prefiller-data-parallel-rank in pkg/sidecar/proxy/dispatch.go:151-159, with none stored as ""), falls back to x-data-parallel-rank when absent, and defaults to 0 on empty or invalid values.runNIXLV2Serial and buildNIXLV2ParallelKVParams (shared by HTTP and handleNIXLV2VLLMGRPC) use prefillDPRank when MoRIIODPSize <= 1 without overwriting x-data-parallel-rank headers.resolveDecodeDPRank accepts any non-negative whole remote_dp_rank returned by prefill when dpSize <= 1 and falls back to the caller-supplied prefill rank otherwise; prepareNIXLV2SerialDecodeKVParams unconditionally sets is_request_leader: true in WRITE mode so decode rank mismatches still trigger the MoRI-IO notify.x-data-parallel-rank: 2 and x-llm-d-prefiller-data-parallel-rank: 1 on a sidecar running --kv-connector nixlv2 --moriio-write-mode --moriio-dp-size 1.dispatch.go strips x-llm-d-prefiller-data-parallel-rank and stores "1" in context; setPrefillDPRank sets x-data-parallel-rank: 1 on the prefill leg while decode keeps x-data-parallel-rank: 2.prefillDPRank returns 1, so both prefill and parallel decode bodies (and serial prefill plus serial decode fallback) carry remote_dp_rank: 1 and remote_dp_rank_override: true, and decode carries is_request_leader: true.kv_transfer_params.remote_dp_rank: 3, resolveDecodeDPRank keeps 3 on the decode request instead of resetting it to 0.target: test/perf/config/targets/endpoint-attribute-parity-job1.yaml and give a run comparable with...What type of PR is this?
/kind test
What this PR does / why we need it:
Adds a nightly perf target for the endpoint-attribute parity config of #2059, so the nightly workflow can be dispatched with target: test/perf/config/targets/endpoint-attribute-parity-job1.yaml and give a run comparable with optimized-baseline-job1.
It fixes two problems of the parity config added in #2393:
endpoint-attribute-scorer is an Alpha plugin, and the config did not set allow-experimental-plugins. epp --validate-config on its plugin config returns plugin 'ea-kv-cache-scorer' (type: 'endpoint-attribute-scorer') has Alpha stability level, but command line flag --allow-experimental-plugins is not set.inferencePool, modelServers, proxy and tracing sections of optimized-baseline.yaml, so a run would have used the chart's default Envoy settings instead of the baseline's.The parity config now matches optimized-baseline.yaml except for the two scorers and the flag. The new target matches optimized-baseline-job1.yaml except for the router config. A test in test_run_nightly_perf.py fails when either pair drifts apart.
No change under .github/: the nightly workflow already takes the target as a workflow_dispatch input.
Which issue(s) this PR fixes:
Part of #2059
Release note _(write NONE if no user-facing change)_:
NONE
Testing
epp --validate-config --allow-experimental-plugins accepts the parity plugin config, built from main at 32a075e2.python3 -m unittest in test/perf: 47 tests pass.make signed-commits-check, check-latest-tags-strict, verify-boilerplate.I have not dispatched the nightly workflow (it needs the project's GKE credentials).
I used an AI coding agent for the analysis and the change; I reviewed it and can answer for every line.
Repairs the endpoint-attribute parity benchmark Helm values in test/perf/config/router-configs/endpoint-attribute-parity.yaml and adds a matching nightly target manifest so the nightly workflow can run an apples-to-apples comparison against optimized-baseline-job1. The existing baseline target, baseline router config, and scheduled workflow triggers remain unchanged.
test/perf/config/router-configs/endpoint-attribute-parity.yaml): Sets router.epp.flags.allow-experimental-plugins: "true" for the Alpha endpoint-attribute-scorer plugin and mirrors inferencePool, modelServers, proxy, and tracing from test/perf/config/router-configs/optimized-baseline.yaml.test/perf/config/targets/endpoint-attribute-parity-job1.yaml): Mirrors test/perf/config/targets/optimized-baseline-job1.yaml with setup.router_config pointed at endpoint-attribute-parity.yaml; run_nightly_perf.py derives test_name = "endpoint-attribute-parity-job1" so results and trend state stay separate from optimized-baseline-job1.test/perf/test_run_nightly_perf.py:590-617): Compares both targets and both router configs after popping allow-experimental-plugins, pluginsConfigFile, and pluginsCustomConfig, then verifies all non-swapped plugins and remapped schedulingProfiles match identically..github/workflows/nightly-router-perf-test-optimized-baseline-10k-1k.yaml with target: test/perf/config/targets/endpoint-attribute-parity-job1.yaml.test/perf/run_nightly_perf.py loads endpoint-attribute-parity-job1.yaml, sets test_name to endpoint-attribute-parity-job1 and Helm release name to endpoint-attribute-parity, and config/charts/routerlib/templates/_epp-ha.tpl converts allow-experimental-plugins: "true" into --allow-experimental-plugins=true alongside Envoy proxy and pool settings matching optimized-baseline.yaml.run_nightly_perf.py and test/perf/trend.py store the run record under runs/endpoint-attribute-parity-job1/ and compare against prior endpoint-attribute-parity-job1 runs without affecting optimized-baseline-job1."model":" " inside the chunk (Fixes #3849).What type of PR is this?
/kind bug
What this PR does / why we need it:
The streamed-response path rewrites the internal target model name back to the name the client asked for one ext_proc body chunk at a time, matching a whole "model":"<target>" inside the chunk. Envoy splits a streamed body at arbitrary byte offsets, so a boundary inside that pattern leaves both halves unmatched and the event reaches the client with the name picked by the InferenceModelRewrite rule.
The parse side already carries partial SSE lines, but the forward path rewrites and sends raw per-chunk bytes, so that carry does not cover it.
This PR adds a bounded per-request carry on the forward path. The tail of a forwarded chunk that could still become an occurrence once the next chunk arrives is held back and prepended to that chunk, and flushed on the end-of-stream chunk or before the trailers when the body ends there. The rewrite runs before the hold-back so a complete occurrence that ends exactly at the boundary stays intact, and the carry is skipped entirely when the names are equal or either is empty, so a deployment without a model rewrite forwards the bytes it forwards today.
Bytes are held back only when a chunk ends inside the model-name pattern, and the hold-back is at most one byte shorter than the pattern, so the delay is one chunk for a tail of that size and zero otherwise.
The test cuts a two-event stream at each of the 270 byte offsets and requires the client-facing name at every one. On main, 42 of those cuts leak the target name; with this change none do. A second test covers the trailer-terminated stream, and a third checks that a request with no rewrite active forwards every byte unchanged. A hermetic full-duplex case now drives the same trailer-terminated stream through the real server in all three execution modes, so the body-before-trailers ordering is not only proven against a mock stream; that harness scripts the Envoy side, so it still does not settle whether a real Envoy accepts a body mutation after it has sent the trailers, which needs a cluster e2e run.
Which issue(s) this PR fixes:
Fixes #3849
Release note _(write NONE if no user-facing change)_:
Fixed the streamed response model-name rewrite so a chunk boundary inside the model name no longer exposes the backend model name to the client.Fixes streamed model-name rewriting in the EPP response path (pkg/epp/handlers/server.go) so target model names split across Envoy ext_proc body chunks are rewritten to the client-facing model name. Holds back any chunk-ending suffix that matches a proper prefix of "model":"<target>" or "model": "<target>" in per-request modelNameRewriteCarry, composes behind dropRequestedUsageFrame, and flushes on endOfStream or before ResponseTrailers. Non-streaming finishResponse rewriting and requests without active model rewriting remain unchanged.
RequestContext.modelNameRewriteCarry (https://github.com/llm-d/llm-d-router/blob/7977f219a803b4bd1174db32d850a694740d4305/pkg/epp/handlers/server.go#L264): bounded per-request byte slice holding a trailing suffix shorter than the compact or spaced model pattern.modelNameRewriter.carryLen and RequestContext.rewriteStreamedModelName (https://github.com/llm-d/llm-d-router/blob/7977f219a803b4bd1174db32d850a694740d4305/pkg/epp/handlers/server.go#L1290-L1330): returns chunk untouched when TargetModelName == IncomingModelName or either is empty; otherwise prepends carry, runs rewriteModelName first so complete occurrences ending at the chunk boundary are rewritten immediately, and when !endOfStream, initializes needles if needed and stores any trailing proper-prefix suffix.https://github.com/llm-d/llm-d-router/blob/7977f219a803b4bd1174db32d850a694740d4305/pkg/epp/handlers/server.go#L1036-L1038, https://github.com/llm-d/llm-d-router/blob/7977f219a803b4bd1174db32d850a694740d4305/pkg/epp/handlers/server.go#L1064-L1070): runs after dropRequestedUsageFrame in ResponseBody, and on ResponseTrailers runs rewriteStreamedModelName(held, true) whenever held or modelNameRewriteCarry is non-empty so updateStateAndSendIfNeeded (pkg/epp/handlers/server.go:1411-1438) emits the body response before ResponseTrailers."llama" (IncomingModelName) to "llama-canary" (TargetModelName).data: {"model":"llama- (endOfStream=false): rewriteStreamedModelName holds "model":"llama- in modelNameRewriteCarry and forwards data: {.canary","choices":[]}: rewriteStreamedModelName prepends the carry to form "model":"llama-canary"..., rewrites it to "model":"llama"..., and forwards the event.ResponseTrailers after chunk 1, Process passes dropRequestedUsageFrame(nil, true) through rewriteStreamedModelName(held, true) with endOfStream=true and sends the held bytes (EndOfStream: false) ahead of TrailersResponse.server.go, server_model_rewrite_test.go:163; not yet resolved.We now support filter/scorer for arbitrary endpoint attributes:
filter
scorer
They can replace legacy runningrequest, queuedepth and kvcaheutilization scorers.
To graduate them, we should:
What type of PR is this?
/kind guide
What this PR does / why we need it:
Adds a tiered-prefix-cache path where SGLang HiCache uses MooncakeStore over RDMA (RoCE) as its L3 tier. Each pod gets its own SR-IOV VF, matched to its RDMA device at startup. Includes a per-namespace Mooncake master helper and an OpenShift SR-IOV network helper.
Verification
2 decode pods (Qwen3-32B, TP=2, H100), through the EPP with load-only scoring: the first time the second pod received a ~7.2k-token prompt, it loaded 7,168 tokens from Mooncake instead of recomputing.
Limitations
Benchmarking
native/cpu baseline with the same CPU RAM size (200GB per tp-rank).guide_tiered-prefix-cache_1 with three stages โ 5 req/s for 150s (warm-up), then 6 and 10 req/s for 120s each .patch-sglang.yaml:43; not yet resolved.README.md:1, kustomization.yaml:1, README.md:1 - [high] Duplicating all 8 manifests of helpers/mooncake-master-store/ into helpers/mooncake-master-store-sglang/ creates a...Adds 23 opt-in vLLM tracing overlays for optimized-baseline and precise-prefix-cache-routing. They keep the existing model/provider settings, so there's no need to edit each manifest by hand. Also cleans up the tracing docs based on a real cluster run.
Related to #2703. This covers vLLM Deployments for now.
Tried this on 4ร A100 with vLLM v0.31.0:
llm_request had a CHILD_OF reference to EPP's request in the same trace, so the cross-service parent/child link checks out.423 Python tests, all 23 tracing overlay renders, README generation, and diff checks passed. Server dry-run passed 20/23; the other 3 need DRA APIs unavailable on Kubernetes 1.31.
Users of optimized-baseline and precise-prefix-cache-routing can enable vLLM tracing through opt-in overlays without changing their existing model or provider settings.Replaces commented-out vLLM tracing snippets across 11 patch-vllm.yaml files with a shared opt-in Kustomize Component (guides/recipes/observability/tracing/components/vllm-deployment/kustomization.yaml) and documents outer-overlay composition in docs/operations/observability/tracing.md. All existing modelserver overlays, tokenizer pools, guide matrices, and vllm serve behavior remain unchanged unless the operator composes and applies the tracing component.
guides/recipes/observability/tracing/components/vllm-deployment/kustomization.yaml:1-63): Targets apps/v1 Deployment with llm-d.ai/role=decode, asserts containers[0].name == modelserver and containers[0].command == [vllm, serve] via JSON Patch test ops, appends --otlp-traces-endpoint=$(OTEL_EXPORTER_OTLP_ENDPOINT), and injects OTEL_SERVICE_NAME, OTEL_POD_NAME (fieldRef: metadata.name), OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_TRACES_EXPORTER, OTEL_TRACES_SAMPLER, OTEL_TRACES_SAMPLER_ARG, and OTEL_RESOURCE_ATTRIBUTES=k8s.pod.name=$(OTEL_POD_NAME).docs/operations/observability/tracing.md:131-261): Guides operators to create a scratch kustomization.yaml under ${REPO_ROOT}/tracing-.../ referencing the guide's modelserver/<accel>/vllm/<provider> overlay in resources: and vllm-deployment in components:, with an optional GKE Managed OpenTelemetry patch overriding OTEL_EXPORTER_OTLP_ENDPOINT.scripts/tests/test_modelserver_tracing.py:1-358): Discovers all vllm provider overlays across optimized-baseline and precise-prefix-cache-routing, verifies EXPECTED_INCOMPATIBLE (ocp, biren, iluvatar, LeaderWorkerSet dynamic slices, and */vllm/tokenizer pools) fail or stay untouched while all compatible overlays preserve non-tracing config and OTEL_POD_NAME ordering.GUIDE_NAME=optimized-baseline, ACCELERATOR_TYPE=gpu, MODEL_SERVER=vllm, INFRA_PROVIDER=base and runs the snippet in docs/operations/observability/tracing.md:161-171 to create ${REPO_ROOT}/tracing-optimized-baseline-gpu-vllm-base/kustomization.yaml.kubectl apply -k builds guides/optimized-baseline/modelserver/gpu/vllm/base first, then applies vllm-deployment after patch-vllm.yaml has set command: ["vllm", "serve"] and args, appending --otlp-traces-endpoint=$(OTEL_EXPORTER_OTLP_ENDPOINT) and injecting the OTEL_* env vars (expanding $(OTEL_POD_NAME) into k8s.pod.name at container start).${MODEL_SERVER_BASE} (docs/operations/observability/tracing.md:490), restoring the Deployment without the tracing flag or OTEL_* variables.tracing.md:145 - [medium] The support table still lists npu (base) under Optimized Baseline only, even though Precise Prefix-Cache Routing now...vllm-rs) and SGLang (sgl-router) frontends. The original body describes routing client requests through a decoupled Rust frontend and an HTTP generation hop back to the gateway/Coordinator, whereas the thread converged on pod-local Loopback mode (frontend sidecar dialing a Coordinator loopback callback listener) as the cross-engine Coord-Text-Tok alternative to StageRPC (render.go / PR #3992).Recent work in vLLM and SGLang separates the frontend from the engine:
<img width="2757" height="781" alt="Image" src="https://github.com/user-attachments/assets/0947ca20-47b8-47a2-8103-29b62821b097" />
This opens an opportunity to reuse their frontends for input and output processing, while inference gateways route native tokens-in/tokens-out requests to the engines.
<img width="3301" height="1740" alt="Image" src="https://github.com/user-attachments/assets/6ef16e02-5094-47b6-87ac-2e5208963a21" />
For the proposed Rust frontend โ HTTP generation โ llm-d gateway โ engine design:
Pros:
Cons:
The main tradeoff is greater reuse of the frontend pipeline in exchange for a maintained remote-generation contract. Full feature parity depends on what the generation endpoint can represent.
SGLang
No code changes expected. Set --worker-urls to the coordinator URL.
[!NOTE]
APIs like OAI/Anthorpic/ollama are being offloaded from sglang's server to sgl-router, keeping sglang-server focused on tokens-in/tokens-out @rainj-me
vLLM
Code changes needed to send generate requests over HTTP instead of ZMQ.
<img width="3979" height="1100" alt="Image" src="https://github.com/user-attachments/assets/40dade84-7b45-4ab9-83eb-3dca76c2882d" />
Alternative approach - pros:
Alternative approach - cons:
[!NOTE]
the same approach also applies when sending requests without coordinator.
cc @vMaroon @elevran @roytman @nilig @hickeyma @ahg-g @liu-cong
Retains #3617 as the cross-engine Loopback RFC (vLLM and SGLang) under tokenize-once umbrella #3991, while #4828, #4829, #4830, #4838, #4839, and PR #4347 track concrete implementation gaps and parity work.
In Loopback mode, Coordinator terminates public text routes (/v1/chat/completions, string /v1/completions, /v1/responses, /v1/messages), runs handlers.go validation and header/body sanitization, attaches an internal correlation ID (#4829), and forwards to a pod-local vllm-rs or sgl-router sidecar over 127.0.0.1 (or UDS). The sidecar renders and tokenizes once and calls back into Coordinator's vllm.Inference / sglang.api.v1 / /inference/v1/generate callback listener, which joins the client context, trace, and cancellation signal and runs EPP + P/D worker stages. Pre-tokenized Coord-Tok-Tok traffic bypasses the sidecar.
Client POST /v1/chat/completions -> Coordinator ingress (handlers.go sanitization + RejectStatefulResponsesFields + validRequestID + correlation ID) -> loopback forward to pod-local sidecar -> sidecar tokenizes once and dials Coordinator callback listener -> correlation-ID join -> EPP + encode/prefill/decode workers.
@ahg-g, @sagearc, @elevran) converged on co-locating the frontend as a pod-local sidecar inside the Coordinator pod using VLLM_RS_REQUEST_WORKER_THREADS for in-pod CPU scaling rather than a separate deployment. Following @ahg-g's audit against PR #3992, #4828 (SGLang Loopback), #4829 (correlation-ID join, headers, single trace, cancellation, unmatched-callback rejection), and #4830 (shared ingress sanitization, stateful /v1/responses rejection, token-route bypass) were filed alongside #4838/#4839 and PR #4347. After initially supporting re-scoping #3617 to vLLM, @hickeyma rolled back that +1 after talking with @sagearc, proposing to keep #3617 open as the cross-engine (vLLM + SGLang) Loopback RFC under #3991 while @sagearc updates the stale body.redis-syncer writes each replica's whole approximate-prefix window to Redis every syncInterval and reads every peer's whole window back, even when nothing changed (Fixes #3971).What type of PR is this?
/kind performance
/kind feature
What this PR does / why we need it:
redis-syncer writes each replica's whole approximate-prefix window to Redis every syncInterval and reads every peer's whole window back, even when nothing changed. The cost scales with endpoints x window size x replicas, independent of request rate.
This PR adds windowReplication: incremental. A replica appends each new prompt once to a per-replica Redis stream next to the existing hash and keeps a small marker (epoch base tip size) in its hash field. Peers read only the prompts past the tip they already hold. maxBytesPerSecond (default 8 MiB/s per replica, each direction) caps stream bytes per second, so a cold window after a restart reaches peers over several ticks instead of in one large transfer.
full stays the default and its Redis commands are unchanged (covered by a test).base. A transaction with an unknown outcome is settled on the next tick from XLEN.redis_syncer_stream_bytes_total, redis_syncer_stream_budget_exhausted_total, redis_syncer_stream_resets_total, redis_syncer_stream_peer_lag_generations, redis_syncer_set_batch_duration_seconds.Values opt in by implementing datalayer.SequencedValue. PrefixHashSet implements it, with Base set to the generation of Prompts[0]. Other contributors are unaffected.
Benchmarks
Redis wire bytes (requests and replies) for two replicas, one endpoint, 2000-hash prompts with uniformly distributed hashes, miniredis, Apple M5 Pro. full is the main code path.
Steady state, one tick (BenchmarkSyncerWireBytesPerTick):
| Window | Tick | full: wire B/tick | full: time/op | incremental: wire B/tick | incremental: time/op |
|---|---|---|---|---|---|
| 72k hashes | unchanged | 3,888,455 | 2.98 ms | 1,440 | 0.15 ms |
| 72k hashes | one 128k-token prompt | 3,888,431 | 3.01 ms | 65,431 | 0.34 ms |
| 500k hashes | unchanged | 26,994,071 | 14.96 ms | 1,454 | 0.15 ms |
| 500k hashes | one 128k-token prompt | 26,994,047 | 14.93 ms | 65,454 | 0.36 ms |
In incremental mode the tick cost grows with the prompts added and is the same at 72k and 500k hashes. The 65 KB tick is the new 16 KB prompt written once and read once, plus command overhead.
Cold catch-up, 20 endpoints x 500k hashes, a peer with nothing cached, 50 ms ticks, default budget (BenchmarkSyncerColdCatchUp):
| Mode | Ticks to converge | Total wire bytes | Largest tick |
|---|---|---|---|
| full | 1 | 269,952,720 | 269,952,720 |
| incremental | 172 | 164,868,127 | 16,888,547 |
The largest incremental tick is the one-second burst for each direction. Later ticks move about 0.4 MiB per direction.
Not in this PR (O(window) local CPU that both modes share, tracked separately):
Read copies the window twice per tick: 0.87 ms and 8.2 MB allocated per endpoint at 500k hashes.Aggregate runs over all peer windows whenever any peer changes.Get on the request path runs Read plus Aggregate.Which issue(s) this PR fixes:
Fixes #3971
Release note _(write NONE if no user-facing change)_:
redis-syncer: add `windowReplication: incremental`, which publishes approximate-prefix windows as per-replica Redis streams and sends only new prompts each tick, and `maxBytesPerSecond` (default 8 MiB/s) to cap stream traffic per replica. The default `full` mode is unchanged.cross_replica_syncer.go:134, redis_stream.go:152, redis_stream.go:118 - [high] SequencedValue leaks stream wire serialization and a 1 MiB transport retraction rule into...What would you like to be added:
Establish a top-level tracking issue and shared cross-pillar interface contract for llm-d-router Flow Control across four pillars (Workload, Capacity, Sharing, and Signals) and SessionStateRegistry.
Why is this needed:
Contributors across Google, IBM, and Red Hat, and more have active RFCs and open PR stacks touching request identity, session state, fair sharing, cross-band scheduling, capacity admission, and in-flight reclamation. Several in-flight PRs (#3939, #3956, #3958, #3962, #3892, #3925, #3173) share request attributes, queue keys, and dispatch invariants. Locking down the boundary contracts in one public issue lets each pillar ship independently without rework.
Flow Control governs admission, queueing, fairness, and overload reclamation upstream of endpoint scheduling under four shared constraints from Flow Control: North Star (Foundations & Client Wire Conventions):
Cold Hold, the scheduler decides where it lands, and PreRequest commits a prefix-discounted Endpoint Lease against the chosen endpoint.| Pillar / Layer | Public Design Docs | Tracking Epic & Active Work | Contacts |
|---|---|---|---|
| Foundations & Wire Conventions | Flow Control: North Star (North Star, Foundations, Client Wire Conventions tabs) | This umbrella issue, #3632 | @LukeAVanDrie, @RishabhSaini |
| Workload | Flow Control: North Star (Workload tab) | Epic #2794 (#3934, PR #3939) | @RishabhSaini, @LukeAVanDrie |
| Sharing | Flow-Control: Sharing | Sharing Epic (to be linked) (#3471, #2920, #3734, PRs #3892, #3925) | @praveingk, @D-Sai-Venkatesh |
| Capacity | Capacity RFC (in progress) | Epic #3110 (PR #3111, #3154 / PR #3173, #3077, #3603) | @LukeAVanDrie |
| Signals | Signals RFC (open) | #2485, #2487, #3491, #3438 | @LukeAVanDrie, @madhugoutham |
| Session & Harness State (Cross-Cutting) | Session State Unification, Extending Session State Producer / Harness Signals | Epic #3796 (#3957, PRs #3956, #3958, #3962, #3371) | @zetxqx, @liu-cong, @D-Sai-Venkatesh, @praveingk, @satyamg1620 |
(TenantID, ProgramID) Carrier, Identity Split & Pre-Admission SessionStateOwners: @RishabhSaini, @zetxqx, @liu-cong, @D-Sai-Venkatesh, @praveingk, @satyamg1620
RequestHeaderLayer (pkg/epp/datalayer/data_graph.go, PR #3956) and DynamicRequestAttribute (pkg/epp/framework/interface/scheduling/attributes.go, #3957), avoiding direct producer lookups across plugins.agent-lineage (DerivedRootKey, PR #3939) publishes the program root for Flow Control fairness across parented sub-agent trees (Claude Code, Codex, opencode). agent-identity (pkg/epp/framework/plugins/requesthandling/requestheader/agentidentity/agent_identity.go, AgentIdentityKey) stays distinct as the leaf/thread identity for KV and endpoint session affinity.pkg/epp/requestcontrol/director.go, Director.HandleRequest sets InferenceRequest.FairnessID to the raw fairness header before runRequestHeaderProcessors and overwrites FairnessID with <escaped-tenant>/<program> afterward. Seeding immutable TenantID on scheduling.InferenceRequest (pkg/epp/framework/interface/scheduling/types.go) before RequestHeader runs, and setting ProgramID (DerivedRootKey falling back to AgentIdentityKey) right after RequestHeader, lets RequestHeader plugins, PreRequest / ResponseBody hooks, TenantNode queues, and EvictionItem policies read structured fields directly (FairnessID stays populated for flat single-level policies).#3958 and #3962, SessionStateRegistry (pkg/epp/framework/plugins/requesthandling/dataproducer/sessionstate/registry.go) keys program-level counters (TurnsTaken, ServedInputTokens, ServedOutputTokens, TotalCachedTokens) on (TenantID, ProgramID) so LASStrategy (pkg/epp/framework/plugins/flowcontrol/fairness/program-aware/strategy_las.go) and turn-priority (#3796) track multi-agent programs accurately under composeFairnessIDs. Phase 2 under #3796 nests per-thread state (thread_id, parent_id, WAITING-TOOL / IDLE) beneath the program record for thunder-agent (#3371) and KV residency.Tenant -> Program Sharing, Program Cap & Over-Share ReclamationOwners: @praveingk, @D-Sai-Venkatesh, @RishabhSaini, @LukeAVanDrie
weighted-fair-share-fairness-policy (pkg/epp/framework/plugins/flowcontrol/fairness/weightedfairshare/weightedfairshare.go, #3471) indexes flowWeights by flat FlowKey.ID (pkg/epp/framework/interface/flowcontrol/flow.go). Evolving Sharing into a two-level TenantNode -> ProgramQueue hierarchy keyed by (TenantID, ProgramID) enforces tenant weights regardless of how many concurrent agent roots a tenant spawns.per-tenant program cap routes overflow roots into a per-tenant default program queue, bounding queue cardinality per tenant and retiring agent-lineage's interim global map cap.pkg/epp/flowcontrol/controller/internal/reclamation.go and pkg/epp/framework/interface/flowcontrol/eviction.go) picks the victim tenant inside the target sheddable band by highest instantaneous weighted in-flight share (running_tokens / weight), then delegates intra-tenant victim ordering to Workload's 4-class kind ordering (background > subagent_exploratory > subagent_critical > foreground).BandSelectionPolicy Standard & Blocked Higher-Band Cold Hold RuleOwners: @loicmarchal, @praveingk, @LukeAVanDrie
BandSelectionPolicy (pkg/epp/framework/interface/flowcontrol/plugins.go, #2920), avoiding a separate band-picker interface. PR #3892 (cross-band-fairness-policy) proceeds under existing monotonic scalar UsageLimit ceilings.Cold Hold lands in Processor.dispatchCycle (pkg/epp/flowcontrol/controller/internal/processor.go), a Cold Hold refusal on the selected head of any non-empty priority band blocks dispatch from all strictly lower bands for that cycle, including minimum-share and work-conserving fallback slots, and arms ReclamationController against evictable bands strictly below the blocked band.stop_reason, Harness compaction Hints & Cached-Token CreditOwners: @D-Sai-Venkatesh, @RishabhSaini, @zetxqx, @LukeAVanDrie
stop_reason (tool_call | turn_ended | unknown) and stock harness compaction / fork hints are extracted once across parser and request-header layers to supply SessionState (WAITING-TOOL / IDLE), Workload foreground-join classification, and Capacity between-turns KV residency leases.Sharing charges raw prompt tokens at dispatch and credits cached prompt tokens post-placement / post-response (TotalCachedTokens in #3958 alongside capacity-ledger #3110).#2794 as the Workload pillar epic and land #3939 (@RishabhSaini)TenantID / ProgramID on scheduling.InferenceRequest and key #3958 program state on (TenantID, ProgramID) before #3962 and turn-priority merge (#3796, @zetxqx, @RishabhSaini)Sharing pillar epic covering TenantNode -> ProgramQueue, per-tenant program cap, and instantaneous weighted in-flight share victim selection (@praveingk, @D-Sai-Venkatesh)cross-band-fairness-policy (#3892) on BandSelectionPolicy (@loicmarchal)Cold Hold -> Endpoint Lease integration under #3110 (@LukeAVanDrie)stop_reason and harness compaction hint plumbing under #3796 and #2794 (@D-Sai-Venkatesh, @zetxqx, @RishabhSaini)What type of PR is this?
/kind feature
What this PR does / why we need it:
Every request is scheduled in its own goroutine as score -> pick -> PreRequest-increment. A burst of concurrent requests is therefore scored against the same pre-pick snapshot, and the least-loaded endpoint wins every pick: the whole burst lands on one pod (#1598).
This PR closes both gaps:
1. Reserve at pick (closes G1). The scheduler reserves the picked endpoints immediately after each profile run, through the inflight-load-producer. The reservation is added to the InFlightLoad the scorers read, so the next concurrently-scheduled request sees each pick without waiting for dispatch. Reservations are request-scoped plugin-state entries: PreRequest converts them into the real counters, and abandonment rolls them back - a request cannot release a reservation it did not make.
The reservation is unconditional: it is an accounting fix, not a policy change - the pick is recorded when it happens (not ~0.4 ms later at dispatch), and it alters no scoring or picking decision.
Reservations count toward the InFlightLoad attribute every consumer reads, not only the load scorers: the utilization filter's
active-requests conditions and the flow-control saturation detectors also see them, so scheduled-but-not-dispatched requests
now count toward filtering and shedding thresholds (documented in the producer's README).
2. Pick-time scoring (closes G2). A load scorer can opt in with scoreAtPick: true:
filters, other scorers (concurrent, as before)
lock(pickMu) (one mutex per Scheduler)
re-run the pick-time scorers (read the LIVE load: every earlier pick's reservation is already in it)
picker.Pick (unchanged, tie rotation intact)
reserve the picked endpoint
unlock
The critical section holds only the opted-in scorers (token-load-scorer and active-request-scorer), the picker (a sort) and the reservation; filters, prefix hashing and the other scorers stay outside. Measured under full contention: ~12 us per request. Profiles with no opted-in scorer take no lock at all.
token-load-scorer and active-request-scorer implement scoreAtPick (off by default). Scorers that read scraped model-server metrics cannot benefit - their inputs do not change at pick time (that staleness is the metrics scrape interval, a separate problem).
Configuration (opt-in):
plugins:
- type: inflight-load-producer
- type: token-load-scorer
parameters:
scoreAtPick: true
- type: max-score-picker
In-process (real producer, scorers, picker, Scheduler.Schedule; a barrier scorer holds a fully concurrent burst at the scoring step - the worst case for G2): with scoreAtPick a burst ends with exactly the per-endpoint load of one-at-a-time scheduling; without it, 0/0/0/16 on the least-loaded endpoint. Non-overlapping requests pick identically ON vs OFF (no behavior change outside bursts). Exactly one reservation per profile run. Mutation checks (lock removed / flag off ) fail the tests. Full suites pass -race.
Live setup:
Definitions:
| profile, EPP log level | excess OFF -> ON | bursts at ideal OFF -> ON | max TTFT OFF -> ON |
|---|---|---|---|
token-load, --v=4 | 1.83 -> 0.00 (p < 0.0001) | 2/18 -> 18/18 | 9.77 s -> 7.40 s (p < 0.0001) |
active-request, --v=4 | 0.67 -> 0.00 (p = 0.004) | 5/12 -> 12/12 | 8.28 s -> 7.41 s (p = 0.002) |
token-load, --v=2 | 0.11 -> 0.00 (n.s.) | 16/18 -> 18/18 | 7.52 s -> 7.40 s (n.s.) |
active-request, --v=2 | 0.08 -> 0.00 (n.s.) | 11/12 -> 12/12 | 7.53 s -> 7.39 s (p = 0.009) |
Debug logging (--v=4) widens the score-to-pick window to ~1.4 ms per request, which reproduces the race. There, pick-time scoring places every burst exactly like one-at-a-time scheduling and removes ~2.4 s from the slowest request of each burst.
At production verbosity on this small rig (4 endpoints, one load scorer, idle CPUs), the race left after the reservation is too small to measure, and ON matches OFF. The same holds with the real tokenizer and with a token-load + queue + KV-utilization profile.
The window size sets the herd's magnitude: a request that reads the load while another is still between its own read and its pick cannot see that pick, so the herd is bounded by how many requests are mid-window at once. This rig is the best case for the unfixed code - one load scorer, 4 endpoints, idle CPUs - and production stacks (several scorers, larger endpoint sets, busier CPUs) sit between the two log levels above; the race also reappears at --v=2 as bursts grow (excess 0.50 at 256 requests). Pick-time scoring does not shrink the window; it makes it irrelevant, because the read happens inside the lock, after every earlier pick's reservation.
Stock main (no reservation) at --v=4 measured excess 2.08 and max TTFT 10.07 s. That is not distinguishable from reservation-only (1.83, 9.77 s): the live gain comes from pick-time scoring, and the reservation is its accounting prerequisite.
No regressions:
--v=2, one run per arm): ON was ideal in every burst. OFF had one non-ideal burst each at 128 (+1) and 256 (+2), too few bursts for significance.Not addressed by this PR: the default profile (queue, kv-cache-utilization and prefix-cache scorers, no inflight-load-producer) herds on the same rig, with up to 48% of tokens on one pod and the worst TTFT around 25 s. All of its inputs are scraped model-server metrics that stay the same for the whole burst, and pick-time scoring cannot help scorers whose inputs do not change at pick time.
Which issue(s) this PR fixes:
Part of #1598 (the scheduling races; the default profile's metric-staleness herd is a separate follow-up)
Release note _(write NONE if no user-facing change)_:
the EPP now reserves picked endpoints at scheduling time, and load-based scorers (token-load-scorer, active-request-scorer) can opt in to `scoreAtPick: true`, which re-scores the live in-flight load inside the picker's critical section. Together these close the two races that made concurrent bursts converge on a single endpoint: each pick is visible to the next request immediately, and the burst is placed exactly as one-at-a-time scheduling under the scorer's own cost model. The reservation is always on when the inflight-load-producer is configured; `scoreAtPick` is opt-in and off by default.plugins.go:103, scheduler.go:55 - The test rewrite in TestAddPluginsProfileRunsPickTimeScorers, removal of HasPickTimeScorersForTest, and temporal-prose...sampling_params.n above 1, sglang streams each sample of a /generate request as its own sequence: every event carries the sample index, and each sample reports only its own completion_tokens on its final event...What type of PR is this?
/kind bug
What this PR does / why we need it:
with sampling_params.n above 1, sglang streams each sample of a /generate request as its own sequence: every event carries the sample index, and each sample reports only its own completion_tokens on its final event (_stream_batch_responses in sglang's tokenizer_manager.py). the sglanghttp and sglanggrpc parsers returned the usage of one finished sample per chunk, and HandleResponseBody merges chunks last-wins, so a streamed n=4 request recorded the output tokens of a single sample. the non-streaming path already sums the samples since #3897, which called out this streaming gap as a follow-up (also noted in #3896 and in the sglanggrpc ParseResponse doc comment).
the fix:
ParsedResponse gets a SampleCompletionTokens map[int]int field: the completion tokens of every sample that finished in the parsed chunk, keyed by sample index. nil when no sample finished, so intermediate chunks are unchanged (the steady-state alloc test still passes).sglanghttp keeps scanning the chunk after the first final event and lists each finished sample (a single-sample stream has no index and lands under 0). sglanggrpc lists each terminal frame by GenerateResponse.index.Usage.CompletionTokens (and TotalTokens) to their sum after the other merges, so salvaged usage from an oversized line cannot overwrite the sum with one sample's count. a sample reported twice keeps its latest count instead of being double counted.prompt and cached tokens keep their current handling, since every sample shares the prompt. this affects the output token metrics, ntpot/tpot, and anything reading reqCtx.Usage for sglang /generate streams with n > 1; single-sample streams produce the same usage as before.
tests:
TestHandleResponseBodySGLangParallelSamplingAcrossChunks drives http and grpc streams through HandleResponseBody with samples finishing in separate chunks and in one chunk, plus a single-sample stream. on main the parallel cases record 3 of 8, 4 of 13 and 7 of 10 completion tokens; with the fix they record the sums.SampleCompletionTokens in sglanghttp_test.go and sglanggrpc_test.go.go test ./pkg/epp/handlers/... ./pkg/epp/framework/plugins/requesthandling/... ./pkg/epp/framework/interface/... -count=1 # all ok
golangci-lint run --config=./.golangci.yml ./pkg/epp/handlers/... ./pkg/epp/framework/plugins/requesthandling/parsers/... ./pkg/epp/framework/interface/requesthandling/... # 0 issues (v2.14.0, same as the builder image)
go build ./...
Which issue(s) this PR fixes:
follow-up to #3896 / #3897 (streaming n > 1 gap noted there; no separate issue).
Release note _(write NONE if no user-facing change)_:
the epp now counts the output tokens of every sample for streamed sglang /generate requests with sampling_params.n above 1, over http and grpc, instead of only one sample.Adds per-sample completion token reporting via SampleCompletionTokens on ParsedResponse so streamed SGLang /generate responses with sampling_params.n > 1 sum completion tokens across all finished samples instead of keeping only one sample's count under last-wins chunk merging. Both sglanghttp and sglanggrpc populate SampleCompletionTokens keyed by sample index on terminal events while leaving intermediate chunks untouched, salvageDroppedSSELine accumulates unindexed counts from oversized (>4 MiB) final SSE events in salvagedCompletionTokens, and HandleResponseBody sums indexed and salvaged sample counts to compute Usage.CompletionTokens and Usage.TotalTokens. Prompt token counting, cached token reporting, and non-streaming /generate responses remain unchanged.
pkg/epp/framework/interface/requesthandling/parser.go): Adds SampleCompletionTokens map[int]int to ParsedResponse, left nil when no sample finishes in a chunk.extractStreamingUsage scans every SSE data: line in a chunk and records each finished sample under event.Index (default 0). SGLangGRPCParser.ParseResponse records each finished GenerateStreamItem frame with completionTokens > 0 under int(item.Index).pkg/epp/handlers/response.go, pkg/epp/handlers/usage_salvage.go, pkg/epp/handlers/server.go): Stores sampleCompletionTokens map[int]int and salvagedCompletionTokens int on RequestContext. salvageDroppedSSELine adds dropped oversized event completion tokens into reqCtx.salvagedCompletionTokens. After mergeUsage and salvagedUsage, mergeSampleCompletionTokens overwrites entries by index (preventing double-counting on duplicate reports) and sets Usage.CompletionTokens to salvagedCompletionTokens plus the map sum before metrics emission./generate request with sampling_params.n = 2 receives chunk 1 containing non-terminal events for indexes 0 and 1: SampleCompletionTokens is nil.1 (completion_tokens: 5): salvageDroppedSSELine records reqCtx.salvagedCompletionTokens = 5 and reqCtx.salvagedUsage sets PromptTokens: 10, CompletionTokens: 5.0 (completion_tokens: 3, endOfStream: true): SampleCompletionTokens is {0: 3}, mergeSampleCompletionTokens computes 5 + 3 = 8 for reqCtx.Usage.CompletionTokens (TotalTokens = 18), and end-of-stream output/TPOT metrics record 8.response.go:132, sglanggrpc.go:261 - [low] Once one sample finishes, reqCtx.sampleCompletionTokens != nil stays true for the rest of the stream, so...Tracker doc https://docs.google.com/document/d/1tM2qI_ElFaIvBy5p564OmrqhLzFzB89P-N7Onhu3UbI/edit?tab=t.0
What would you like to be added:
A tracking issue for making a session the addressable unit the router and engine share, so prefix-cache affinity, eviction visibility, and retention all become expressible over one identity. This is the umbrella; each step below lands as its own issue and PR, and each is independently useful.
The building blocks are two identifiers and three contracts, all computed by the router from request bytes โ no tokenization, no engine hashes on the wire:
session_tag โ policy scope. A router-minted handle for a lineage; declared client ids (prompt_cache_key, previous_response_id, session headers) alias it, content seeds it where they are absent.continuation_id โ the addressable node. A content-derived chain position; hash-prefix equality holds exactly when content prefixes are byte-identical, the condition for KV reuse. Recomputable from any resent prefix.application -> llm-d): declared identity where present, derived from content where absent; external APIs untouched.engine -> llm-d): session labels ride block-store events, so the index learns what the engine actually holds instead of guessing.llm-d -> engine): retain first, then offload / move / prefetch, all addressed in the same coordinates.Roadmap:
session -> {engine -> extent} index, and covered-fraction affinity through the existing prefix-cache-scorer slot. Tracked in #<L1L2-issue>.session_tag + continuation_id on the request, echoed on block-store events.The end-state is session/continuation-id-driven communication between the router and the engine: eviction signals, retention, and prefetch all expressed at the session/node language level, with block hashes and token offsets kept engine-internal.
Boundary that holds across every stage: the engine is the mechanism, llm-d is the meaning. State and policy live in the router; the engine exposes primitives and stays policy-unaware. Engine-side steps are proposals to raise with vLLM, tracked here for the shared picture; the router steps stand on their own against stock engines.
Why is this needed:
Prefix-cache routing is solved โ approx-prefix-cache-producer and precise-prefix-cache-producer both route to where a prefix is cached, precise truthfully from KV events. What the stack lacks is orchestration of session state: keeping a paused session warm, placing and moving it, prioritizing by program. The truthful visibility it has speaks block hashes โ the right level for reusing a prefix, the wrong level for these: a hash-keyed LRU cannot tell a paused session's KV from dead KV, and offload, move, and program-aware placement have no session to address. The root is one missing name โ the serving layer has no identity for a session's state. Naming it once, from content and aligned with what the Responses and Messages APIs already declare, lets the orchestration stack build over a single index instead of arriving as separate mechanisms.
/kind feature
cc @liu-cong @bongwoobak @hyeongyun0916
Subagents are often short-lived: they spawn to execute a specific task or tool call, build up a large KV cache, run briefly, and terminate. When serving these workloads without explicit session isolation:
Upstream open-source SGLang introduced explicit Session Control (/open_session, /close_session, session_params, SessionRadixCache), which isolates session KV caches into dedicated streaming slots outside the main radix tree, protecting them from LRU radix eviction and allowing deterministic memory release.
NVIDIA Dynamo integrates this SGLang session control mechanism into its serving backend, wrapping session actions (open, close, bind) and routing hints (nvext.session_control, nvext.agent_hints) into OpenAI-compatible interfaces.
Provide an experimental plugin integration with this feature and validate with benchmark. The goal is to understand how much benefit this provides. Graduating to a stable plugin will come next depending on the results.
x-session-control)./open_session, /close_session) and session_params payload objects.Status: Initial brainstorming with an AI agent โ details are subject to change as implementation starts and maintainers weigh in.
PR volume is rising and we need to merge with high confidence. Per-PR CI today validates plumbing (unit / hermetic integration / sim e2e) but not:
test/perf runs nightly but covers only optimized-baseline and performs no baseline comparison (it measures and records, nothing gates or alerts).Full E2E benchmarks are too slow and GPU-hungry to gate PRs, so we need fast, GPU-free evaluation.
Ship a small set of canned, router-owned presets (config/presets/*.yaml, delivered in the EPP image/chart like default-plugins.yaml) covering well-known workload patterns, and point all evaluation at exactly those presets:
make update-replay-goldens.test/perf: (a) preset coverage in the nightly matrix (realign test/perf/config/router-configs/ to consume shipped presets), (b) trend comparison vs trailing GCS history โ >10% degradation vs 7-day median auto-files an issue, (c) a /perf-deep slash command to run the suite against a PR branch on demand.Initial preset candidates (seeded from the well-lit-path guide configs, then router-owned): optimized-baseline, pd-disaggregation, precise-prefix-cache-routing, tiered-prefix-cache, predicted-latency-routing, flow-control.
test/perf extensions (preset coverage, trend comparison, /perf-deep)/perf-deep.Umbrella proposal spanning shipped EPP configuration presets, deterministic scheduler replay tests, kind e2e smoke coverage, nightly perf trend gating, and contributor checklists.
On origin/main, #3580 implemented the 7-day trailing median trend check in test/perf/trend.py with per-metric thresholds in test/perf/config/targets/optimized-baseline-job1.yaml (0.10 CPU/mem, 0.25 scheduler latency), max-of-window plus 2-consecutive-run gating, and router_config exclusion from DIGEST_FILE_KEYS so router config updates preserve baselines. Remaining components (config/presets/, test/replay/, test/e2e/ Presets matrix, /perf-deep, and preset perf targets) remain unimplemented and should align with llm-d.ai/v1 (#2923), Runner config phases + ValidatePluginStability (#2384) + --validate-config (#4175), and chart vs. image packaging boundaries.
In cmd/epp/runner/stable_plugin_configs_test.go, TestStablePluginConfigs validates configs via r.parseConfigurationPhaseOne, r.parseConfigurationPhaseTwo, and fwkplugin.ValidatePluginStability(r.PluginHandle, false); test/replay/ should reuse that pipeline before driving pkg/epp/scheduling.
doctor capture bounded in-memory ring buffer + offline doctor analyze Cache Hit Rate Ladder and counterfactual scorer sensitivity pass). Two open PRs carry related building blocks: #3916 (satyamg1620, #3229 Phase 2 /debug/scheduling/recent decision ring buffer with top-5 endpoint trimming by default) and #4205 (sohom-cs, initial pkg/epp/scheduling/capture.Record schema and tools/doctor ladder).The google doc has more details.
Feel free to comment on this issue or in the google doc.
The llm-d Router Profiler is an on-demand diagnostic tool (analogous to Go's pprof) that solves the black-box routing problem: "Why is my cache hit rate lower than expected?" and "Are my scorers and filters conflicting?"
doctor capture against router replicas. The router records lightweight, privacy-preserving decision traces (block hashes, filter drops, weights, scores) into a bounded in-memory ring buffer.doctor analyze on the downloaded directory. It replays request fingerprints through mathematical cache simulations and counterfactual scoring to output root-cause findings and remediations.$ doctor run --replicas epp-0:9090,epp-1:9090 --duration 5m --fleet-kv-blocks 32768
LADDER (cache hit rate breakdown)
Ideal unbounded shared cache 74.2% <-- Workload ceiling (max possible reuse)
Capacity bound fleet KV capacity, one shared cache 58.1% <-- 16.1% lost to GPU RAM capacity limit
Perfect routing same capacity split per endpoint 55.4% <-- 2.7% lost to distributed sharding
Observed what the router achieved 41.8% <-- 13.6% lost to router routing deficit
records: 1420, endpoints: 4, blocks simulated: 28400, dropped: 0
ACTIONABLE ROOT-CAUSE FINDINGS:
[WARNING] Hit rate is capacity-bound (16.1% gap)
--> Action: Enable CPU KV offloading or scale GPU RAM to stop premature prefix evictions.
[CRITICAL] Router routing gap detected (13.6% gap)
--> Action: Raise 'prefix-cache-scorer' weight from 1.0 to 3.0 so cache affinity wins routing.
[WARNING] Dead scorer detected: 'queue-depth-scorer' (weight: 1.0)
--> Action: Removing or doubling it flips 0.0% of decisions. Remove to save CPU scheduling time.sohom-cs claimed #2326 with a 3-step plan (shared capture buffer with #3229 Phase 2, offline analyze ladder, and counterfactual scorer pass) and opened #4205. liu-cong reviewed #4205 on Nov 23-24 requesting token alignment (PredictedCachedTokens vs EngineCachedTokens) and scheduling profile support for P/D. On Nov 19, tryambak2019 stepped back from the analyzer and offered to own the counterfactual pass once capture stabilizes. On Nov 25, sohom-cs noted counterfactual depends on capture having scorer weights and every candidate's per-scorer scores (#4205 has neither and #3916 trims to top 5 endpoints by default), preferring to keep item 3 with capture unless liu-cong decides otherwise.What happened
With the Anthropic parser enabled, every POST /v1/messages/count_tokens routed through the endpoint picker fails at the gateway with HTTP 500 ext_proc failed: failed to send request, while POST /v1/messages from the same clients (same conversations, same body sizes) succeeds. Measured on one production InferencePool over a 72-minute window:
| Path | Requests | Result |
|---|---|---|
/v1/messages/count_tokens | 158 | 158 ร HTTP 500, 0 successes |
/v1/messages | 320 | 320 ร HTTP 200 |
Each failing request lines up, to the second, with these EPP log lines:
error failed to prepare per request data DataProducer "token-producer/token-producer" failed: unsupported request body type, skipping estimation
error failed to read prefix plugin state not found
The Anthropic parser has supported count_tokens since #1509 ("the body is forwarded unchanged as a raw payload"), so the request is accepted โ but the raw payload has no typed body, estimateBytes (pkg/epp/framework/plugins/requestcontrol/dataproducer/tokenizer/estimate.go) lands in its default: arm, the prefix plugin finds no state, and the ext_proc stream ends in an error rather than a "skip scoring, pick any endpoint" outcome. The gateway's failureMode: FailOpen does not help because agentgateway only honours it before body bytes have been sent (agentgateway/agentgateway#3362), so the client sees a 500.
Why it matters: Anthropic-protocol clients call count_tokens for context accounting late in long sessions (Claude Code does, once the conversation is large), so a pool that serves /v1/messages perfectly still kills every long-running client at ~100 turns.
Environment
llm-d-router-endpoint-picker:v0.9.0 (I could not find a fix for this in the v0.10.0 notes; happy to be corrected)InferencePool with endpointPickerRef.failureMode: FailOpen/v1/messages/count_tokens directly (present in its /openapi.json); routing the path straight to the Service works.Expected
A request the parser accepts as a raw payload should not fail the ext_proc call when a data producer or scorer cannot use it. For count_tokens specifically, "skip estimation and prefix scoring, choose an endpoint by the remaining scorers (or any healthy endpoint)" would be the right outcome โ the response is a token count and gains nothing from cache affinity, as the parser's own comment notes.
Workaround we run
An HTTPRoute rule ahead of the InferencePool rule that sends /v1/messages/count_tokens to the vLLM Service directly (bypassing the EPP). We will remove it when this is fixed and released.
Disclosure: this issue was drafted by an AI coding agent (Claude) on behalf of @HipHoff, who approved filing it and owns it. Evidence is from our own production gateway/EPP logs, aggregated; no request content is included.
What:
Each scheduler publishes KV-cache events on a ZMQ port numbered by its global DP rank (5557 + dp_rank), but the serving listeners on each node are numbered by local rank (30000 + local_index).
Why it breaks:
for each kv event, the serving port is guessed from the zmq port offset
Example
2 nodes, 4 DP ranks (2 per node), ZMQ base 5557, HTTP base 30000:
| Global DP rank | ZMQ PUB port (5557 + global) | Rust listener (30000 + local) | |
|---|---|---|---|
| Node 0 | 0, 1 | 5557, 5558 | 30000, 30001 |
| Node 1 | 2, 3 | 5559, 5560 | 30000, 30001 |
Ref:
sglang fix: https://github.com/sgl-project/sglang/pull/39659
vllm fix: -
fyi @Amit-Berman @ahg-g @vMaroon @liu-cong @zetxqx
EPP maps each pod target port to a node-local RankIndex (0..N-1 per pod), whereas multi-node SGLang schedulers bind ZMQ KV-event PUB sockets at 5557 + global_dp_rank. Open PR #4392 introduces PodDiscoveryConfig.GrpcBasePort to query SGLang GetServerInfo for DeploymentInfo.DpRank, but leaves the newer shared kv-events-source (#3911) untouched and still uses RankIndex for replay/snapshot ports.
In pkg/epp/datastore/datastore.go, podUpdateOrAddIfNotExist sets EndpointMetadata.RankIndex from the port index in pool.TargetPorts (0, 1 on every node). Both pkg/epp/framework/plugins/requesthandling/dataproducer/preciseprefixcache/extractor.go (subscriberEndpoints) and pkg/epp/framework/plugins/datalayer/source/kvevents/source.go (Extract, from #3911) add RankIndex to SocketPort, EffectiveReplayPort(), and SnapshotSocketPort (with extractor.go honoring meta.ZMQPort from #4288 for file discovery).
Open PR #4392 adds GrpcBasePort to pkg/kvevents/pool.go (PodDiscoveryConfig) and dials apiv1.SglangServiceClient.GetServerInfo at GrpcBasePort + RankIndex in preciseprefixcache/server_info.go to read DeploymentInfo.DpRank and KvEventSources, retrying asynchronously until the server responds. Three gaps remain in #4392:
pkg/epp/framework/plugins/datalayer/source/kvevents/source.go (kv-events-source) is not updated, so shared KV-event pipelines remain broken.finishGRPCSubscriber calls p.subscriberEndpoints(meta) for replayEndpoint and snapshotEndpoint, which still offsets by meta.GetRankIndex() instead of int(dpRank).preciseprefixcache imports SGLang's generated gRPC client directly instead of isolating engine-specific metadata discovery behind pkg/kvevents / an adapter, and GrpcBasePort lacks 1..65535 startup validation.With 2 nodes and 2 local ranks per node (TargetPorts: [30000, 30001], SocketPort: 5557, ReplaySocketPort: 5558), Node 1 runs global DP ranks 2 and 3. Currently EPP subscribes Node 1 endpoints (RankIndex 0 and 1) to 5557/5558 instead of 5559/5560. In PR #4392, GetServerInfo returns DpRank=2 on Node 1 rank 0 so zmqEndpoint becomes :5559, but replayEndpoint from subscriberEndpoints(meta) still computes 5558 + 0 = :5558 instead of 5558 + 2.
What would you like to be added:
Warm start for a new or promoted EPP replica: bootstrap request-path state (approximate prefix index, no-hit-lru-scorer ordering, speculative seeds) from peers or a shared syncer instead of starting empty.
Why is this needed:
On active-passive failover, or when a replica joins an active-active set, the replica starts with no learned routing state, so routing quality drops until it relearns. Carried over from the snapshot bootstrap stage of #1892.
Part of #1946.
Replace request-path prefix peer merging with an off-path serial import worker in crossReplicaPublisher fed by versioned PeerSnapshot reads from CrossReplicaSyncer, plus opt-in per-spec StateTTL for rejoin.
On failover or restart, SetBatch updates PeerSnapshot version -> importWorker calls approx-prefix.ImportCrossReplica off-path -> standby/restarted EPP matches prefixes against its local indexer in ~0.28 ms without running mergeRemoteHashes or Get+Aggregate during Produce.
sglang-torchtpu) across llm-d well-lit paths. Phase 1 (optimized-baseline, tiered-prefix-cache host-DRAM HiCache on v5p/v7, and pd-disaggregation over raiden with HiCache on both roles) is merged as community with tpu/v5p nightlies for optimized-baseline and tiered-prefix-cache consistently green through 2026-11-26. Phase 2 (tpu/v7/sglang/native/fs on Managed Lustre) and precise-prefix-cache-routing (#2980) remain blocked because v0.1.0-tpu (2026-10-19) is still the only lmsysorg/sglang:*-tpu release tag on Docker Hub; Phase 3 (multi-host wide-EP P/D) awaits SGLANG_RUST_SERVER=1 validation on TPU (#2899), and follow-up PR #3037 (kimi-k3-1 tuning) remains open.This issue tracks bringing SGLang on Google Cloud TPU (sglang-torchtpu, published as the lmsysorg/sglang:*-tpu images) to the llm-d well-lit paths that SGLang on NVIDIA GPU already has. The SGLang GPU recipes are the baseline: each TPU item below mirrors an existing modelserver/gpu/sglang overlay, reuses its router configuration, and is validated on tpu7x (2x2x1, 4 chips / 8 TensorCores) GKE node pools. vLLM already covers these paths on TPU (modelserver/tpu/*/vllm), so the guide structure, guide.yaml rows and nightly-lane conventions are in place.
KV-cache tiering is the thread through all of it: L1 (HBM radix cache) in every overlay, L2 (host DRAM through SGLang HiCache) in the tiered and P/D overlays, and L3 (shared storage) once the engine carries it.
optimized-baseline, tiered-prefix-cache (host DRAM tier) and pd-disaggregation (with host DRAM tier on both roles), each community in its guide.tiered-prefix-cache, validated with Google Cloud Managed Lustre.validated.Status as of 2026-11-11: โ done ยท ๐ง in review / in progress ยท โฌ not started ยท โ blocked
| # | Phase | Well-lit path | SGLang GPU baseline (exists today) | SGLang TPU item | Status |
|---|---|---|---|---|---|
| 1 | 1 | Image component | images/gpu-sglang/{release,nightly} | images/tpu-sglang/release tracking the sglang-torchtpu release images (bumped as releases ship) | โ #2890 (merged 2026-10-27) |
| 2 | 1 | optimized-baseline | gpu/sglang (Qwen3-32B, TP=2), GKE nightly | tpu/{v5p,v6,v7}/sglang (Qwen3-32B; v7 = TP=8 on one 2x2x1 node, torch-compile with bucket precompile) + GKE TPU SGLang nightly | โ #2890 (merged 2026-10-27) |
| 3 | 1 | tiered-prefix-cache, host DRAM tier (native/cpu) | gpu/sglang/native/cpu (HiCache, 200 GB/rank), GKE nightly | tpu/v7/sglang/native/cpu: HiCache with the Torch TPU io backend (page_first_fused layout, 32 GB/rank = 256 GB/pod), --page-size=64, router lruCapacityPerServer row; plus a tpu/v5p/sglang/native/cpu variant (TP=4 on 2x2x1, the pattern of #2890's v5p baseline) so the lane in item 8 can run on the CI cluster's v5p capacity | โ
#2915 (merged 2026-10-29: v7 and v5p overlays plus the v5p nightly lane; validated on tpu7x and on ct5p-hightpu-4t Spot) + #3004 (merged 2026-11-02: variant-level kustomization.yaml the TPU lanes render) |
| 4 | 1 | pd-disaggregation | gpu/sglang: one DisaggregatedSet, 1P (TP=2) + 1D (TP=2), gpt-oss-120b, NIXL, routing sidecar --kv-connector=sglang, GKE nightly | tpu/v7/sglang: same DisaggregatedSet shape, 1P + 1D on one 2x2x1 node each (gpt-oss-120b TP=8/EP=8), --disaggregation-transfer-backend=raiden (tpu-sync DMA over the pod network; SGLang's bootstrap/ZMQ rendezvous and the sidecar protocol are unchanged), default pd-disaggregation.values.yaml | โ merged 2026-10-28 through #2946, which was stacked on #2945 and carried it (#2945 closed as superseded) |
| 5 | 1 | pd-disaggregation + host DRAM tier | none merged for SGLang GPU (the GLM-5.2 guide has a prefill-only hicache component) | HiCache on both roles (--hicache-io-backend=raiden, 32 GB/rank): the prefill restores evicted prefixes from host DRAM instead of recomputing; the decode adds --disaggregation-decode-enable-radix-cache so a follow-up turn reuses the KV it already holds (transferred prefix plus its own response) instead of pulling it from the prefill again. Mirrors sglang-torchtpu's pd_singlehost_kv_offload CI configuration | โ #2946 (merged 2026-10-28) |
| 6 | 2 | tiered-prefix-cache, shared-storage tier (native/fs) | gpu/sglang/native/fs (HiCache file backend on a RWX PVC) | tpu/v7/sglang/native/fs on Managed Lustre, same file backend | โ release: sgl-project/sglang-torchtpu#1610 (file backend on the TPU host pool) merged 2026-10-29; the overlay waits for the next lmsysorg/sglang:*-tpu release image - as of 2026-11-11 v0.1.0-tpu (2026-10-19) is still the only release tag; the newer dev-kimi-k31-pro-tpu is a dev image |
| 7 | 3 | Multi-host P/D with wide-EP (Models pillar) | models/glm-5-2/modelserver/gpu/sglang (DisaggregatedSet, DEP8, Rust frontend; L2/L3 tiers merged in #2924, tuning in #2997) | a Models-pillar guide for SGLang on tpu7x: DisaggregatedSet with DP attention + EP and one listener per DP rank. Prerequisite: the SGLang Rust HTTP server (SGLANG_RUST_SERVER=1, #2899) validated on TPU, which has not been exercised there yet. Multi-host precedent now on main: models/kimi-k3-1 (#3021, merged 2026-11-05) serves Kimi-K3.1-Pro with SGLang on tpu7x as a LeaderWorkerSet of 4 pods per 2x2x4 slice (TP=32 x EP=8, aggregated, HiCache host tier over raiden, Python server); engine tuning follow-up in #3037 | โฌ prerequisite: the Rust server validated on TPU |
| 8 | all | Nightly lanes | optimized-baseline, pd-disaggregation, tiered-prefix-cache GKE SGLang lanes | the same three for TPU SGLang: optimized-baseline (v5p, from #2890) green every night 2026-10-28 to 11-10; tiered-prefix-cache (v5p, nightly-e2e-tiered-prefix-cache-gke-cpu-tpu-sglang-native.yaml, 16:00 UTC, from #2915 + #3004) green every night since 2026-11-03; on 2026-11-11 both failed in llm-d-infra's Ensure Nightly Build Image step together with every GKE SGLang lane that day, not in the overlays; pd-disaggregation lane waits for tpu7x capacity in llm-d-infra - the reusable nightly workflow currently skips every tpu/v7 run ("TPU v7 capacity is currently not available"), and the P/D overlay's raiden transport is validated on v7x/v6e only, so it is not ported to v5p | ๐ง 2 of 3 |
CI note: llm-d's TPU nightlies run on v5p Spot today and llm-d-infra skips every tpu/v7 lane until tpu7x capacity exists, so validated for SGLang on TPU currently means a v5p lane, while the recipes are developed and hand-validated on tpu7x.
precise-prefix-cache-routing and predicted-latency-routing SGLang TPU overlays: router-side guides that reuse the baseline overlay; added as small follow-ups, tracked in the guides' support tables. A first precise-prefix-cache-routing attempt (#2980, closed 2026-11-04 for rework) found that --kv-events-config crashes on v0.1.0-tpu because the image lacks libssl-dev for the HiCache hash extension; the Dockerfile fix shipped with sgl-project/sglang-torchtpu#1610, so it also waits for the next release image.tpu/v7 fs overlay uses it through TPURaidenOffloadingConnector); SGLang on TPU gets L3 through the HiCache file backend first.sglang-jax; pod-snapshot, omni-serving and multimodal E/P/D on TPU./cc @achandrasekar @liu-cong @ahg-g for visibility
github-actions[bot] posted a 30-day inactivity reminder on 2026-11-27 warning of auto-unassignment in 14 days without a status comment.What type of PR is this?
/kind feature
What this PR does / why we need it:
Implements Phase 2 of #3229. The EPP retains its most recent scheduling decisions in a fixed-capacity ring buffer and serves them as JSON on /debug/scheduling/recent, on the same metrics/admin server as /debug/plugins/state and subject to the same exposure and authentication controls.
Each decision records the request ID, target model, and one entry per profile run:
The decision carries the picked primary endpoint on success, or the failure reason matching a llm_d_epp_scheduler_failures_total label value on failure. No request payloads or headers are recorded.
The endpoint is disabled by default. --scheduling-decisions-history sets how many decisions are retained (0 disables collection and the endpoint); --scheduling-decisions-top-endpoints (default 5) caps the endpoints recorded per profile. The recorded model string is truncated to 1024 bytes, so retained state is bounded by these values regardless of traffic.
The endpoint is available on the controller-manager path. In file-discovery mode the EPP refuses to start when --scheduling-decisions-history is set, because that metrics server applies no metrics-endpoint authentication.
Design notes:
all_filtered, no_profile_selected, profile_handler_error). Attempts the director rejects before calling Schedule record no decision. A result that Schedule returns together with an error records only the failure reason.[], so failed attempts with no profile runs still parse with jq '.decisions[].profiles[]'.x-llm-d-routing-decision response header) is not implemented here; --emit-endpoint-scores already covers part of that use case via dynamic metadata.Which issue(s) this PR fixes:
Part of #3229
Release note _(write NONE if no user-facing change)_:
Added a `/debug/scheduling/recent` endpoint on the EPP metrics/admin server that serves the most recent scheduling decisions: per-filter candidate counts, per-scorer weights, per-endpoint scores for the top endpoints, the picked endpoints, and the failure reason for failed attempts. The endpoint is disabled by default; enable it with `--scheduling-decisions-history` (number of decisions retained) and cap the endpoints recorded per profile with `--scheduling-decisions-top-endpoints`. The endpoint is not available in file-discovery mode, where setting `--scheduling-decisions-history` stops startup with an error.
Test plan:
Scheduler.Schedule on success (filter counts, scorer weight, per-endpoint scorer scores, picked target)all_filtered failure reason, draining filter stage, profile error)--scheduling-decisions-history is setmake presubmit: every step passes except verify-review-playbook, which fails identically on the base commit 647ca7callm_d_epp_scheduler_attempts_total{status="success"}; a director rejection with no endpoints records no decision; the payload contains no null arraysall_filtered decision with no target endpoint, decode-filter going from 2 candidates to 0, and the profile error; llm_d_epp_scheduler_failures_total{reason="all_filtered"} matchesdocker run: the EPP exits with an error when the flag is set and starts without itAdds an opt-in in-memory ring buffer (decisionhistory.Recorder) and GET /debug/scheduling/recent endpoint on the controller-manager metrics/admin server to inspect recent scheduling decisions, including per-filter candidate counts, per-scorer weights, top-K endpoint raw/weighted scores, picked endpoints, and failure reasons. When --scheduling-decisions-history is 0 (default), no collector is allocated and scheduling runs without time.Now() or mutex overhead; file-discovery mode refuses startup when the flag is set because its standalone metrics server has no authentication filter.
--scheduling-decisions-history (default 0) and --scheduling-decisions-top-endpoints (default 5). Controller-manager mode creates decisionhistory.Recorder, attaches it to Scheduler via WithDecisionRecorder, and registers /debug/scheduling/recent via SetupSchedulingDecisionsDebugHandler; file-discovery mode fails startup at runner.go:1396.Schedule calls Begin(requestID, targetModel) (returning nil when disabled), attaches *Collector via ContextWithCollector, and commits in defer (clearing targetEndpoint whenever err != nil). runSchedulerProfile, runFilterPlugins, runScorerPlugins, and runPickerPlugin each look up CollectorFromContext once per stage and record filter counts, raw scores, and top-K endpoints.Recorder stores up to capacity immutable Decision values under sync.Mutex, truncates Model to 1024 UTF-8 bytes, drops NaN/Inf raw scores and clamps non-finite weighted scores to 0, and initializes slices to [] so JSON never emits null arrays.--scheduling-decisions-history=100 --scheduling-decisions-top-endpoints=5.req-1 for my-model enters Scheduler.Schedule: Begin allocates a *Collector, decode-filter narrows 12 endpoints to 4 (FilterRan), kv-cache-utilization-scorer scores the 4 pods (ScorerRan), and Picked retains the top 4 entries and selected default/pod1, then Commit writes the Decision into the ring.GET /debug/scheduling/recent on the authenticated metrics port and receives JSON with decisions[0] showing candidatesBeforeFilters: 12, filter drop 12 -> 4, topEndpoints with weightedScore and per-scorer raw scorerScores, and targetEndpoint: "default/pod1".scheduling_debug.md, scheduling_decisions_debug.go:63; not yet resolved.decisionhistory.go:112, scheduler_profile.go:274, options.go:507 - [low] NewRecorder panics in make([]Decision, capacity) when capacity is negative, whereas topK < 1 is clamped and zero...samplePercent, samplePercentByFairnessID), buffers up to 64 MiB in an async drop-on-full queue, and exports correlated prompt/completion pairs to an ingest endpoint. Code inspection on origin/main shows fwkrc.Response (pkg/epp/framework/interface/requestcontrol/types.go) currently carries no response body bytes (streaming chunks are forwarded directly in StreamingServer.HandleResponseBody / Director.HandleResponseBody with only Usage/StreamedEvents parsed), fwksched.InferenceRequest (pkg/epp/framework/interface/scheduling/types.go) carries parsed Body rather than raw bytes (Request.RawBody lives on handlers.RequestContext and is overwritten on Director.repackage), RequestHeaderProcessor runs inside Director.HandleRequest after body buffering and modelRewriteIfNeeded (and before AgentIdentityKey fallback/admission), and requests with SkipResponseProcessing close the ext_proc stream before any response hook runs.We want to sample a small fraction of live inference traffic at the router and export correlated request/response pairs to an ingest endpoint, to build a supervised fine-tuning corpus from production traffic. Not RL โ no reward signal, no policy update; just harvesting (prompt, completion) pairs.
The reason we looked at the EPP is that it already carries the identity we want to sample by. Our per-client sampling key is the fairness ID โ the same identity that already drives the router's per-client metrics, flow-control queueing and rate limits โ so the sampling policy is expressed in the router's own vocabulary:
`samplePercent: 1
samplePercentByFairnessID: { <client>: 50 }`
and the exported record is keyed by it. That is the whole proposal: a small, opt-in, per-client-controlled sample with no new component in the request path.
A plugin at existing extension points โ no new ones needed:
RequestHeader โ captures the request line before the EPP rewrites the path for a peer, so the recorded path is the one the client used and the ingest stores it under the right partition.PreRequest / ResponseBody โ decide once, then emit the pair at end of stream.Sampling is deterministic on a hash of the request ID, so a percentage is stable across replicas. The export queue is bounded in bytes (64 MiB default) and drops rather than applying backpressure, so a slow or unreachable sink cannot degrade scheduling.
Status: Alpha, running in one production deployment.
We'd rather solve the concerns raised than argue the placement:
| Option | Our experience |
|---|---|
| Client-side logging | Works, and the client we most want samples from is ours. Doesn't cover clients we don't own, and makes each one an inter-team dependency. |
| vLLM request/response logging | Engine-side. We lose the frontier's view, and we can't filter by fairness ID โ vLLM's labels are fixed, so there is no client-derived dimension to sample on. |
| Envoy tap filter | Needs an Envoy. Our model ingress has none: GKE Gateway โ agentgateway โ EPP โ peer hop. |
| LiteLLM / Langfuse | A new proxy or dependency we'd have to run and own โ another hop in the request path. |
response body"?
@ScraperNerd18 offered to open an upstream PR from an alpha production implementation and asked whether this belongs in upstream EPP and whether the response-body hook should be narrower. @elevran pushed back on adding payload capture to the router due to security/privacy, scale, and performance concerns and out-of-tree scope, pointing to client logging, gateway/mesh tapping (Envoy, GKE policies, Istio/Linkerd, LiteLLM), a custom ext_proc wrapping llm-d-router, or agentgateway's native custom webhook guardrail, and cc'd @ahg-g, @liu-cong, and @vMaroon.Hi, I'd like to request membership in the llm-d GitHub org.
GitHub username: archlitchi
I contribute hardware-support guides for accelerators in mainland China that are not covered by the default NVIDIA path, including Iluvatar, Biren, Enflame, Mthreads, and Hygon.
You can see my name listed as maintainer in every hardware support i anticipated(https://github.com/llm-d/llm-d/blob/main/docs/getting-started/accelerators.md#support)
@chcost @robertgshaw2-redhat @ahg-g @davidgs
My llm-d contributions so far:
PRs
Co-authored
Issues
Reviews
Thank you!
dp_rank -> engine_id map per prefill host:port in getMooncakeEngineMap. Nothing evicts an entry, and vLLM mints a new engine_id at every start (Fixes #4072).What type of PR is this?
/kind bug
What this PR does / why we need it:
The Mooncake P/D sidecar caches the prefill's dp_rank -> engine_id map per prefill host:port in getMooncakeEngineMap. Nothing evicts an entry, and vLLM mints a new engine_id at every start. A prefill container that restarts in place keeps its address, so the sidecar keeps putting the dead remote_engine_id into kv_transfer_params: prefill answers 200, decode's KV pull never completes, and every later request hangs until the sidecar is restarted. #4072 records this on vLLM 0.31.0 with a reproduced in-package test.
This PR drops the cached map when a request through that prefill fails, so the next request re-queries /query and uses the current engine_id. Both Mooncake handlers โ handleMooncake and the vLLM gRPC handleMooncakeVLLMGRPC โ wrap the client writer in captureResponseStatus and remove the entry, deferred, when the response is evidence the engine is gone: it answered nothing, answered with a 5xx, answered with a server-side grpc-status on a 200, or its answer could not be delivered to the client. A 4xx or a client-side gRPC status is not evidence โ a malformed request, a rate limit or a load-shedding rejection leaves the map valid, and evicting on one makes every rejected request pay a bootstrap /query during the overload that produced it. A streamed request that the client abandoned without receiving a single body byte also evicts: its headers are already committed as a 200, so a KV pull that never completes otherwise leaves no trace in the response.
The check sits on the response rather than on the prefill leg because the decoder proxy's error handler relays a prefill failure onto the same writer it wraps, so one check covers a failed prefill and a failed decode alike. It also covers the reported path, where prefill succeeds and decode is what fails.
Scope: the cache is dropped only after a request through the stale engine finishes, so that request โ and every request already in flight against the same prefill โ still fails as before, for as long as its own timeout allows (#4072 saw minutes). A TTL or a background refresh would shorten that window and is deliberately out of scope here; recovery costs one re-query after the request that failed.
Which issue(s) this PR fixes:
Fixes #4072
Special notes for your reviewer:
handleMooncake lines and #4011 touches this file plus the sidecar's gRPC path. This change is independent of both; land it before them where possible, and the conflict in handleMooncake is mechanical.connector_mooncake_test.go drive the production decoder proxy. The two eviction tests fail on 876c4dd2; TestMooncakeEngineMapKeptAfterClientError fails on the previous head of this branch.Release note _(write NONE if no user-facing change)_:
Mooncake P/D sidecar recovers from a prefill restart: after a request to a restarted prefill fails, the cached engine_id is dropped and later requests re-query it. This covers HTTP and vLLM gRPC requests, and a streamed request the client abandoned without receiving a byte (its 200 headers are already committed, so a stalled KV pull leaves no error status). Requests already in flight against the stale engine still fail until they time out.Fixes #4072 where an in-place vLLM prefill restart keeps s.mooncakeEngineIDs populated with a stale engine_id across both HTTP and vLLM gRPC Mooncake requests. handleMooncake (https://github.com/llm-d/llm-d-router/blob/7ca2d2ad68dfe89b8159460af37a82dcd5afa37f/pkg/sidecar/proxy/connector_mooncake.go#L106-L109) and handleMooncakeVLLMGRPC (https://github.com/llm-d/llm-d-router/blob/7ca2d2ad68dfe89b8159460af37a82dcd5afa37f/pkg/sidecar/proxy/vllm_grpc.go#L678-L680) now share trackMooncakeEngineMap, wrapping the response writer and removing prefillPodHostPort from s.mooncakeEngineIDs when upstreamFailed() or abandoned(ctx) holds. Non-5xx HTTP and client-side gRPC statuses remain cached, and in-flight requests are unaffected until they finish.
trackMooncakeEngineMap (pkg/sidecar/proxy/connector_mooncake.go:131-140) wraps w with captureResponseStatus(w) and returns a deferred cleanup function invoked by both handleMooncake and handleMooncakeVLLMGRPC.(*responseStatus).upstreamFailed() (pkg/sidecar/proxy/status_response_writer.go:185-191) returns true for statusCode == 0, statusCode >= 500, writeFailed, or grpcframe.HTTPStatus(status) >= 500 on a 200, keeping 4xx and client-side gRPC errors (InvalidArgument, ResourceExhausted, Canceled) cached.captureResponseStatus tracks bytesWritten (pkg/sidecar/proxy/status_response_writer.go:99,110), and (*responseStatus).abandoned(ctx) (pkg/sidecar/proxy/status_response_writer.go:199-201) evicts when ctx.Err() != nil && statusCode == 200 && bytesWritten == 0 && !writeFailed, so stalled SSE/gRPC streams canceled before first byte also drop the stale map.pkg/sidecar/proxy/connector_mooncake_test.go:449-645 tests decode 502 eviction, 429 retention, non-streaming/streaming prefill 503 eviction, gRPC status classification, and zero-byte vs post-data abandoned streams; pkg/sidecar/proxy/vllm_grpc_test.go:1949-1950 asserts cache eviction after a gRPC Mooncake prefill failure.prefillHost and mints engine-v2, while s.mooncakeEngineIDs still holds engine-v1.engine-v1; decode either fails (502 or grpc-status: 13) or sends 200 headers and stalls until the client cancels with 0 body bytes.trackMooncakeEngineMap observes upstreamFailed() or abandoned(ctx) and calls s.mooncakeEngineIDs.Remove(prefillHost).s.mooncakeEngineIDs in getMooncakeEngineMap (pkg/sidecar/proxy/connector_mooncake.go:197-203), queries /query, and caches engine-v2.connector_mooncake.go, connector_mooncake_test.go; not yet resolved.status_response_writer.go:200, vllm_grpc_test.go:1949, connector_mooncake.go:134 - [medium] abandoned(ctx) evicts on trailers-only gRPC responses (200 OK with 0 body bytes) whenever ctx.Err() != nil.../kind bug
What this PR does / why we need it:
Thanks @blacksoxx for agreeing on the split. This is the first step of #2881: a saturated sentinel and a 429.
With failOpen: false, when the concurrency-detector filter removes the last candidate, the request gets the same 503 rejected-no-endpoints as an empty pool.
fwksched.SaturationFilter marker and the fwksched.ErrSaturated sentinel. The concurrency detector implements the marker.SchedulerProfile.Run: when a saturation filter removed the last candidates, the error wraps ErrSaturated and an errcommon.Error (429, rejected-saturated). Every other drain, and an empty candidate list, keeps the 503.Validation: controlled unit tests set the detector's load directly (requests, tokens and hybrid modes), and a director test mocks admission and the filter. On base df4ecfe1 the saturation cases return 503. go test -race on the touched packages and make presubmit ran clean, except verify-review-playbook, which fails the same way on main on two files this PR does not touch.
Limitation: if a tolerated non-saturation failure (an optional encode profile, for example) happens alongside, a saturated required profile still returns 503. The re-queue and the hold follow in later PRs.
Which issue(s) this PR fixes:
Part of #2881
This PR was written in part with the assistance of generative AI. I reviewed and tested every change.
Release note _(write NONE if no user-facing change)_:
With `failOpen: false`, when scheduling fails and every failed profile was drained by the concurrency-detector filter, the request now returns 429 with `x-llm-d-request-dropped-reason: rejected-saturated` instead of 503 `rejected-no-endpoints`.Distinguishes saturation-filter drains from missing-endpoint drains in scheduling so requests rejected for endpoint capacity return HTTP 429 (rejected-saturated) instead of 503 (rejected-no-endpoints). Empty candidate pools, non-saturation filter drains (such as label or health filters), and fail-open detectors continue to behave unchanged.
ErrSaturated and the SaturationFilter marker interface (FiltersSaturatedEndpoints()), implemented by concurrency-detector.runFilterPlugins records drainedBy only when candidates > 0 drops to 0 on that filter; Run returns wrapped ErrSaturated + errcommon.ResourceExhausted (rejected-saturated) when drainedBy implements SaturationFilter, and errcommon.ServiceUnavailable (rejected-no-endpoints) otherwise.Schedule promotes ErrSaturated (429) only when every entry in profileRunErrors wraps ErrSaturated, omitting ErrSaturated entries when any failed profile is non-saturated so errors.As in Director.HandleRequest keeps 503.Director.HandleRequest.PreRequest runs, another request fills the pod (90/100 tokens), so concurrency-detector (failOpen: false) filters out all candidates (candidates = 1 -> 0) and SchedulerProfile.Run returns ErrSaturated wrapping 429 ResourceExhausted (x-llm-d-request-dropped-reason: rejected-saturated).Director.HandleRequest releases the dispatch reservation and returns the unwrapped errcommon.Error, which BuildErrResponse encodes as HTTP 429 instead of 503.plugins.go:74, scheduler.go:172 - [medium] Built-in utilization-filter also drops overloaded endpoints (fallbackOnEmpty: false by default) but does not...lastSeq at the replay start point (Fixes #4844).What type of PR is this?
/kind bug
/area kvcache
/area telemetry
What this PR does / why we need it:
When a sequence gap arrives while replay is in cooldown, the ZMQ subscriber drops the frame and keeps lastSeq at the replay start point. Every later frame in the cooldown computed the gap from that same lastSeq and added it to llm_d_epp_kv_cache_events_missed_total again. For example, with lastSeq at 0, frames 4, 5, 6 and 7 added 3 + 4 + 5 + 6 = 18 missed sequences where only 3 are missing.
The subscriber now counts only the sequences missed after the previous live frame, or after lastSeq when that is later. Frames received during the cooldown are still dropped and counted in llm_d_epp_kv_cache_events_dropped_total{reason="replay_cooldown"}. A new hole that opens during the cooldown is still counted as missed. sequence_gaps_total, the replay start point and indexing are unchanged.
Tests:
| EPP | Replay port | missed_total | sequence_gaps_total | dropped_total{replay_cooldown} | Index keys |
|---|---|---|---|---|---|
| main | closed | 400 | 27 | 27 | 13 |
| this PR | closed | 2 | 27 | 27 | 13 |
| main | vLLM replay socket | 2 | 2 | 0 | 129 |
| this PR | vLLM replay socket | 2 | 2 | 0 | 129 |
Which issue(s) this PR fixes:
Fixes #4844
Release note _(write NONE if no user-facing change)_:
Fix llm_d_epp_kv_cache_events_missed_total adding the same missing KV-event sequence numbers again for every frame received while replay is in cooldown.Fixes double-counting in llm_d_epp_kv_cache_events_missed_total (metrics.EventsMissed) when live ZMQ frames arrive during replay cooldown. Instead of adding seq - z.lastSeq - 1 on every cooldown-dropped frame while z.lastSeq stays pinned at the replay start point, the subscriber computes missed sequences from max(z.lastSeq, prevLiveSeq). EventsSequenceGaps, EventsDropped (replay_cooldown), replay start sequence (z.lastSeq + 1), and block indexing behavior remain unchanged.
prevLiveSeq, hadLiveSeq := z.lastLiveSeq, z.hasLastLiveSeq before updating z.lastLiveSeq in pkg/kvevents/zmq_subscriber.go#L274-L276.countedThrough = max(z.lastSeq, prevLiveSeq) (when hadLiveSeq is true) and increments metrics.EventsMissed by seq - countedThrough - 1 in pkg/kvevents/zmq_subscriber.go#L287-L291.restarted (seq < lastLiveSeq, resetting hasLastLiveSeq) and seq == lastLiveSeq (continue) execute earlier, guaranteeing prevLiveSeq < seq whenever hadLiveSeq is true, while the enclosing seq > z.lastSeq+1 check guarantees z.lastSeq < seq.seq = 0 (lastSeq = 0, lastLiveSeq = 0) while replay cooldown is active.seq = 4 arrives: countedThrough = max(0, 0) = 0, EventsMissed adds 4 - 0 - 1 = 3 (for sequences 1, 2, 3), lastLiveSeq becomes 4, and frame 4 is dropped as replay_cooldown (lastSeq stays 0).seq = 5 arrives: prevLiveSeq = 4, countedThrough = max(0, 4) = 4, EventsMissed adds 5 - 4 - 1 = 0, and frame 5 is dropped.seq = 8 arrives: prevLiveSeq = 5, countedThrough = max(0, 5) = 5, EventsMissed adds 8 - 5 - 1 = 2 (for sequences 6, 7), bringing total EventsMissed to 5.profiles.fallback to disagg-profile-handler so decode-first deployments can keep serving new requests during a temporary pool outage (Fixes #2636).What type of PR is this?
/kind feature
What this PR does / why we need it:
Adds an optional profiles.fallback to disagg-profile-handler so decode-first deployments can keep serving new requests during a temporary pool outage.
Before forwarding, the router tries the fallback profile once when either:
Backup workers handle the full request locally and must be excluded from both normal profiles. Capacity limits and admission behavior still apply. New requests return to normal P/D routing as the pools recover.
Which issue(s) this PR fixes:
Fixes #2636
Release note _(write NONE if no user-facing change)_:
Add optional P/D fallback when Decode or required Prefill cannot be scheduled.
Test plan:
Validation: targeted profile-handler and scheduler tests passed with the race detector; make presubmit passed in a clean worktree containing the same changes. The focused simulator E2E passed (1 spec; 29 unrelated specs skipped). Simulator coverage validates routing only, not real inference-engine or KV-connector capabilities.
Adds an optional profiles.fallback scheduling profile to disagg-profile-handler in decode-first mode so requests route to an aggregated backup worker when the decode profile or a required prefill profile selects no endpoint. Normal P/D requests pay no extra runtime wrapping or endpoint-scoping cost, and PrefixBasedPDDecider re-evaluates conditional-decode cache checks against the chosen fallback endpoint. Unchanged are prefill-first mode, admission/flow-control rejections, and normal encode-unavailable or prefill-declined decode-only paths.
pkg/epp/framework/interface/scheduling/plugins.go:60-63, pkg/epp/config/loader/configloader.go:410-414, pkg/epp/framework/plugins/scheduling/profilehandler/disagg/disagg_profile_handler.go:210-215, 295-328): DisaggProfileHandlerConfigParser rejects blank profiles.fallback, stageOrder != decode-first, or collisions with decode, prefill, encode, or scheduling.DefaultPrefillProfile. Handler implements SchedulingProfileValidator, and buildSchedulerConfig calls ValidateSchedulingProfiles(profiles) to verify profiles.fallback exists.pkg/epp/framework/plugins/scheduling/profilehandler/disagg/disagg_profile_handler.go:454-473, 623-634): pickDecodeFirst triggers profiles.fallback at most once when decodeRes.FirstEndpoint() == nil or prefillRequiredButFailed is true and ctx.Err() == nil, clearing PeerEndpointAttributeKey. ProcessResults emits DisaggPathFallback ("fallback") and returns only h.fallbackProfile in SchedulingResult.ProfileResults so PreRequest strips PrefillEndpointHeader, PrefillDataParallelRankHeader, and EncoderEndpointsHeader.pkg/epp/framework/plugins/scheduling/profilehandler/disagg/prefix_based_pd_decider.go:93-97, 249-263): remotePrefillDecision includes endpointID, so PrefixBasedPDDecider.PreRequest recomputes needsRemotePrefill when PrimaryProfileName switches from an abandoned decode endpoint to the fallback endpoint.decode pods scale to zero while a prefill-decode worker remains Ready in aggregated-fallback.pickDecodeFirst runs decode, which returns nil (503 rejected-no-endpoints).Pick, decodeRes.FirstEndpoint() == nil triggers profiles.fallback (aggregated-fallback) once and clears PeerEndpointAttributeKey.aggregated-fallback selects the prefill-decode pod; ProcessResults records decision_type="fallback" and PreRequest deletes any stale prefill/encode headers so the backup worker runs the request locally.disagg_profile_handler.go:623 - [low] Guard profileResults[h.fallbackProfile] with an outer if h.fallbackProfile != "" check./v1/chat/completions/render? does it emit KV-cache events in a given format? does it expose the metrics a router scorer needs?), but...llm-d guides implicitly assume things about the model-server image they deploy (does it expose /v1/chat/completions/render? does it emit KV-cache events in a given format? does it expose the metrics a router scorer needs?), but nothing declares or checks those assumptions. A deployment can be fully Ready and serving HTTP 200s while the feature it was built around is silently inert โ #2439 is a concrete instance of this failure class.
This PR is PR 0: it proposes a capability vocabulary and a runtime-probe contract shape so guides can declare required model-server capabilities and a verifier can check them against a running deployment, rather than trusting a version pin. It defines scope and ownership boundaries only โ no implementation code. See the proposal for the suggested follow-on PR sequence (PR 1: a single capability against a single engine, fixture-tested).
It is deliberately scoped to compose with, not duplicate, the cluster-preflight effort in #2429, and proposes sharing that effort's planned requirements: block in guide.yaml (requirements.cluster / requirements.modelServer) rather than adding a second per-guide metadata file.
model-server-capability-contract.md:75, model-server-capability-contract.md:100 - [medium] Declaring api.render.chat-completions as an unconditional requirements.modelServer capability conflicts with how...MONITORING environment variable to false, so the router does not create a ServiceMonitor.A follow-up to PR #2771
The monitoring stack is optional and must be installed separately. The multitenant guide defaults the MONITORING environment variable to false, so the router does not create a ServiceMonitor. Deployment without Prometheus Operator CRDs is therefore supported.
However, the original cleanup unconditionally deletes optional monitoring objects without distinguishing between two cases:
--ignore-not-found does not ignore this error.--ignore-not-found should handle the missing object.As a result, on a cluster without monitoring CRDs, the generated cleanup script exits early because of set -e.
Guards multitenant guide cleanup against missing Prometheus Operator and Google Managed Prometheus (GMP) CRDs by querying only the target group-version discovery endpoint before running kubectl delete. This prevents set -euo pipefail teardown scripts from aborting when optional monitoring CRDs are absent, while keeping --ignore-not-found active for missing resource instances. Core apps/v1 gmp-frontend cleanup and all deploy/verify steps remain unchanged.
GET /apis/monitoring.coreos.com/v1 for "name":"podmonitors" (guides/batch-serving/asynchronous-processing/multitenant/guide.yaml:176) and GET /apis/monitoring.googleapis.com/v1 for "name":"podmonitorings" (guide.yaml:183) via kubectl get --raw without requiring jq or cluster-scoped get crd RBAC.grep stdout to /dev/null instead of using grep -q so kubectl get --raw is drained and does not receive SIGPIPE (exit 141) under bash -euo pipefail when a large discovery list is matched early.apps/v1 manifests/gmp-frontend.yaml deletion from conditional manifests/gmp-podmonitoring.yaml deletion in the Pub/Sub cleanup block (guide.yaml:182-185) and mirrors both blocks in guides/batch-serving/asynchronous-processing/multitenant/README.md:919-936.scripts/tests/test_nightly_deploy_async_multitenant.py:231-344 to assert jq, kubectl get crd, kubectl api-resources, and /apis are not invoked while testing 7 discovery/deletion states with >pipe-buffer discovery output.MONITORING=false and no Prometheus Operator CRDs installed.kubectl get --raw /apis/monitoring.coreos.com/v1 2>/dev/null returns 404 (exit 1), grep '"name":"podmonitors"' >/dev/null exits 1, and the if branch skips kubectl delete -n ${NAMESPACE} -k ${MT}/manifests/monitoring --ignore-not-found without tripping set -e."name":"podmonitors" present in a multi-resource discovery response), grep drains the full JSON stream to /dev/null, exits 0 without SIGPIPE, and runs kubectl delete ... --ignore-not-found.guide.yaml; not yet resolved./test-nightly async-multitenant-gke-acc-gpu-vllm-x/test-nightly async-multitenant-holdback-gke-acc-gpu-vllm-xdocs/architecture/disaggregation/pd-disaggregation.md advises tuning the xPyD ratio to ensure balance for given ISL/OSL workloads, but sizing has remained a manual tuning exercise because only prefill throughput... (Fixes #2836)docs/architecture/disaggregation/pd-disaggregation.md advises tuning the xPyD ratio to ensure balance for given ISL/OSL workloads, but sizing has remained a manual tuning exercise because only prefill throughput (peakPrefillThroughput / $V_P$) had a calibration recipe (calibrate.sh).
As published in literature (DistServe OSDI '24, Splitwise ISCA '24, NVIDIA Dynamo SLA planner), the sizing rule is rate matching:
89888\text{P:D} = (ISL / V_P) : (OSL / V_D)89888
This PR adds the decode counterpart to measure peakDecodeThroughput ($V_D$) and size P:D ratios:
guides/recipes/router/calibration/calibration-peak-decode.yaml:Kubernetes Job + ConfigMap running calibrate_decode.py (Python stdlib). Sends open-loop decode-bound load across a concurrency ladder, measures inter-token latency (TPOT) of streamed tokens, selects the peak throughput meeting the p90 TPOT target, and calculates $V_D = \text{max(throughput)} / \text{DECODE\_REPLICAS}$. When PEAK_PREFILL_THROUGHPUT is set, it computes and emits the rate-matched P:D ratio.
guides/recipes/router/calibration/calibrate-decode.sh:Orchestration script that discovers endpoints, renders and executes the calibration Job, waits for completion, and reports $V_D$ and sizing recommendations.
scripts/tests/test_decode_calibration.py:Test suite covering streaming parsing, synthetic error handling, empty stream handling, SLO compliance, and P:D ratio calculations.
guides/recipes/router/calibration/README.md & docs/architecture/disaggregation/pd-disaggregation.md:Document the rate-matching formula and decode calibration recipe.
Fixes #2836
pytest scripts/tests/test_decode_calibration.py passes 5/5 test cases.pytest scripts/tests/test_prefill_calibration.py passes 4/4 test cases.shellcheck: 0 errors/warnings.python scripts/guide.py check-manifest: OK.Adds the peakDecodeThroughput calibration recipe (Job, Bash orchestrator, and test suite) to measure decode throughput within a target p90 TPOT SLO and calculate rate-matched P:D replica ratios.
calibration-peak-decode.yaml, calibration-peak-decode.yaml; not yet resolved./test-nightly predicted-latency-routing-*calibrate-decode.sh:117, calibration-peak-decode.yaml:176 - [medium] Under set -eo pipefail, empty throughput output from a failing calibration job aborts the script at grep before...This is a routing-side mitigation for #2346, not a replacement for pool-wide flow-control admission.
Agentic sessions start with a long, cold prefill. While one endpoint is paying that cost, warm follow-up turns queue behind it and lose the benefit of their cached prefix.
The new cold-session-filter reads SessionState from session-state-producer and treats a request as cold when:
TurnsTaken == 0, andCold requests are routed only to candidates whose in-flight cold-prefill count is below maxConcurrentColdPrefills. If every candidate is at the limit, the filter fails open and returns all candidates, so it cannot starve a cold session by itself. A TTL releases tracked requests whose response never reaches end-of-stream.
It composes with turn-priority or any other fairness policy; it does not queue or reject requests when the whole pool is busy.
plugins:
- type: session-state-producer
- type: agent-identity
- type: cold-session-filter
parameters:
profileName: prefill
maxConcurrentColdPrefills: 1
requestTtlSeconds: 600
schedulingProfiles:
- name: prefill
plugins:
- pluginRef: cold-session-filter
The filter is a no-op when no SessionState is present, so it is safe to add to pools that do not carry session headers.
go test ./pkg/epp/framework/plugins/scheduling/filter/coldsessiongo test ./cmd/epp/runnergofmt, go vetThis adds the endpoint-placement guard. The issue's full ask โ queueing or capping new sessions at the flow-control layer โ is not implemented here; the README says so explicitly.
Part of #2346.
Adds cold-session-filter scheduling filter to prevent new agentic sessions (TurnsTaken == 0) from piling onto prefill endpoints already running cold prefills up to maxConcurrentColdPrefills.
ColdSessionFilter implements scheduling.Filter, PreRequest, and ResponseBodyProcessor. It checks session-state-producer data for TurnsTaken == 0 and InFlightRequests == 0. When an endpoint reaches maxConcurrentColdPrefills, cold sessions are routed elsewhere, failing open if all endpoints are busy.
When endpoint A already has 1 cold prefill in flight, subsequent cold sessions are routed to endpoint B. If both A and B are busy, the filter returns both to avoid request starvation.
coldsession.go:206, coldsession.go:156, coldsession.go:110 - [high] In-flight cold prefill counters leak permanently (up to the 10-minute TTL) when requests abort, time out, or encounter...What type of PR is this?
/kind feature
What this PR does / why we need it:
During a Prefill/Decode rollout, a Prefill-only overflow check can keep a revision whose Decode endpoints are saturated, or overflow into one. A fail-closed Decode profile then has no endpoints and the EPP returns HTTP 503 even when another revision has capacity for both roles.
Allow revisionGating.overflow.guards to specify role/guard pairs. A revision is eligible only when every configured guard admits at least one endpoint of its role. Preserve the legacy guardPluginName/role form, weighted and affinity-based selection, strict revision headers, shared coordination decisions, and the all-full fallback. Validate list configuration and expose guard references through the existing plugin dependency mechanism.
Declare delegated guards' required and optional data dependencies on the Screener so early eligibility checks can read their inputs through the request-control data scope. Guard data production runs before screening. Guards must support repeated early evaluation without admission side effects. Eligibility checks observe capacity; they do not reserve it atomically.
Validation:
Local Linux/arm64 builder validation passed: make presubmit (invoked with GNU Make as gmake presubmit), focused runner/loader/Screener regressions, and race tests covering those packages plus concurrency filters, disaggregation profiles, and request control. Tests exercised the reviewed Go source in commit 75521655f3321392e50f5bab4ec31ac95147cd18; the second commit only corrects the README's rejection status. Presubmit and focused regressions also passed with that README correction present.
-race: both configuration forms, concurrency 1/8/32/64, three trials per point, and asymmetric Decode saturation, strict v1/v2, and pre-established shared coordination decisions. This covered 2,520 burst requests plus 24 coordination seeds, routing-pair consistency, selection/overflow metrics, and in-flight counter cleanup.In the asymmetric case at concurrency 1, the legacy form accepted 0/3 requests and the multi-role form accepted 3/3 on the revision with both roles free. Held streams filled that revision; subsequent requests could legitimately receive 503. Some concurrent trials admitted two requests to nominal capacity one in both paths, consistent with capacity observation without atomic reservation.
Sequential overflowRevision microbenchmarks with real concurrency filters (GOMAXPROCS=4, three 300 ms repetitions; median microseconds/op):
| Endpoints | Path | Single guard | Two guards |
|---|---|---|---|
| 8 | Keep revision | 0.394 | 0.579 |
| 8 | Overflow | 1.071 | 1.143 |
| 128 | Keep revision | 6.640 | 8.961 |
| 128 | Overflow | 12.976 | 15.320 |
The extra role adds one Filter call per measured path, 112 B/5 allocations at 8 endpoints and 2,032 B/39 allocations at 128 endpoints. These measurements exclude full screening, data production, coordination, gRPC, queueing, and backend service; they do not establish production latency or performance acceptability. Runtime/performance harnesses were local overlays and are outside the eight-file PR diff.
Limitations and maintainer questions:
Validation used simulated backend responses. No live Gateway/Prefill/Decode deployment, routing sidecar, GPU KV transfer, cross-replica coordination, production traffic, or endurance validation was run. Shared decisions were seeded before concurrent requests; cross-replica creation races were not modeled.
Which issue(s) this PR fixes:
Fixes #3755
Release note _(write NONE if no user-facing change)_:
The disaggregatedset-rollout-screener accepts revisionGating.overflow.guards to check capacity across multiple roles before choosing an overflow revision. Existing single-guard configuration remains supported, and delegated guard data dependencies are available during screening.Extends disaggregatedset-rollout-screener with revisionGating.overflow.guards to check capacity across multiple disaggregated roles (such as prefill and decode) before keeping or selecting an overflow revision. A candidate revision has room only when every configured guard admits at least one endpoint of its role. Existing single-guard configuration (guardPluginName and role), strict revision headers, shared coordination decisions, and weighted or affinity selection policies remain unchanged.
RevisionOverflowGuard (role, guardPluginName) and RevisionOverflow.UnmarshalJSON, tracking legacy key presence to reject mixed forms, null lists, empty lists, duplicate roles, and roles outside requiredRoles.DependencyParser, which projects all configured guard names onto []string tagged pluginRef:"" so buildPluginDAG instantiates every guard before the Screener.Consumes() across all overflowGuards via rendezvous.MergeGuardConsumes so guard producers (such as inflight-load-producer) run in DataProducerPhaseRequestHandling before screening.overflowRevisionOf groups all in-scope endpoints by revision, and hasRoom requires every guard to admit at least one endpoint matching guard.role.v1 and v2, configured with guards: [{role: prefill, guardPluginName: p}, {role: decode, guardPluginName: d}].v1, whose prefill endpoints are idle (0) while decode endpoints are at saturation (12).hasRoom for v1 passes p on v1 prefill endpoints, then runs d on v1 decode endpoints, which filters all of them out and returns false.overflowRevision evaluates v2 (both roles free), hasRoom returns true, and the request overflows to v2.overflow.go:92 - [low] Sizing capacity for candidates up front in hasRoom avoids slice growth reallocations on the screening hot path.length-adaptive-load-scorer scheduling plugin (pkg/epp/framework/plugins/scheduling/scorer/lengthadaptiveload), which scores candidate endpoints by dynamically interpolating between request-concurrency headroom... (Fixes #3880)What type of PR is this?
/kind feature
What this PR does / why we need it:
Adds the length-adaptive-load-scorer scheduling plugin (pkg/epp/framework/plugins/scheduling/scorer/lengthadaptiveload), which scores candidate endpoints by dynamically interpolating between request-concurrency headroom ($S_{\text{queue}}$) and in-flight KV token headroom ($S_{\text{token}}$) based on the incoming request's prompt token length $L_r$:
$\alpha(L_r) = \text{clip}\!\left(\frac{L_r - \text{shortThresholdTokens}}{\text{longThresholdTokens} - \text{shortThresholdTokens}},\, 0.0,\, 1.0\right)$
$S_{\text{raw}}(w, r) = \bigl(1 - \alpha(L_r)\bigr) \cdot S_{\text{queue}}(w) + \alpha(L_r) \cdot S_{\text{token}}(w)$
512): Routed by active request count ($\alpha = 0$) to fill idle decode batch slots.16384): Routed by in-flight KV token load ($\alpha = 1$) to avoid stacking long-context KV caches on the same decode pod.0.0 (falling back to $S_{\text{raw}}$ if all endpoints exceed the guardrail simultaneously).llm-d.ai/max-num-seqs and llm-d.ai/max-kv-tokens by default, configurable via maxConcurrencyLabel and maxTokenCapacityLabel) first for heterogeneous accelerator pools (#3791), and falls back to plugin parameters (maxConcurrency, default 256, and maxTokenCapacity, default 150000).TestFactory)TestLengthAdaptiveLoadScorer_2PodDeepInferScenario)TestLengthAdaptiveLoadScorer_EdgeCases)TestLengthAdaptiveLoadScorer_ScopeInvocation)StartOfStream and EndOfStream (TestLengthAdaptiveLoadScorer_DecodeLifecycleRetainsTokensUntilEndOfStream)TestLengthAdaptiveLoadScorer_HeterogeneousPerPodCapacityLabels)Which issue(s) this PR fixes:
Fixes #3880
Release note _(write NONE if no user-facing change)_:
Added `length-adaptive-load-scorer` scheduling plugin that dynamically blends request-concurrency scoring and KV token-load scoring based on request prompt length, with two-tier per-endpoint capacity guardrails.length_adaptive_load.go:206, length_adaptive_load.go:466, runner.go:750 - [high] Scorer implements request lifecycle hooks and shadow token tracking instead of fixing InFlightLoadProducer.What type of PR is this?
/kind feature
What this PR does / why we need it:
The problem. In prefill/decode (P/D) disaggregation, one GPU reads the prompt (prefill) and hands its memory (the KV cache) to another GPU that writes the answer (decode). vLLM only accepts this handoff when both sides are set up the same way: same vLLM build, model, data types, KV layout and attention backend. vLLM checks this with a compatibility hash during the NIXL handshake. Two GPU generations can fail this check even when they serve the same model, for example when one card picks a different attention backend. When that happens, the decode GPU rejects the memory and the request fails. Today the router cannot tell which prefill GPUs are safe for a given decode GPU, so it keeps sending requests into these failures.
What this PR adds. Two Alpha plugins that read a compatibility key on each pod (label llm-d.ai/kv-compat-key). The key is set by whatever deploys or labels the model servers.
kv-compat-pd-decider wraps any existing prefill decider, for example prefix-based-pd-decider. It asks one question first: does this decode GPU have at least one prefill GPU it can safely take memory from? If not, the request is served on the decode GPU alone, so it gets answered instead of failing. If yes, it returns the wrapped decider's answer unchanged.kv-compat-filter goes in the prefill profile. It removes the prefill GPUs that the chosen decode GPU cannot take memory from.When two pods count as compatible:
approvedPairs setting ("prefillKey->decodeKey", one direction only) or by a label on the decode pod: accept.kv-compat.llm-d.ai/<prefillKey>=true.If no pod carries a key, nothing changes: both plugins pass everything through.
Why the check is in the decider and not only in the filter. If the prefill profile ends up with no pod, the request fails. If the decider says no, the request is served decode-only. So the decider must say no when no safe prefill pod exists.
Cost on the request path. The decider keeps a count of prefill pods per key, updated from endpoint events, so a decision reads a few map entries instead of scanning the pool.
Results (details and data in #3791):
| Stock llm-d | With this PR | |
|---|---|---|
| GPU lab (T4 + A10G prefill, L4 decode): long documents that failed, busy system | about 40 of 86 per run | 0 |
| Same lab, idle system | about 73 of 86 per run | 0 |
| Load test (simulated pods, 10% with an incompatible key): requests sent to incompatible pods per minute | 1,400 to 2,300 | 0 |
Chat traffic was unchanged.
Example config:
- type: prefix-based-pd-decider
parameters:
nonCachedTokens: 1024
- type: kv-compat-pd-decider
parameters:
decider: prefix-based-pd-decider
- type: kv-compat-filter
parameters:
decider: kv-compat-pd-decider
- type: disagg-profile-handler
parameters:
deciders:
prefill: kv-compat-pd-decider
# and add `- pluginRef: kv-compat-filter` to the prefill scheduling profile
This is part 1 of 3, as discussed in #3791, and replaces draft #3953:
Which issue(s) this PR fixes:
Part of #3791
Test plan:
make presubmitRelease note _(write NONE if no user-facing change)_:
Add the Alpha kv-compat-pd-decider and kv-compat-filter plugins. They stop P/D disaggregation from pairing a prefill pod with a decode pod whose KV compatibility key differs; such requests are served decode-only instead of failing.kv_compat_test.go:217, kv_compat.go:259; not yet resolved.kv_compat.go:420, kv_compat.go:269, kv_compat.go:448 - [high] Inverted plugin architecture: filter is hard-coupled to decider via concrete pointer assertion instead of consuming typed...pd-disaggregation guide for the overlays that carry their own DisaggregatedSet manifest: gpu/vllm/base (and the cks-mooncake overlay that replaces its sidecar... (Part of #3043)Turns on the llm-d-router sidecar's SSRF allowlist in the pd-disaggregation guide for the overlays that carry their own DisaggregatedSet manifest: gpu/vllm/base (and the cks-mooncake overlay that replaces its sidecar args), gpu/sglang/base, and tpu/v7-dynamic-slice/vllm/base.
Per decode pod:
--enable-ssrf-protection=true on the routing-proxy container. The sidecar then accepts a prefill target only when it is a pod of the InferencePool on a pool target port, and rejects any other value of the prefill header with 403.INFERENCE_POOL=$(POD_NAMESPACE)/pd-disaggregation. The namespace comes from the downward API. The pool name is the router release name, which the README already marks as mandatory for this guide because the pool selector pairs with it.automountServiceAccountToken: false, so the model server still runs without a token.Role and RoleBinding (rbac.yaml) with list and watch on inferencepools and pods, bound to the decode service account. Without the pods permission the allowlist stays empty and every prefill request fails, so the RBAC lands with the flag.The README gets one paragraph that states the behavior and links to the router's SSRF Protection docs.
Part of #3043. The sidecar reads the prefill target from the x-llm-d-prefiller-host-port header. The EPP drops client values of that header, so the gateway path is closed, but any peer that reaches a decode pod's sidecar port directly can still choose the target. The allowlist is the control the router ships for that case, and the published manifests did not enable it.
Only the three standalone pd-disaggregation bases. The overlays that build on guides/recipes/modelserver/base/single-host/pd-disaggregatedset (the other pd-disaggregation accelerators, coord-disaggregation, multimodal-serving, and several models/* guides) share one base across guides whose InferencePool names differ, so they need a per-overlay INFERENCE_POOL patch and are left for a follow-up. wide-ep, p2p-kv-cache-sharing, and the models/* guides with their own manifests are also follow-ups.
kubectl kustomize renders every overlay under gpu/vllm, gpu/sglang, and tpu/v7-dynamic-slice/vllm (aws, coreweave, gke, ocp, cks-mooncake). Each rendered decode pod has the flag, the two env vars, the token mount, the projected volume, and one RoleBinding.python scripts/guide.py render guides/pd-disaggregation/ --check reports the README up to date.8000, which is the pool target port, so the allowlist admits them. The SGLang bootstrap port and the NIXL side channel are not checked by the allowlist, so they are unaffected.Enables SSRF protection for the llm-d-router sidecar in the pd-disaggregation guide across NVIDIA GPU (vLLM and SGLang) and TPU7x dynamic sub-slice overlays, restricting prefill proxying to validated InferencePool pod endpoints while keeping model server containers unprivileged.
The change activates --enable-ssrf-protection=true on the routing-proxy sidecar container in each DisaggregatedSet decode role. To populate the allowlist without granting the model server Kubernetes API access, each decode pod spec adds a projected volume (sidecar-sa-token) mounted read-only strictly inside the sidecar, while keeping automountServiceAccountToken: false on the underlying ServiceAccount. A namespace-scoped Role and RoleBinding provide list and watch permissions on inferencepools and pods, and the sidecar resolves its target pool via INFERENCE_POOL=$(POD_NAMESPACE)/pd-disaggregation.
# Projected token mounted exclusively in the sidecar container
volumeMounts:
- name: sidecar-sa-token
mountPath: /var/run/secrets/kubernetes.io/serviceaccount
readOnly: true
volumes:
- name: sidecar-sa-token
projected:
sources:
- serviceAccountToken:
path: token
expirationSeconds: 3600
- configMap:
name: kube-root-ca.crt
items:
- key: ca.crt
path: ca.crt
- downwardAPI:
items:
- path: namespace
fieldRef:
fieldPath: metadata.namespace/test-nightly pd-disaggregation-cks-acc-gpu-vllm-x/test-nightly pd-disaggregation-gke-acc-gpu-sglang-x/test-nightly pd-disaggregation-gke-acc-gpu-vllm-x/test-nightly pd-disaggregation-ibm-acc-gpu-vllm-xx-llm-d-inference-priority-class and turns it into one admission priority: The same integer is stored on the request and on the request_prio span attribute.What type of PR is this?
/kind feature
What this PR does / why we need it:
RHAISTRAT-2347 / RHOAIENG-99624. The Endpoint Picker reads x-llm-d-inference-priority-class and turns it into one admission priority:
sheddable uses -1. The InferenceObjective object is not edited. With flow control off, a saturated pool rejects that request with the existing HTTP 429. With flow control on, the request waits on the -1 band, which is provisioned at startup and kept on every reconcile.critical, a missing header, and an empty or unrecognized header keep the InferenceObjective priority, including when that priority is already negative.The same integer is stored on the request and on the request_prio span attribute. The span also carries llm_d.epp.priority_class. Metrics on port 9090 are llm_d_epp_requests_total, llm_d_epp_priority_class_shed_total, and llm_d_epp_priority_class_unknown_total. Fairness ids on those series use the existing label cap.
Flow control stays off unless the deployment enables it. The operator doc is docs/optimistic-scheduling.md. It covers the admission rules, the requirement that queued burst needs the flowControl gate, and the saturation polling window.
This pull request does not stamp the header. The requesting layer owns that, and it must overwrite a client-supplied value.
Which issue(s) this PR fixes:
RHOAIENG-99624
Release note:
The Endpoint Picker treats x-llm-d-inference-priority-class sheddable as admission priority -1 and drops that request when the pool is full. Critical, missing, and invalid values keep the InferenceObjective priority.
go test ./pkg/epp/requestcontrol/ ./pkg/epp/controller/ ./pkg/epp/metrics/ ./pkg/epp/flowcontrol/ -count=1 covers parse, admission priority, legacy full-pool and spare-capacity drops, the sheddable band, and unsafe fairness-id labelsdocs/optimistic-scheduling.md and the priority-class section in docs/metrics.mdconsts.go:67, director.go:400, inferenceobjective_reconciler.go:162 - [high] Do we need a hardcoded core header contract for x-llm-d-inference-priority-class instead of using...resumeOnOtherPod to thunder-agent, off by default. Today a paused session only goes back to its own pod, so if that pod stays full it waits up to forceAdmitTimeout even when other pods have room (Part of #3221).What type of PR is this?
/kind feature
What this PR does / why we need it:
Adds resumeOnOtherPod to thunder-agent, off by default. Today a paused session only goes back to its own pod, so if that pod stays full it waits up to forceAdmitTimeout even when other pods have room. With the option on, a paused session that doesn't fit its own pod (even after reclaiming idle sessions there) falls back to findFitPod, and admitLocked rebinds and reserves it on that pod like a new session. Its own pod still wins whenever it fits, and a session that fits no pod keeps waiting for its own.
There is one guard. A second queued turn of the same session, picked before PreRequest charges the first, stays on its pod. Without the guard that turn still looked paused and its own reservation had already used up the pod's room, so it got moved again and the first turn's reservation was lost. Both cases have a test.
Known limits: the move only lands if the thunder-agent scorer decides the pick. If another scorer outweighs it, or the new pod is filtered out, PreRequest rebinds the session to the old pod. A request cancelled before PreRequest leaves the session bound to the new pod, same as a new session today.
This will conflict with #4191 in fairness.go and manager.go. I'll rebase whichever way it lands.
Benchmark (asked for in the issue)
This is a small Go simulation, not an engine or GPU run. It drives the plugin's real Saturation/Pick/Score/PreRequest/ResponseBody hooks in scaled wall-clock time. Completion times come from a synthetic cost: prefill is uncached tokens times a per-token cost, plus 15 ms of decode.
The workload is built so that moving can help. Two pods of 20000 tokens, short sessions that fill pod-b and then finish, long sessions that outgrow pod-a. Each row is 5 seeds x 3 repetitions, and tool delays are fixed per (seed, session, turn) so off and on see the same workload.
Pausing only changes thunder-agent's accounting and doesn't evict anything in vLLM, so I ran two hypothetical cache scenarios. In "lost" the prefix is gone once a session is paused. In "kept" it stays reusable on the session's last pod and only a move recomputes the history, which favors staying. "Shared" compute means a pod prefills one request at a time, so a recompute delays the requests behind it.
| Cache scenario | Compute | Prefill cost (us/token) | Completion ms, off -> on | Change per pair (min / median / max) | Pairs where on was slower | EPP admission wait p99 ms, off -> on |
|---|---|---|---|---|---|---|
| lost | independent | 2 | 2955-3501 -> 1651-2044 | -48% / -44% / -32% | 0 of 15 | 533-798 -> 31-183 |
| kept | independent | 2 | 2711-3267 -> 1716-1944 | -45% / -39% / -34% | 0 of 15 | 596-827 -> 38-133 |
| kept | independent | 8 | 2787-3220 -> 1858-2104 | -42% / -37% / -32% | 0 of 15 | 610-828 -> 75-167 |
| kept | shared | 2 | 2640-3196 -> 1695-2038 | -41% / -38% / -32% | 0 of 15 | 490-856 -> 62-161 |
| kept | shared | 8 | 2964-3335 -> 1912-2222 | -36% / -34% / -30% | 0 of 15 | 609-943 -> 83-210 |
| kept | shared | 40 | 3824-4395 -> 3093-4610 | -20% / -10% / +10% | 2 of 15 | 585-983 -> 68-430 |
| no pressure (10x capacity) | independent | 2 | 1517-1676 -> 1515-1671 | -0% / -0% / +0% | 3 of 15 | 0 -> 0 |
Ranges are min-max over the 15 runs. A pair is the off and on run with the same seed and repetition.
All 210 runs finished every session, and forced admission never fired. At 2 and 8 us/token the option was faster in all 75 pairs. At 40 us/token with shared prefill it is mixed: the median pair is 10% faster, but 2 of 15 were slower (+1% and +10%), and repeats of the same run differ by up to 15% there. In that row some of the wait also moves from the EPP queue to the pod's prefill slot (mean prefill-slot wait goes from 48-50 ms to 62-85 ms). With nothing under pressure the option does nothing.
p99 is per run over 104 turns, so it rests on about 2 values. These are simulated timings under one constructed workload and cost model, so they say nothing about real GPU throughput or latency. If the harness or the per-run numbers would help the review, let me know and I will share them.
Which issue(s) this PR fixes:
Part of #3221 (item 3)
Test plan:
resumeOnOtherPod, default offRelease note _(write NONE if no user-facing change)_:
thunder-agent: add `resumeOnOtherPod` (default false). When enabled, a paused session whose own pod has no room resumes on another pod with room, which recomputes its history.fairness.go; not yet resolved.fairness.go:207, config.go:50 - [high] Committing cross-pod rebinds and target-pod idle-session evictions inside FairnessPolicy.Pick couples admission control...sjf-ordering-policy (Shortest Job First), an Alpha flow control ordering policy that dispatches smaller requests first while bounding how long any request can be passed (Fixes #4872).What type of PR is this?
/kind feature https://github.com/llm-d/llm-d-router/issues/4872
What this PR does / why we need it:
Adds sjf-ordering-policy (Shortest Job First), an Alpha flow control ordering policy that dispatches smaller requests first while bounding how long any request can be passed. Under saturation this lowers mean queue wait compared with FCFS when request size tracks service time.
ByteSize). Each request is ordered by EnqueueTime + maxDelaySeconds * min(ByteSize / referenceBytes, 1), with FCFS breaking ties, so only requests that arrived within maxDelaySeconds after a request can be dispatched ahead of it.maxDelaySeconds defaults to 2 and referenceBytes to 65536. Both must be positive, and maxDelaySeconds must be below the time.Duration overflow.plugins:
- type: sjf-ordering-policy
parameters: # optional; defaults are maxDelaySeconds 2, referenceBytes 65536
maxDelaySeconds: 5
referenceBytes: 131072
- type: round-robin-fairness-policy
flowControl:
priorityBands:
- priority: 100
orderingPolicyRef: sjf-ordering-policy
fairnessPolicyRef: round-robin-fairness-policy
Design notes:
global-strict-fairness-policy (the default), the fairness policy compares flow heads with this policy's Less, so the size order applies across all flows in the band. Under round-robin or weighted-fair-share it applies within each flow. The README recommends a per-flow fairness policy when tenants share a band.Which issue(s) this PR fixes:
Fixes #4872
Release note _(write NONE if no user-facing change)_:
Add the Alpha `sjf-ordering-policy` flow control ordering policy, which dispatches smaller requests first. Optional `maxDelaySeconds` (default 2) and `referenceBytes` (default 65536) bound how long a larger request can be passed.
Test plan:
referenceBytesmaxDelaySeconds bounds passing across flowsmake presubmitAdds sjf-ordering-policy at StabilityAlpha to favor smaller queued requests under flow-control saturation while bounding overtaking by maxDelaySeconds. Each item's priority key is computed deterministically from its enqueue time and request ByteSize, leaving the underlying priorityQueue heap, FlowController, and downstream scheduler untouched.
sjf.go):** SJFOrderingPolicyFactory decodes optional maxDelaySeconds (default 2, 0 collapses to FCFS, upper-bounded below math.MaxInt64/float64(time.Second)) and referenceBytes (default 65536, > 0). SJFPolicy is an immutable, goroutine-safe flyweight singleton.delayedArrival):** Computes EnqueueTime + maxDelaySeconds * min(ByteSize/referenceBytes, 1) on the fly with zero allocations and breaks ties by EnqueueTime. Missing OriginalRequest() maps to math.MaxUint64 (full delay), and nil QueueItemAccessor sorts lowest.runner.go, added to TestOrderingPolicyConformance, and verified end-to-end across single-flow and two-flow global-strict bands in TestDispatchOrderingSJF.sjf-ordering-policy with maxDelaySeconds: 2 and referenceBytes: 1000.t = 0s, a 1000-byte request R1 arrives while the pool is saturated; its delayedArrival is t + 2s.t = 0.5s, a 100-byte request R2 arrives; its delayedArrival is 0.5s + 0.2s = 0.7s (< 2s), so R2 moves ahead of R1 in the heap.R3 (100 bytes) arrives at t = 2.5s (delayedArrival = 2.7s > 2s), R1 dispatches before R3 because R1 has already waited past maxDelaySeconds.README.md:84 - [low] Computational Overhead is listed under ## Workload Fit instead of ## Trade-offs.What type of PR is this?
/kind feature
What this PR does / why we need it:
Part of #3584, the "Coordinator: upstream request duration" row under item 2.
llm_d_coordinator_upstream_request_duration_seconds records how long each outbound call from a coordinator step takes. Its Observe call is replaced with the shared ObserveWithTraceExemplar, so for sampled requests each call duration carries the requestโs trace as an exemplar, and a slow call links to the step that made it.
To get the request context to the recorder:
UpstreamCall.Done and RecordUpstreamRequestDuration now take a ctx, and every step that calls an upstream service passes its own.decode_proxy.go, the timedRoundTripper callback gets the ctx from the outgoing request.The exemplar's span_id is the span of the step that made the call. The metric name, labels and buckets are unchanged.
I also noted in docs/metrics.coord.md that the metric now carries a trace exemplar.
Test plan:
trace_id and span_id.go test -race passes for ./pkg/coordinator/... and ./cmd/coordinator/....make -f Makefile.coord.mk presubmit passes.make presubmit passes except verify-review-playbook, which also fails on main's HEAD because of a file unrelated to this change.Which issue(s) this PR fixes:
Part of #3584
Release note:
The coordinator's llm_d_coordinator_upstream_request_duration_seconds histogram now carries a trace exemplar for sampled requests, so an upstream latency point links to the step span that made the call. Exemplars require an OpenMetrics scrape and exemplar storage in Prometheus.Threads context.Context into coordinator upstream latency recording so llm_d_coordinator_upstream_request_duration_seconds attaches the calling step's OpenTelemetry trace exemplar via metricsutil.ObserveWithTraceExemplar. Metric names, labels, histogram buckets, and upstream_request_total counting behavior remain unchanged.
RecordUpstreamRequestDuration and UpstreamCall.Done take ctx context.Context and delegate to ObserveWithTraceExemplar, matching RecordStepDuration.asyncbroker/broker.go, force_stream.go, grpc_relay.go, render.go, replace_media_urls.go, utils.go) pass their step or derived context into call.Done(ctx) while the pipeline step span is still recording.timedRoundTripper.RoundTrip passes r.Context() from the cloned outgoing request to RecordUpstreamRequestDuration.runStep starts a sampled decode span on ctx and invokes DecodeStep.Execute.serveDecode wraps transport in timedRoundTripper; ReverseProxy.ServeHTTP clones proxyReq with ctx and calls RoundTrip.timedRoundTripper calls RecordUpstreamRequestDuration(r.Context(), UpstreamDecode, d), attaching both trace_id and the decode step's span_id as an exemplar (or omitting exemplars for unsampled/traceless requests while still observing d).What type of PR is this?
/kind feature
What this PR does / why we need it:
A model server can pass ordinary health checks while inference fails or stops producing output. Add an opt-in model-inference-health producer that combines verified business output with bounded inference probes when response activity is absent. It discovers the endpoint's model automatically and reduces probe frequency while requests are in flight.
Publish reusable endpoint health state and two EPP metrics: llm_d_epp_model_inference_up and llm_d_epp_model_inference_probes_total. Unknown or expired results have no up series. Scheduling and Pod readiness remain unchanged.
Validation includes affected-package race tests and local kind checks for idle probing, business-output suppression, in-flight suppression, inference errors, timeouts, and recovery. The kind backend is simulated; real vLLM/GPU faults and full Envoy integration remain unverified.
Known limitation: the existing data-layer auto-registration path does not apply the model source's polling interval. Local kind observed 100 model-list queries in five seconds. Explicitly configuring models-data-source under dataLayer.sources respected the interval (three queries in six seconds with a two-second interval). This needs resolution before relying on automatic source wiring.
The local presubmit review-bundle gate has a baseline failure: forwardtokens/plugin.go has no production routing row. This was also reproduced on a clean upstream archive.
Which issue(s) this PR fixes:
Fixes #4383
Release note _(write NONE if no user-facing change)_:
Add an opt-in model-inference-health plugin that observes business inference output and probes inactive endpoints, exposing inference-health metrics and reusable endpoint state without changing routing or Pod readiness.plugin.go:80, data_types.go:110 - [high] Do we need active synthetic /v1/chat/completions probing in every EPP replica, and should endpoint polling live in...Thanks @larkowl for comparing the same gateway with and without llm-d in the report, which narrowed the buffering to the llm-d route.
What type of PR is this?
/kind bug
What this PR does / why we need it:
A gRPC server-streaming call routed with passthrough-parser reaches the client only after the backend finishes. passthrough.ParseRequest never sets Body.Stream, and at response headers only text/event-stream turns streaming on, so the EPP buffers every chunk until the trailers.
This implements design B from https://github.com/llm-d/llm-d/issues/3089#issuecomment-7039736614, where I asked which design you prefer:
ParseResult gets an OpaqueResponse field, set only by passthrough-parser.text/event-stream responses keep the existing streaming path. Other parsers keep the complete-body contract.Time to first message behind agentgateway v1.7.0 on a CPU kind node (18 messages 80 ms apart, 100 calls at c=1): p50 1454.0 ms on main, 83.2 ms with this PR, 82.5 ms without the EPP. Results up to c=128, fault injection and the design note: https://github.com/llm-d/llm-d-router/pull/4412#issuecomment-7061982969, https://github.com/lkhun9311/gpu-platform-control-plane/blob/0c0633de1ec1d53a84ecb878fb82a2684876d4fb/experiments/llmd-3089-grpc-stream/design-note.md
Design A instead: passthrough-parser sets Body.Stream for gRPC requests. It also fixes the gRPC latency, but HTTP passthrough bodies without text/event-stream stay buffered, and there is no body response for the final metadata before the trailers. If you prefer A, I'll switch this PR to it.
Behavior changes on the opaque path only:
streaming="false".passthrough-parser sets no model name, so the rewrite was a no-op there on main.Testing: unit and integration tests cover per-message forwarding while the backend holds the next message, final metadata before trailers, trailers-only errors, client disconnect, backpressure (at most 3 chunks read ahead), and a 66 MB stream with heap growth under 16 MiB. The forwarding tests fail on main. go test -race passes for ./pkg/epp/handlers/..., ./pkg/epp/framework/plugins/requesthandling/parsers/... and ./pkg/epp/framework/interface/requesthandling/....
Which issue(s) this PR fixes:
Fixes llm-d/llm-d#3089
Release note _(write NONE if no user-facing change)_:
With `passthrough-parser`, the EPP forwards response chunks other than `text/event-stream` as they arrive, so gRPC server-streaming responses reach the client message by message. For these responses TTFT is measured to the first response byte and the model-name rewrite is not applied.Adds an OpaqueResponse flag on ParseResult and sets it in passthrough-parser so StreamingServer forwards non-SSE response chunks immediately without buffering or mutating them, while still observing headers, trailers, tool-calling telemetry, metrics, and DynamicMetadata. Previously, only Body.Stream or text/event-stream bypassed response buffering, causing gRPC server-streaming responses on passthrough-parser to stall until trailers arrived. Existing text/event-stream responses continue on modelServerStreaming, and all other parsers retain their complete-body or streaming contracts unchanged.
ParseResult.OpaqueResponse declares that the parser neither reads nor rewrites response bodies; PassthroughParser.ParseRequest sets OpaqueResponse: true with SkipResponseProcessing: false.reqCtx.modelServerStreaming is false (not text/event-stream) and reqCtx.opaqueResponse is true, Process tracks responseSize, firstTokenTimestamp, and upstream tool-calling detection, forwards each chunk immediately via generateResponseBodyResponses, and invokes HandleResponseBody(ctx, reqCtx, nil, true) once at EndOfStream.ResponseHeaders with EndOfStream, Process uses upstream grpcStatusFromHeaders classification, completes the response, attaches DynamicMetadata to respHeaderResp, and marks toolCallingForwardedComplete on header send. On ResponseTrailers, finishResponse runs HandleResponseBody once with nil, true, emits a BodyResponse carrying DynamicMetadata before TrailersResponse, and sums per-chunk responseProcessingDuration.PassthroughParser.ParseRequest returns OpaqueResponse: true, setting reqCtx.opaqueResponse = true while reqCtx.modelServerStreaming stays false.ResponseHeaders (content-type: application/grpc, EndOfStream: false) pass through without setting modelServerStreaming.message 1 arrives in ResponseBody (EndOfStream: false), Process records firstTokenTimestamp, forwards message 1 immediately to Envoy without waiting for message 2 or calling HandleResponseBody, and repeats for message 2.ResponseTrailers (grpc-status: 0) arrives, finishResponse marks responseComplete = true, runs terminal metrics and Director.HandleResponseBody (populating DynamicMetadata such as request-attribute-reporter cost), emits an empty BodyResponse carrying that DynamicMetadata, and sends TrailersResponse.server.go:1163 - [low] In finishResponse, an opaque gRPC response terminated by ResponseTrailers still calls rewriteModelName and emits an...utilization-detector decides whether an endpoint's KV cache has room from the latest scrape (Fixes #4369).What type of PR is this?
/kind feature
/area flowcontrol
/area epp
/area scheduling
/area datalayer
What this PR does / why we need it:
utilization-detector decides whether an endpoint's KV cache has room from the latest scrape. A running sequence keeps allocating blocks as it decodes, so requests admitted while the reading is low fill the cache later, and the engine preempts them. This PR adds a projection of that growth: inflight-load-producer estimates how much more KV cache each request on an endpoint will take, and the detector counts it as already used. Requests that do not fit wait in the flow-control queue instead of stalling mid-stream.
On four workloads that push vLLM 0.34 past its KV capacity, no stream stalled for more than 5 s with the projection. The default configuration and token accounting left up to 248 requests stalled that long. It is opt-in; without kvGrowthProjection the producer publishes zero and the detector is unchanged. Motivation, alternatives and the prototype runs are in #4369.
plugins:
- type: inflight-load-producer
parameters:
kvGrowthProjection:
maxOutputTokens: 4096
term added to the detector's score: KVCacheUsage + KVGrowthTokens / KVCacheCapacity
KVGrowthTokens = booked + growth
growth = max over t of sum_i [ S_i(t) * (c_i + t) - c_i ] + S_0(t) * (p + t) + z * sd(t)
sd(t)^2 = sum_i S_i(t) * (1 - S_i(t)) * (c_i + t)^2 + S_0(t) * (1 - S_0(t)) * (p + t)^2
In words: for each running request, take what it will hold t tokens from now if it is still running, minus what it holds now, and add the next request. The projection reserves the peak of that total over t, plus z standard deviations.
c_i is what request i holds now: its uncached prompt plus the tokens it has streamed.S_i(t) is the chance it is still running after t more tokens, from the output lengths of recent requests. It is 0 past the request's own max_tokens or maxOutputTokens, whichever is lower.S_0 and p describe the next request, with p the mean prompt length of recent requests.booked is the prompt and streamed tokens the scrape does not show yet.z is 3 by default.The term joins queue depth and KV usage in the detector's maximum, and it reaches 1.0 when scraped usage plus projected growth equals the cache size. Flow control holds requests while the average score across endpoints is at or above the band's usage limit. In its Filter role the detector also drops an endpoint whose term reaches 1.0, unless that would drop every candidate.
Example: before any request has completed there is nothing to learn from, so every running request is reserved its full output up to the 4,096-token cap. On the 171k-token cache that admits about as many sequences as fit at that size: 45 of 192 at the start of the closed-loop runs in #4369. More are admitted as completed requests show that most outputs are shorter.
The estimate takes requests as independent and looks ahead to one admission.
Why these choices:
maxOutputTokens stay in the sample, so a run of short outputs does not erase long ones.t can come before the running requests finish, because those that end free their blocks while others keep growing.Response.StreamedEvents, which inflight-load-producer already reads in ResponseBody.Computing the projection for 76 running requests takes about 22 microseconds on an Apple M5 core. It is recomputed when a request is dispatched to or ends on the endpoint, and otherwise every 100 ms; recording a response chunk takes about 10 ns.
n) of each prompt it carries; n is read from a JSON request body.The capacity ledger in #3110 books the KV blocks each request holds now, and this projection is what those requests will still take. Once the ledger lands it can supply booked through its Memory axis.
Of the added lines, about 600 are code, 1,100 tests and 45 docs. The estimator is inflightload/kv_growth.go (about 400 lines) and depends only on the standard library and the plugin interface package, so it can be read on its own. producer.go, detector.go and data_types.go wire it in.
vLLM 0.34, Qwen3-8B, 171k-token KV cache, flowControl feature gate on, max_tokens: 4096 on every request unless noted.
Does it stop preemption under overload? 480 requests at 1.0 req/s, which ask for 2,518 output tok/s from an engine that delivers 1,662:
| default configuration | projection | projection, max_tokens equal to the output length | |
|---|---|---|---|
| requests preempted | 20.4% | 0 | 0 |
| requests stalled for more than 5 s | 86 | 0 | 0 |
| output tok/s | 1,662 | 1,603 | 1,662 |
| end-to-end P50 | 149.6 s | 159.5 s | 146.1 s |
A backlog builds in every configuration. The default configuration lets it into the engine, where requests stall mid-stream; with the projection it waits in the flow-control queue, where priority bands decide which requests leave first.
How does it compare with the options available today? Token accounting is concurrency-detector in tokens mode with the cache size as its budget and estimated output tokens, next to the default utilization-detector:
| workload | default configuration | token accounting | projection |
|---|---|---|---|
| 192 closed-loop clients, 360 long outputs: requests preempted | 70.3% | 18.6% | 0 |
| 120 requests with four sequences each: requests preempted | 28.3% | 29.2% | 0 |
On the closed-loop workload the projection ran at 1,415 tok/s against token accounting's 1,423. On the two workloads that arrive at 1.0 req/s it was 4.8% and 4.6% faster than token accounting. On 720 requests whose output lengths shift from short to long, static concurrency-detector limits of 82 and 110 requests left 28 and 30 requests stalled for more than 5 s. The projection left none, at 1,562 tok/s, between the limits' 1,538 and 1,602.
max_tokens equal to the output length it runs at 1,777 tok/s against the default configuration's 1,666, with 1 of the 120 requests preempted.Test plan:
z margin and its bound, streamed progress, cached prompt prefixes, output limits, several prompts and choices, the sample size and the assumed requests.Filter include the term, and the score is unchanged when no projection is published.Which issue(s) this PR fixes:
Fixes #4369
Release note:
`inflight-load-producer` can project the KV cache growth of running requests (`kvGrowthProjection`). `utilization-detector` counts the projection toward saturation, so requests wait in the flow-control queue while the KV cache has no room for their output.Adds an opt-in KV cache growth estimator (kvGrowthProjection) to inflight-load-producer that projects how many additional KV tokens each endpoint will need beyond its latest scraped KVCacheUsagePercent, and wires that projection into utilization-detector as a third saturation and filter term. When kvGrowthProjection is unset, InFlightLoad.KVGrowthTokens remains 0 and utilization-detector behavior is unchanged.
pkg/epp/framework/plugins/requesthandling/dataproducer/inflightload/kv_growth.go): Maintains a sliding cohort of recent requests (max(200, 2.5*running)) plus max(20, len(cohort)/10) prior requests capped at maxOutputTokens. Rebuilds a Kaplan-Meier survival curve every 100ms (kvGrowthRefreshInterval) using completed requests with reported Usage.CompletionTokens (single sequence, natural termination, not cut off by a smaller per-request cap) as observed events and all others as right-censored.producer.go:729, kv_growth.go:213, 233, 247): ResponseBody updates startedAt and output = max(StreamedEvents, CompletionTokens) under index.RLock without blocking on mu. Unscraped prompt and streamed tokens stay reserved until two scrapes of ScalarFieldKVCacheUsagePercent complete after observation.pkg/epp/framework/plugins/flowcontrol/saturationdetector/utilization/detector.go:176, 293, 358): Computes ProjectedKVCacheUsage = KVCacheUsagePercent + KVGrowthTokens / (CacheBlockSize * CacheNumBlocks), taking max(qRatio, kvRatio, ProjectedKVCacheUsage) in Saturation and blocking endpoints with ProjectedKVCacheUsage >= 1.0 in Filter.max_tokens is dispatched via PreRequest (producer.go:588) to decode pod pod-a (100k-token KV capacity, 50% scraped usage), adding it to kvGrowth and writing a kvGrowthRelease eviction hook to PluginState.KVCacheUsagePercent scrapes, kvGrowth.projected (kv_growth.go:297) keeps the 8,000 prompt tokens in unscraped and searches over future decode steps up to maxOutputTokens (4096) for the peak mean + z * std occupancy across running requests plus one next request.utilization-detector.Saturation (detector.go:293) adds KVGrowthTokens / 100000 to 0.50; once ProjectedKVCacheUsage reaches 1.0, flow control holds further dispatches in queue and Filter (detector.go:358) removes pod-a while other candidates have room.kv_growth.go:305, producer.go:442, kv_growth.go:189 - [medium] The 100 ms projection cache is not invalidated when a new metrics scrape arrives, so updated KVCacheUsagePercent...llm-d-infra Helm chart is archived/deprecated; this change targets the current Kustomize deployment surface.Add Kustomize support for fixed replicas, proxy resources, and opt-in HPA for the Istio Gateway recipe.
guides/recipes/gateway/istio-hpa as an opt-in overlay using Istio's horizontalPodAutoscaler customization.The old llm-d-infra Helm chart is archived/deprecated; this change targets the current Kustomize deployment surface.
kubectl kustomize guides/recipes/gateway/istiokubectl kustomize guides/recipes/gateway/istio-hpapytest -q scripts/tests/test_istio_gateway_recipe.pygit diff --checkIstio's Gateway API documentation defines the parametersRef keys used here and the generated Deployment naming convention.
/test-nightly optimized-baseline-*configmap.yaml:12, kustomization.yaml:1 - [high] Hardcoding replicas: 1 in the base Istio ConfigMap forces istio-hpa to inherit both deployment.spec.replicas: 1 and...What type of PR is this?
/kind feature
/area coordinator
Proactive upstream contribution. This experimental connector is built from the public Coordinator/EPP and Mooncake integration contracts, not from a production incident or a deployed internal integration. The Validation section below covers the assembled pipeline and Go tests; live GPU Mooncake P/D transfer, retention, and expiry remain unverified.
What this PR does / why we need it:
The sidecar already supports Mooncake, but the Coordinator cannot build the connector's transfer parameters, so a Mooncake deployment cannot run prefill and decode through it. This adds an experimental, opt-in kv-mooncake connector for the existing sequential HTTP prefill/decode pipeline.
Coordinator handoff ยท HTTP admission regression
pkg/coordinator/pipeline/mooncake.go), so a retried prefill allocates a new ID and a handoff belonging to another request reads as absent./v1/chat/completions with explicit prefill followed by decode. Existing defaults and other connectors are unchanged.The configuration example uses operator-supplied endpoint attributes. Automatic engine registry refresh, multi-rank steering, gRPC and conditional decode are outside this slice.
Which issue(s) this PR fixes:
Part of #4390 (tracking #3156). This does not close the issue.
Validation:
Admission is enforced before scheduling, so an unsupported request does not consume a prefill round trip:
| Request | Before | After |
|---|---|---|
n: "2", n: 2.5, n: 0 | 200, one prefill and one decode | 400, no worker call |
image_embeds, audio_embeds, video_embeds content parts | 200, one prefill and one decode | 400, no worker call |
n: 2, image_url part | 400 | 400 |
image_url part next to a number outside float64 (1e400), non-array messages | 200, one prefill and one decode | 400, no worker call |
text-only, n absent or n: 1 | 200, one prefill and one decode | 200, one prefill and one decode |
These rows came from driving the assembled pipeline through the coordinator server against a fixture Gateway with the real EPP header plugins. Reverting the guards reproduced the "Before" column for every rejected shape, so the tests distinguish them from the fixed code. Configuration rejection is asserted through the exported Build and admission through a real HTTP server route, so losing either check fails the tests: removing the validatePipeline call from Build fails all eight configuration rows, and moving the handler off /v1/chat/completions fails every admission row with 502 instead of 400. The admission regression also covers image parts whose type is omitted or null. Both are recognized by the shared chat-part normalizer and rejected before either worker is called. The cases live in pkg/coordinator/server/mooncake_admission_test.go.
1e28c324, go build ./..., go vet ./pkg/coordinator/..., and go test -race ./pkg/coordinator/... pass locally with Go 1.27.4 (darwin/arm64).Not covered: a version-pinned live Mooncake P/D run on GPUs, so KV transfer, retention and expiry behavior are still unverified. Full make presubmit was not completed on 1e28c324: cryptographic signing requires a configured private key and the remaining checks require Docker/Podman; neither is available in this environment. All commits retain DCO sign-offs.
Release note _(write NONE if no user-facing change)_:
Add an experimental, opt-in kv-mooncake connector for single-rank HTTP chat-completion prefill/decode pipelines using configured EPP endpoint metadata.Adds an experimental, opt-in kv-mooncake connector (pkg/coordinator/connectors/kv/mooncake.go) for single-rank HTTP /v1/chat/completions prefill-then-decode pipelines, plus a pre-scheduling pipeline.RequestValidator hook (pkg/coordinator/pipeline/mooncake_guard.go, pkg/coordinator/server/handlers.go) and single-use MooncakeHandoff state (pkg/coordinator/pipeline/mooncake.go). Existing default connectors, gRPC pipelines, and sidecar Mooncake/NIXL protocols stay unchanged apart from consolidating FieldTransferID, FieldRemoteBootstrapAddr, and PartType*Embeds constants into pkg/common/request/constants.go.
validateMooncakePipeline (pkg/coordinator/pipeline/builder/builder.go:90) restricts kv-mooncake to HTTP worker_format=passthrough, [prefill, decode] steps, and no force_stream or forward_prompt_token_ids. Before Pipeline.Execute runs, Server.handleInference (pkg/coordinator/server/handlers.go:273) calls Pipeline.ValidateRequest, where PrefillStep.ValidateRequest delegates to ValidateMooncakeRequest (pkg/coordinator/steps/mooncake.go:48) to reject non-chat-completions, media/embeds parts, and n != 1 with HTTP 400 before consuming a prefill slot.PreparePrefillKVParams calls BeginMooncakeHandoff(reqCtx) to allocate a fresh xfer-<uuid> MooncakeHandoff bound to owner: reqCtx (pkg/coordinator/pipeline/mooncake.go:26). PrefillStep clears the handoff via AbandonMooncakeHandoff on any prefill error (pkg/coordinator/steps/prefill.go:110). ReadPrefillResponse (pkg/coordinator/connectors/kv/mooncake.go:57) requires x-llm-d-mooncake-prefill-handoff (endpoint, engine_id, bootstrap_port) to match x-llm-d-prefiller-host-port, then PrepareDecodeKVParams calls ConsumeMooncakeHandoff so each prefill handoff can feed at most one decode request.MooncakePrefillHandoffHeader is added to internalForwardingHeaders (pkg/coordinator/pipeline/context.go:70) so client values, forward_response_headers, and decode response headers cannot carry or leak it./v1/chat/completions (model: "m", text-only, n: 1 or omitted) to the coordinator; StripInternalHeaders drops any client x-llm-d-mooncake-prefill-handoff, and ValidateRequest admits the request.PrefillStep runs PreparePrefillKVParams, creating MooncakeHandoff{TransferID: "xfer-...", owner: reqCtx} and sending kv_transfer_params: {do_remote_prefill: false, do_remote_decode: true, transfer_id: "xfer-..."} to the prefill EPP.x-llm-d-mooncake-prefill-handoff from the endpoint's mooncakeHandoff attribute and copies it plus x-llm-d-prefiller-host-port onto the response; ReadPrefillResponse verifies both name the same host:port and populates EngineID and BootstrapAddress (http://<host>:<bootstrap_port>).DecodeStep calls ConsumeMooncakeHandoff(reqCtx) (clearing reqCtx.MooncakeHandoff and owner) and forwards kv_transfer_params: {do_remote_prefill: true, do_remote_decode: false, transfer_id, remote_bootstrap_addr, remote_engine_id} to the decode worker.inflight overlays create resources with fixed names. Verification looks up the names in SCALEDOBJECT_NAME and HPA_NAME, so the checks fail when readers set custom values.The default KEDA EPP inflight overlays create resources with fixed names. Verification looks up the names in SCALEDOBJECT_NAME and HPA_NAME, so the checks fail when readers set custom values.
Render both names in the Kubernetes and OpenShift overlays. The apply and cleanup commands now use the same names as verification, with the existing defaults for the stock deployment.
Follow-up to #2657.
kubectl kustomize and GNU envsubst with default and custom names on both platforms. The custom-name cases failed on the base revision and passed with this change.make verify, the guide Python suite, Markdown lint, and YAML lint.Validation used local manifest rendering with cluster operations stubbed. Live KEDA reconciliation and GPU inference remain unverified.
Replaces hardcoded ScaledObject and HPA resource names in the keda-epp inflight overlays with ${SCALEDOBJECT_NAME} and ${HPA_NAME} placeholders so custom deployment names match the verify commands. Updates the inflight apply and cleanup commands in guide.yaml and README.md to require and substitute both variables, while leaving queue, saturation, and nightly deploy scripts unchanged.
metadata.name (optimized-baseline-keda-epp) and spec.advanced.horizontalPodAutoscalerConfig.name (keda-hpa-optimized-baseline) with ${SCALEDOBJECT_NAME} and ${HPA_NAME} in k8s inflight scaledobject.yaml and ocp inflight scaledobject.yaml.: "${SCALEDOBJECT_NAME:?}" "${HPA_NAME:?}" guards and appends $SCALEDOBJECT_NAME $HPA_NAME to the envsubst allowlist in guide.yaml (and cleanup at lines 204-211), rendered into README.md.test_inflight_resource_names to run real kubectl kustomize + envsubst on both k8s and ocp inflight apply/cleanup commands for default and custom names.NAMESPACE=custom-ns, TARGET_DEPLOYMENT=custom-decode, SCALEDOBJECT_NAME=custom-so, and HPA_NAME=custom-hpa.apply_k8s_inflight or apply_ocp_inflight; envsubst substitutes ${SCALEDOBJECT_NAME} and ${HPA_NAME} into the kustomized ScaledObject.verify.tests.scaledobject and verify.tests.hpa; kubectl get scaledobject custom-so and kubectl get hpa custom-hpa now match the applied resources./test-nightly workload-autoscaling-keda-epp-amd-acc-rocm-vllm-x/test-nightly workload-autoscaling-keda-epp-ibm-acc-gpu-vllm-xguide.yaml:101, test_keda_epp.py:46 - [medium] apply_k8s_inflight (here), apply_ocp_inflight (line 106), and the inflight cleanup steps (lines 206, 210) only...Part of #4467 (item 3).
EngineType() string to kv-events-source (defaulting empty to vllm, matching New) and pass it to sessionStamp in inflight-load-producer.engineType: sglang, read or stamp top-level body session_id instead of the X-Session-ID header (which SGLang does not read):session_id without mutating the body.StartOfStream when session_params is set (non-null, including {}), because SGLang rejects requests setting both session_id and session_params and does not echo a session id on BlockStored for session_params requests.PayloadBytes), malformed/empty session_id, or empty RequestID.null for session_id and session_params as unset, write request.RequestID via MutatePayloadMap so Director.repackage re-serializes the body and updates Content-Length, and leave request headers untouched.inflight-load-producer README.CGO_ENABLED=0 go test -v ./pkg/epp/framework/plugins/datalayer/source/kvevents/... ./pkg/epp/framework/plugins/requesthandling/dataproducer/inflightload/... โ PASSgo test -race -count=1 ./pkg/epp/framework/plugins/datalayer/source/kvevents/... ./pkg/epp/framework/plugins/requesthandling/dataproducer/inflightload/... โ PASSCGO_ENABLED=0 go test ./pkg/epp/requestcontrol/... ./pkg/epp/config/loader/... โ PASSgolangci-lint fmt --diff โ cleangolangci-lint run --new-from-rev=origin/main โ 0 issuestypos โ cleanSupport KV-event-based prefill load release for SGLang backends by stamping top-level body `session_id` in `inflight-load-producer` when neither `session_id` nor `session_params` is set by the client.Extends inflight-load-producer's KV-event prefill completion tracking to SGLang backends by stamping the top-level JSON body field session_id instead of the X-Session-ID header when the referenced kv-events-source uses engineType: sglang. Requests carrying session_params, non-JSON payloads (such as SGLang gRPC PayloadBytes), malformed session_id, or an empty RequestID are left untouched and fall back to StartOfStream release. Existing vLLM X-Session-ID header stamping and vllm_xargs.session_id precedence remain unchanged.
Source.EngineType returns the configured EngineType, defaulting nil or empty config to vllm to match New.InFlightLoadProducerFactory reads source.EngineType() once at startup and stores it in kvEventsEngineType.sessionStamp dispatches sglang to sglangSessionStamp, which inspects PayloadMap via reqcommon.FieldValue (handling json.RawMessage and treating JSON null as unset) and writes request.RequestID via request.Body.MutatePayloadMap.Director.repackage runs after Director.prepareRequest (PreRequest plugins), sees Body.Mutated == true, re-marshals PayloadMap, and updates reqCtx.Request.RawBody and reqCtx.RequestSize so StreamingServer.generateHeaders emits the updated Content-Length.kv-events-source configured with engineType: sglang is bound by inflight-load-producer via kvEventsSourceRef, caching kvEventsEngineType = "sglang".{"model":"m","messages":[...]}) with RequestID = "req-sglang" and no session_id or session_params reaches PreRequest.sglangSessionStamp writes session_id = "req-sglang" through MutatePayloadMap, setting Body.Mutated = true without modifying X-Session-ID headers, and registers watchPrefill for req-sglang.Director.repackage serializes the updated body with session_id and updates Content-Length; when SGLang emits BlockStored with session_id: "req-sglang", ProcessEvents releases the prefill load immediately.standingRequestTTL, shorter than defaultRequestTTL and used only while the band is overloaded (Fixes #4608).What type of PR is this?
/kind feature
What this PR does / why we need it:
Adds an optional per-band queue-wait budget, standingRequestTTL, shorter than defaultRequestTTL and used only while the band is overloaded. Once one of a flow's requests waits out defaultRequestTTL, the flow and its band switch to the short budget, and each returns to defaultRequestTTL after one short budget without backlog. With the field unset nothing changes.
On one L4 under three 250-request bursts followed by a 1.5x overload, 30 s with 3 s once standing served all 750 burst requests and held the median TTFT under overload at 3.36 s. A fixed 30 s budget gave 30.36 s, and a fixed 3 s budget served 292 of the burst requests. Motivation and alternatives are in #4608, and the measurements are below.
How it works:
defaultRequestTTL while the pool has endpoints, it marks the flow and its band as standing. From then on the sweep evicts a request once it has waited the short budget since its enqueue or since the switch, whichever is later.EvictedTTL, the same 429 as today, and llm_d_epp_flow_control_standing_ttl_evictions_total counts them per band. Bands without the field, an empty pool under noEndpointRequestTTL and a shorter x-llm-d-inference-ttl behave as before.For reviewers: start with registry/standing.go, which holds the standing state of a flow and of a band behind the contracts.StandingQueue interface, then controller/internal/processor.go, where the sweep records long-budget expiries and applies the short budget.
Test plan:
defaultRequestTTL.llm_d_epp_flow_control_standing_ttl_evictions_total, and an expiry at the long budget does not.go test ./pkg/epp/flowcontrol/... ./pkg/epp/config/loader/... ./apix/config/... ./pkg/epp/requestcontrol/... ./cmd/epp/... and golangci-lint on the changed packages.The setup is in #4608: Qwen2.5-1.5B-Instruct behind Envoy, streaming 64 output tokens, about 25.3 req/s capacity. The standing row of the #4608 table is from a second session on the same setup, with capacity calibrated at 25.1 req/s instead of 25.6, so its last column is a share of the requests sent. A second arrival seed gave 750 burst requests served and a 3.37 s median.
With the 1.5x overload spread over 500 fairness IDs, the median TTFT went from 30.4 s to 3.4 s under global-strict and from 23.8 s to 3.3 s under round-robin.
A queue expiry carries no Retry-After, so a client on the OpenAI SDK defaults resends it twice, after about 0.5 s and 1 s. With such clients under sustained 1.5x overload, counting the requests first sent between 150 s and 300 s:
| Queue-wait budget | Original requests served | Attempts per request | TTFT from the first send, p50 / p90 / p99 | Unserved requests give up after |
|---|---|---|---|---|
| Fixed 30 s | 65.5% | 1.93 | 30.6 / 61.5 / 92.7 s | 92 s |
| 30 s, 3 s once standing | 66.3% | 1.92 | 3.6 / 7.5 / 11.4 s | 11 s |
An attempt that expires in the queue never reaches the engine, which is why the two budgets serve about the same share.
These replays drive the real FlowController on a Go virtual clock with one flow, eight simulated service slots sized to 25.5 req/s, and the public controller configuration. Ranges cover three arrival seeds. On the three budgets of the #4608 table, the replay gives burst counts within 16 requests and medians within 0.23 s of the L4 figures.
The #4608 trace with every budget I tried. Waits are queue waits of served requests sent between 195 s and 285 s:
| Queue-wait budget | Burst requests served (of 750) | Steady-overload median wait | Requests served across the trace |
|---|---|---|---|
| Fixed 3 s | 303 to 308 | 3.14 to 3.15 s | 74.6% to 75.1% |
| Fixed 5 s | 457 to 462 | 5.13 to 5.15 s | 76.8% to 77.3% |
| Fixed 8 s | 682 to 691 | 8.13 to 8.15 s | 80.1% to 80.5% |
| Fixed 10 s | 728 to 733 | 10.13 to 10.14 s | 81.1% to 81.4% |
| Fixed 12 s | 750 | 12.13 to 12.15 s | 81.6% to 82.4% |
| Fixed 15 s | 750 | 15.13 to 15.14 s | 82.5% to 83.2% |
| Fixed 20 s | 750 | 20.13 to 20.14 s | 83.9% to 84.6% |
| Fixed 30 s | 750 | 30.13 to 30.14 s | 86.6% to 87.4% |
| 30 s, 3 s once standing | 750 | 3.13 to 3.15 s | 79.1% to 79.9% |
Sustained 1.5x overload with callers that give up after 10 s, counting the requests sent between 120 s and 240 s. With the long budget above the callers' deadline no request waits it out, so the band never switches:
| Queue-wait budget | Median wait of served requests | Requests served |
|---|---|---|
| Fixed 30 s | 9.89 s | 66.1% to 66.6% |
| 30 s, 3 s once standing | 9.89 s | 66.1% to 66.6% |
| Fixed 8 s | 8.14 to 8.15 s | 66.9% to 67.4% |
| 8 s, 3 s once standing | 3.14 to 3.15 s | 66.9% to 67.4% |
The band switches to the short budget when a request has waited the full 30 s, about 90 s into a 1.5x overload, and until then waits grow as with the fixed budget. The 688 completions of the switch are the backlog of (30 s โ 3 s) ร 25.5 req/s, the same in replays of 150 s, 300 s, 600 s and 1,200 s.
The replays drive the real FlowController on a Go virtual clock with eight simulated 40 ms service slots and the public controller configuration. Ranges cover three runs. In the 2,175-request replay the light flow sends 118 requests to an idle pool, then for 7 s the light and heavy flows send 50 and 244 req/s under round-robin. A completion is timely when the request waited at most 300 ms in the queue.
Median queue wait of dispatched requests under seeded Poisson arrivals, measured from 8 s to 20 s (to 24 s for the two-flow rows). Waits exceed the budget because a request is evicted at the next sweep or check after its budget ends.
| Traffic in one band | Fairness policy | Fixed 1 s | 1 s, 100 ms once standing |
|---|---|---|---|
| 1 flow at 294 req/s | global-strict | 1,149 to 1,150 ms | 111 to 112 ms |
| Light flow at 50 req/s and heavy flow at 200 req/s (heavy flow shown) | round-robin | 1,135 to 1,139 ms | 105 to 106 ms |
| Same two flows (heavy flow shown) | global-strict | 1,096 to 1,101 ms | 105 ms |
| 294 req/s over 2,000 hashed flow IDs | global-strict | 1,148 to 1,149 ms | 112 ms |
| 294 req/s over 2,000 hashed flow IDs | round-robin | 717 to 719 ms | 70 to 71 ms |
The 2,175-request replay with every budget tried:
| Budget | Burst completed, of 118 | Light-flow completions from steady arrivals, of 350 | Timely completions, of 2,175 | All completions, of 2,175 |
|---|---|---|---|---|
| Fixed 100 ms | 118 | 350 | 998 to 1,005 | 1,516 to 1,522 |
| Fixed 300 ms | 118 | 350 | 536 to 542 | 1,565 to 1,571 |
| Fixed 600 ms | 118 | 350 | 528 to 529 | 1,641 to 1,649 |
| Fixed 1 s | 118 | 350 | 528 to 533 | 1,691 to 1,694 |
Fixed 1 s, band maxRequests: 20 | 28 | 180 to 197 | 1,420 to 1,423 | 1,420 to 1,423 |
Fixed 1 s, band maxRequests: 60 | 68 | 198 to 207 | 380 to 397 | 1,502 to 1,506 |
Fixed 1 s, band maxRequests: 120 | 118 | 225 to 230 | 403 to 408 | 1,609 to 1,614 |
| 1 s, 100 ms once standing | 118 | 350 | 1,118 to 1,122 | 1,512 to 1,514 |
The burst arrives 50 ms after the clock starts. Fixed budgets under 1 s are enforced at the 1 s sweep, so at this phase fixed 100 ms and 300 ms also complete the whole burst.
Light-flow burst in a standing band: the two flows at 50 and 200 req/s under round-robin, with 118 extra light-flow requests at 12 s or at 12.5 s. Light-flow rejections in the following 2 s were 106 to 110 with the standing budget. With fixed 1 s they were 0 for the burst at 12 s and 9 to 10 for the burst at 12.5 s.
CPU cost of the checks: medians of six samples on an Apple M5 with GOMAXPROCS=2, 1,000 flows holding one queued request each and no dispatches. With one flow on a short budget, scanning every flow each 100 ms took 9.76 ms of CPU per second of clock time and scanning only that flow's band took 1.01 ms. With all 1,000 flows on a short budget the two took 11.28 and 11.27 ms.
Which issue(s) this PR fixes:
Fixes #4608
Release note _(write NONE if no user-facing change)_:
Flow control: priority bands accept an optional `standingRequestTTL`, a shorter queue-wait budget that a flow and its band use once one of the flow's requests waits out `defaultRequestTTL`, until they show no backlog for that budget. `llm_d_epp_flow_control_standing_ttl_evictions_total` counts the evictions at that budget.registry.go:209, flowcontrol.go:195 - [high] Moving standingState, standingBand, and standingQueue into registry/standing.go still leaves TTL policy state and...PreRequest: the engine has not received it, and the in-flight producer has not counted it yet (Fixes #4611).What type of PR is this?
/kind bug
What this PR does / why we need it
The utilization detector does not count a request between its release by flow control and PreRequest: the engine has not received it, and the in-flight producer has not counted it yet. While data producers and scheduling place that request, flow control releases more requests against the same reading. Batch requests then queue at the engines, which serve them first-come-first-served, ahead of interactive requests that arrive later.
The detector now counts the requests awaiting placement that exceed their recent average as queued work. While requests are placed at a steady rate, each placement is matched by a completion at an engine, so the requests in placement at any moment do not lengthen the engine queues. A burst released faster than that does, and the detector counts it until it is placed. Counting every request awaiting placement would be simpler, but it limits dispatch to queue threshold ร endpoints per placement delay, however many slots the engines have free. That is 54 requests/s in the setup below.
On one EPP with four simulated engines, a 370 ms placement delay and an 8 s mean service time, the mean engine queue fell from 78 to 19 requests against a target of 20. When 160 clients start against an idle pool, the engine queue peaks at 36 requests instead of 136. Steady-state throughput did not fall in any workload.
A burst into idle engines is admitted over several placement delays, because the average rises only as requests are placed. When 700 clients start against engines with 1,024 free slots, the slots are 50% busy over the first 10 s instead of 64%.
Each pair shows main at c32ac7c first and this branch second. The real flow controller and utilization detector feed four simulated FIFO engines with eight running slots each. The threshold is five waiting requests per engine, scrapes run every 50 ms, and each run measures 400 s after a 100 s warm-up. Engine queue length is the time-weighted total across engines. Interactive start time runs from arrival at the EPP to the start of engine execution. #4611 contains the test source and reproduction commands.
| Mean service | Placement delay | KV usage | Live in-flight count | Mean engine queue | Mean interactive start | Throughput (req/s) |
|---|---|---|---|---|---|---|
| 8 s | 50 ms | 0% | yes | 44.93 / 19.70 | 11.53 s / 5.24 s | 3.96 / 3.96 |
| 8 s | 50 ms | 72% | yes | 41.27 / 19.71 | 10.48 s / 5.32 s | 4.00 / 3.98 |
| 8 s | 50 ms | 0% | no | 67.86 / 20.39 | 16.64 s / 5.18 s | 3.99 / 3.99 |
| 8 s | 370 ms | 0% | yes | 78.19 / 19.41 | 21.42 s / 5.23 s | 3.98 / 3.97 |
| 8 s | 370 ms | 72% | yes | 75.82 / 19.37 | 21.76 s / 5.28 s | 3.98 / 3.97 |
| 8 s | 370 ms | 0% | no | 78.54 / 21.17 | 21.19 s / 5.61 s | 3.98 / 3.98 |
| 100 ms | 50 ms | 0% | yes | 30.41 / 14.81 | 151.9 ms / 105.8 ms | 313.91 / 314.20 |
| 100 ms | 50 ms | 72% | yes | 26.35 / 13.96 | 156.5 ms / 106.4 ms | 309.27 / 311.78 |
| 100 ms | 50 ms | 0% | no | 46.39 / 29.44 | 214.8 ms / 145.5 ms | 315.36 / 315.26 |
| 100 ms | 370 ms | 0% | yes | 28.37 / 8.84 | 548.4 ms / 423.4 ms | 205.18 / 271.29 |
| 100 ms | 370 ms | 72% | yes | 27.90 / 8.85 | 551.0 ms / 413.4 ms | 201.62 / 272.66 |
| 100 ms | 370 ms | 0% | no | 28.15 / 9.88 | 529.1 ms / 414.8 ms | 215.40 / 292.08 |
Four more runs use the 8 s, 370 ms, 0% KV configuration with the live in-flight count.
| Run | Engine queue | Mean interactive start | Throughput (req/s) | Slots busy |
|---|---|---|---|---|
| Engines with 256 slots and 700 clients, so no engine fills | 0 / 0 | 370 ms / 370 ms | 84.09 / 84.06 | 66% / 66% |
| First 60 s after 160 clients start against an idle pool | peak 136 / 36, mean 77.5 / 21.1 | 22.43 s / 5.50 s | 3.82 / 3.83 | 99% / 99% |
| First 10 s after 700 clients start against idle engines with 256 slots | 0 / 0 | 370 ms / 439 ms | 56.90 / 37.50 | 64% / 50% |
| First 30 s after the same start | 0 / 0 | 370 ms / 417 ms | 73.67 / 67.20 | 65% / 60% |
How requests are counted
Flow control already holds a reservation for each request it releases, until the PreRequest hooks have run. The concurrency detector has counted these reservations since #3065.
Each time a reservation is released, the detector records how many are left, and it averages that number over about the last 16 releases. A pool that has had no request in placement counts every reservation. With four endpoints, a queue threshold of five and empty queues, 20 reservations give a saturation of 20 / 5 / 4 = 1.0, and the next request stays in the EPP queue until one is placed. A pool that usually has 30 requests in placement dispatches until 50 are.
PreRequest, right after it adds the request to the in-flight count of the selected endpoints. Without a producer, the director releases it after PreRequest, and the request shows up at the next engine scrape. An error before placement also releases it.Which issue(s) this PR fixes
Fixes #4611
Test plan
The affected flow-control, request-control, producer and runner packages pass go test -race.
Release note
When flow control uses the utilization detector, each active EPP counts a burst of requests it has released for scheduling against its estimated queue depth until they are placed. This keeps more work in the priority queue when placement is slow.runner.go:1013, detector.go:267 - [high] Wiring *utilization.Detector directly into *inflightload.InFlightLoadProducer in parseConfigurationPhaseTwo couples a...What type of PR is this?
/kind feature
What this PR does / why we need it:
Third and last PR of the importer design on #3345 (comment), on top of #4141 and #4674.
An EPP container restarted in place is a new process with a new replica ID. Since #4674 its first successful publish queues an import of the prefix window of the process it replaced, but that publish only sees the window if that process's Redis fields have not expired yet. With the default 2 s stateTTL that is a close race: in the cluster runs on #4674 the restarted process read all 100 fields in every round, but in 3 of 8 rounds 38โ90 of them were already gone when their TTL was queried right after the read.
This PR lets a contributor keep its published state longer than the syncer's TTL.
CrossReplicaSpec gets an optional StateTTL. A syncer that supports it uses the larger of StateTTL and its own TTL; a syncer may ignore it. Zero keeps the syncer's TTL.redis-syncer uses max(spec.StateTTL, stateTTL) for the field in Set and SetBatch. The key expiry is now set with PEXPIRE NX followed by PEXPIRE GT in the same transaction, so a Set only extends it: a replica with a shorter TTL cannot cut fields that another replica wrote with a longer one. This also holds when crossReplicaStateTTL is unset and replicas are configured with different stateTTL values; before, the last writer set the key expiry. With one TTL everywhere it behaves like the plain PEXPIRE it replaces. It adds one command per endpoint to each publish transaction.approx-prefix exposes it as crossReplicaStateTTL (duration). Unset by default, which keeps the syncer's TTL; a negative value fails construction.inflight-load-producer keeps the syncer TTL, so a dead replica's in-flight load still expires after stateTTL. p2p-syncer ignores StateTTL: each replica sends only its own values, so a restarted process cannot read the window of the process it replaced, whatever the TTL.What a longer TTL costs: for up to StateTTL after a replica stops, every peer still reads its window on each publish cycle, and a replica whose publish succeeds in that time reads it and queues an import, also when a model server has evicted those blocks since. Prompts a peer imported earlier stay in its index until LRU eviction with any TTL. It is set per contributor and not on the syncer so that a dead replica's in-flight load does not stay counted for the longer time.
Rolling upgrade: a replica without this change still sets the key expiry to its own stateTTL with a plain PEXPIRE, which can shorten it below a longer field TTL. After that, a Set from an upgraded replica extends the key only to that Set's own TTL. So until a replica publishes with the longer TTL again, the longer-lived fields last only while some replica keeps publishing to the key within the shorter TTL; if publishing stops for longer than that, the key expires and takes them with it. The README says to set the parameter only after every EPP replica supports it.
Overlap with #4019. Both PRs change how redis-syncer sets expiry when it publishes. #4019 adds a stream write path that sets the field, hash key and stream key expiry from stateTTL. Whichever PR lands second has to use the spec TTL and the extend-only key expiry on that path too. I'll do that if #4019 lands first.
Measurements. None on this branch. The numbers below are from the prototype on 876c4dd2 reported on #3345, same tx_air harness as #4674, with crossReplicaStateTTL: 15s, one round each of single kill, late switch-back and injected first-publish failure: the restarted primary read and imported 100 of 100 old fields in every round, routed 20 of the first 20 requests after switch-back to the prefix owner, and had no producer timeouts in the 3 s after switch-back. These are first restarts only. 15s is meant to also cover one 10 s kubelet restart backoff; that was not measured, and a longer crash loop is not covered.
Open questions (from the design comment):
StateTTL on CrossReplicaSpec the right place, or should the syncer config take a TTL per state key?crossReplicaStateTTL? This PR only adds the plugin parameter.Test plan:
redis-syncer: the field and key TTL for a spec TTL that is zero, shorter and longer than the syncer's, through Set, SetBatch and repeated Set calls.redis-syncer: a Set with a shorter TTL does not shorten the key expiry, and a plain PEXPIRE from a replica without this change is extended by the next Set.approx-prefix: crossReplicaStateTTL parses, is passed to the spec, and a negative value is rejected.inflight-load-producer publishes with a zero StateTTL.PEXPIRE a Set with the shorter TTL leaves the key at the shorter TTL and a Set with the longer TTL extends it again.make presubmit up to verify-review-playbook. That last step fails the same way on main at a4e84c4e: two files from #4375 and #3706 have no routing row in the review playbook. This PR does not touch them.Which issue(s) this PR fixes:
Fixes #3345
Release note _(write NONE if no user-facing change)_:
approx-prefix: new optional `crossReplicaStateTTL` parameter keeps a replica's published prefix window in redis-syncer longer than `stateTTL`, so an EPP restarted in place can import the window of the process it replaced.cross_replica_syncer.go:171, redis_syncer.go:291 - [high] Putting StateTTL on CrossReplicaSpec and crossReplicaStateTTL on approx-prefix (types.go:247) leaks...Qwen/Qwen3-32B without --enable-auto-tool-choice, so requests that carry tools are rejected and the thinking block comes back as plain content (Part of #2640).Part of #2640
The TPU v5p vLLM overlays serve Qwen/Qwen3-32B without --enable-auto-tool-choice, so requests that carry tools are rejected and the thinking block comes back as plain content. The v6 and v7 overlays and the tiered v5p SGLang overlay already set the parser flags.
This adds --enable-auto-tool-choice, --tool-call-parser hermes and --reasoning-parser qwen3 to:
optimized-baseline/modelserver/tpu/v5p/vllm/base/patch-vllm.yamlprecise-prefix-cache-routing/modelserver/tpu/v5p/vllm/base/patch-vllm.yamltiered-prefix-cache/modelserver/tpu/v5p/vllm/native/cpu/base/patch-vllm.yaml (inside the /bin/sh -c serve script, with line continuations)Not run on a cluster.
scripts/tests/test_tpu_v5p_vllm_tool_flags.py renders the base and gke variant of each overlay with kubectl kustomize. For the shell entrypoint it checks the script parses, is one continued exec vllm serve command, and then reads argv with shlex. It asserts --enable-auto-tool-choice appears once and each parser flag has exactly one value. It fails 6/6 on main and passes 6/6 with this change. Dropping a line continuation or setting --enable-auto-tool-choice=false in the tiered script makes it fail. make verify is clean.
Enables vLLM automatic tool calling (--enable-auto-tool-choice, --tool-call-parser=hermes) and Qwen3 reasoning extraction (--reasoning-parser=qwen3) on the three TPU v5p vLLM single-host overlays serving Qwen/Qwen3-32B, and adds a Kustomize-render pytest regression suite. The existing TPU v5p P/D overlays, TPU v6 vLLM overlays, and TPU v5p SGLang overlays remain unchanged.
guides/optimized-baseline/modelserver/tpu/v5p/vllm/base/patch-vllm.yaml (L21-L23) and guides/precise-prefix-cache-routing/modelserver/tpu/v5p/vllm/base/patch-vllm.yaml (L23-L25) append the three flags to the vllm serve container args array, inherited by their gke/ and top-level Kustomize overlays.guides/tiered-prefix-cache/modelserver/tpu/v5p/vllm/native/cpu/base/patch-vllm.yaml (L21-L23) inserts the flags into the line-continued exec vllm serve command inside the /bin/sh -c args[0] script.scripts/tests/test_tpu_v5p_vllm_tool_flags.py renders base and gke for all three overlays with kubectl kustomize, validates /bin/sh -n and single-command line continuations for shell entrypoints, and asserts --enable-auto-tool-choice appears once with --tool-call-parser=hermes and --reasoning-parser=qwen3.guides/tiered-prefix-cache/modelserver/tpu/v5p/vllm/native/cpu/gke renders the decode Deployment inheriting /bin/sh -c from common/single-host with the patched exec vllm serve Qwen/Qwen3-32B ... --enable-auto-tool-choice --tool-call-parser hermes --reasoning-parser qwen3 command.tools schema are accepted by vLLM instead of returning HTTP 400, and <think> blocks are parsed into reasoning_content./test-nightly optimized-baseline-gke-acc-tpu-vllm-x/test-nightly precise-prefix-cache-routing-gke-acc-tpu-vllm-x/test-nightly tiered-prefix-cache-gke-cpu-tpu-vllm-nativepatch-vllm.yaml:21 - [low] guides/agentic-api/README.md (line 278) still qualifies optimized-baseline, precise-prefix-cache-routing, and...โฆt blocks.
The estimate tracks dispatched input commitments, deduplicates shared full blocks, and combines them with sampled KV usage.
The feature defaults to observation only. When routing is enabled, it filters candidates at or above estimated capacity, retains unknown candidates, and fails open when all candidates are filtered.
An optional latency-predictor guard can retain a filtered candidate when the estimated remaining completion time of its sole tracked request is no greater than the predicted TTFT difference to the best eligible alternative. The estimate uses observed stream-event progress and the request output cap.
The change also refreshes metrics before scheduling and retains candidates with missing or stale metrics in the utilization scheduling filter.
The feature is experimental: it requires one EPP replica and does not model output KV blocks. Stream events are approximate progress, not guaranteed token counts, and the remaining completion time is not a bound.
/kind feature
Which issue(s) this PR fixes:
Fixes #
https://github.com/llm-d/llm-d-router/issues/4752
Add experimental opt-in projected KV-capacity filtering based on active input blocks, with an optional latency-predictor guard.kv_capacity.go:87, kv_capacity.go:183, director.go:468 - [high] Implementing fwksched.Filter on TokenLoadScorer bolts an experimental, single-EPP, vLLM-only capacity gate onto a...DecodePodName logged at error level when the client-supplied session token was not valid base64 (Fixes #4693).What type of PR is this?
/kind bug
What this PR does / why we need it:
DecodePodName logged at error level when the client-supplied session token was not valid base64. The token is client input and an invalid value is ignored, so a client sending a malformed x-session-token produced one error log line per request while routing proceeded normally.
This changes the log to V(logutil.DEBUG).Info, matching how an invalid TTL header is handled in pkg/epp/requestcontrol/admission.go. The change is in the shared helper, so it covers both the session-affinity filter and scorer. Routing behavior does not change.
A table test for DecodePodName captures the log output. The invalid-token case fails on main with ERROR ... Error decoding session header and passes with this change. The session-affinity filter, scorer and helper tests and golangci-lint pass.
Test plan:
"" and emits no error-level log lineWhich issue(s) this PR fixes:
Fixes #4693
Release note _(write NONE if no user-facing change)_:
The session-affinity plugins log a malformed session token at debug level instead of error level.Lowers the log level in DecodePodName when decoding an invalid base64 x-session-token header from Error to V(logutil.DEBUG).Info, preventing per-request error logs on malformed client input. Both the session-affinity filter and scorer share this helper, and routing behavior (returning "" to ignore affinity) stays unchanged.
pkg/epp/framework/plugins/scheduling/util/sessionaffinity/header.go#L71: replaces log.FromContext(ctx).Error(err, "Error decoding session header") with log.FromContext(ctx).V(logutil.DEBUG).Info("Ignoring invalid session header", "err", err).pkg/epp/framework/plugins/scheduling/util/sessionaffinity/header_test.go#L31-L68: adds TestDecodePodName capturing logs via logutil.NewTestLoggerWithWriter for valid, empty, and invalid tokens.x-session-token: not-base64!! to an EPP configured with the session-affinity filter or scorer.encodedEndpointHeaderStrategy calls sessionutil.DecodePodName(ctx, token) at encoded_endpoint_header.go:52, which fails base64.StdEncoding.DecodeString, emits Ignoring invalid session header only at verbosity logutil.DEBUG (4), and returns "" so normal scheduling proceeds.header_test.go:63 - [low] TestDecodePodName only asserts that no ERROR line is logged, so deleting the debug log call in DecodePodName would...TenantKey; the qos-contract plugin does this from its team header (Fixes #4730).What type of PR is this?
/kind bug
What this PR does / why we need it:
A RequestHeaderProcessor can produce a request's fairness ID through TenantKey; the qos-contract plugin does this from its team header. applyDeclaredOverrides copies that tenant onto FairnessID, and the attribution switch in HandleRequest then sees a non-empty ID and records it with source="header", the same as a client-supplied fairness-ID header. As a result, llm_d_epp_fairness_id_resolved_total{source="header"} and trace attribution count plugin-derived tenants as header traffic, so the share of requests that arrived without a fairness-ID header cannot be measured.
runRequestHeaderProcessors already knows whether the request carried the header. This PR carries that provenance to the attribution switch and records a tenant produced through TenantKey with the new source="tenant_key". The sidecar handoff accepts the new source, its overflow series is created at startup, and docs/metrics.md documents it.
The recording rules llm_d:epp_named_fairness_ids:count5m and llm_d:epp_named_fairness_ids:incomplete5m now select source=~"header|tenant_key", so TenantKey tenants still count as named fairness IDs and their overflow still marks the count incomplete. A tenant seen from both sources counts once. The rules test covers this.
The fairness ID used for scheduling and flow control is unchanged; only the recorded source changes.
Which issue(s) this PR fixes:
Fixes #4730
Release note:
Add `tenant_key` as a `source` label value on `llm_d_epp_fairness_id_resolved_total` and `llm_d_epp_fairness_id_overflow_total` for fairness IDs a RequestHeaderProcessor produced through `TenantKey`. These requests were previously reported with `source="header"`. The `llm_d:epp_named_fairness_ids:count5m` and `llm_d:epp_named_fairness_ids:incomplete5m` recording rules include the new source, so their values do not change. Dashboards or alerts that filter `source="header"` directly no longer see these requests.Previously, a RequestHeaderProcessor such as qos-contract that populated request.FairnessID via TenantKey was recorded under source="header" in metrics and trace attribution, making plugin-derived tenants indistinguishable from client-supplied fairness headers. This change adds a dedicated tenant_key attribution source across EPP resolution, sidecar handoff, startup overflow series initialization, Prometheus recording rules, and docs. Scheduling, flow-control queueing, and the resolved FairnessID value itself remain unchanged.
AttributionSourceTenantKey ("tenant_key") to normalizeAttribution and WithAttributionHandoff, and pre-creates the startup zero series in InitFairnessIDResolutionMetrics.runRequestHeaderProcessors snapshots hadHeaderTenant := request.FairnessID != "" before running plugins and returns tenantFromKey = true when applyDeclaredOverrides copies a non-empty TenantKey string.HandleRequest, source starts as tenant_key when tenantFromKey is true (or header otherwise) and stays unchanged across both composed (<tenant>/<program>) and standalone tenantID != "" branches, while empty tenantID still falls through to derived_root, agent_identity, or default.docs/rules/fairness-id-rules.yaml expands source=~"header|tenant_key" in llm_d:epp_named_fairness_ids:count5m and incomplete5m, deduplicating an ID seen from both sources via count by (namespace, inference_pool, fairness_id).x-llm-d-inference-fairness-id, so hadHeaderTenant is false and BeginRequestAttribution initializes the ingress span state to (default-flow, default).qos-contract resolves team-a from its team header and writes TenantKey="team-a"; applyDeclaredOverrides copies it to request.FairnessID and sets tenantFromKey=true.HandleRequest sets source="tenant_key" (composing team-a/<session> if composeFairnessIDs is enabled and an agent/lineage ID is present), updates request attribution and llm_d_epp_fairness_id_resolved_total{fairness_id="team-a",source="tenant_key"}, and hands (team-a, tenant_key) to the P/D sidecar on sampled traces.metrics.md:871 - [low] Listing tenant_key after derived_root and agent_identity (while those bullets still say "no header") suggests...What type of PR is this?
/kind bug
/area datalayer
What this PR does / why we need it:
File discovery watches the endpoints file itself, so the watch stays on the old file when the file is moved aside, or deleted and recreated. Reloads then stop until the EPP restarts (reproduction in #3615).
The plugin now re-attaches the watch and re-reads the file every 10 seconds, as controller-runtime's certwatcher does (and #3051 for the config). A sha256 of the content skips the reload when nothing changed; the event path uses the same check, so a poll and an event for one change reload once. This also picks up atomic replaces on Docker Desktop bind mounts, which deliver no events, so the docs note from #3851 now says the change is picked up within 10 seconds instead of asking to edit in place.
The per-file watch stays, so the ConfigMap ..data swap and the cross-directory symlink keep working; the tests #3851 added for both pass unchanged. A directory watch was the alternative, and #3615 shows why it breaks those two cases.
Tests added: rename the file away then write a new one, delete and recreate, and a poll with unchanged content that must not reload. go test -race passes for the plugin.
make presubmit passes except verify-boilerplate (.github/scripts/merge-pr-onto-base*.sh) and verify-review-playbook (requesthandling/forwardtokens/plugin.go), which fail on main too, in files this change does not touch. Verified on Linux (OrbStack); not on Docker Desktop itself.
Thanks to @iit2009046 for the analysis in #3615 and the tests and docs in #3630 and #3851.
Which issue(s) this PR fixes:
Fixes #3615
Release note _(write NONE if no user-facing change)_:
file-discovery with `watchFile: true` now picks up changes within 10 seconds when the endpoints file is moved aside, deleted and recreated, or replaced on a Docker Desktop bind mount. Previously reloads stopped until the EPP restarted.File-based endpoint discovery loses its inotify watch when the endpoints file is moved aside, deleted and recreated, or atomically replaced on a Docker Desktop bind mount. This change adds a 10-second polling ticker to FileDiscovery.Start that re-attaches the fsnotify watch and re-reads the file, plus a SHA-256 content hash check in FileDiscovery.load to skip redundant datastore reloads. The per-file watch, validation rules, and multicluster-file-discovery wrapper behavior remain unchanged.
pkg/epp/framework/plugins/datalayer/discovery/file/plugin.go:226-239): When watchFile is enabled, Start creates a time.Ticker (defaultPollInterval = 10 * time.Second) and on each tick calls _ = watcher.Add(f.path) followed by f.load(notifier), logging reload errors without stopping.pkg/epp/framework/plugins/datalayer/discovery/file/plugin.go:103,284-288): FileDiscovery.load computes sha256.Sum256(data) after reading (within the 1 MiB limit) and returns nil early when hash == f.lastHash, preventing repeated Upsert/Delete churn across idle ticks or overlapping fsnotify and poll triggers.Start executes <-poll.C and <-watcher.Events in a single select loop, so f.lastHash and watcher are accessed from one goroutine while f.mu continues to guard f.endpoints for concurrent DumpState() reads.pkg/epp/framework/plugins/datalayer/discovery/file/multicluster.go:54-56): multiClusterFileDiscovery delegates Start to FileDiscovery.Start, inheriting the 10-second recovery poll and hash deduplication.FileDiscovery.Start loads /etc/epp/endpoints.yaml (endpoints ep1, ep2), stores its SHA-256 in f.lastHash, closes Ready(), and attaches watcher.Add./etc/epp/endpoints.yaml to /etc/epp/endpoints.yaml.bak (fsnotify emits Rename, which Start ignores) and writes a new /etc/epp/endpoints.yaml containing ep3.poll.C fires: watcher.Add("/etc/epp/endpoints.yaml") attaches to the new inode, f.load sees a new SHA-256 hash, upserts ep3, deletes ep1/ep2, and updates f.lastHash.f.lastHash, and return immediately without touching the datastore; future in-place writes trigger fsnotify.Write immediately.plugin_test.go:595, plugin_test.go:579, plugin.go:236 - [medium] The in-place-2 assertions here and in TestStart_WatchFileReloadsAfterDeleteAndCreate (line 680) pass via the 100ms...OTEL_TRACES_ENABLED_SCOPES, a comma-separated list of instrumentation scopes to record, following the design in the issue (Fixes #3372).What type of PR is this?
/kind feature
What this PR does / why we need it:
Today there's no way to drop spans from a noisy package without turning tracing off. This adds OTEL_TRACES_ENABLED_SCOPES, a comma-separated list of instrumentation scopes to record, following the design in the issue. When it is set, Tracer(scope...) returns a no-op tracer for any scope not on the list, including the default llm-d-router scope. Those spans record nothing but keep the parent span context, so a span from an enabled scope still nests under its nearest enabled ancestor, or under the remote parent from an incoming traceparent. Unset, empty, whitespace-only or separator-only values keep every scope enabled, which matches current behavior. Tracer reads the variable on each call and trims each entry, so nothing else needs wiring. The tracing env table in docs/disaggregation.md lists it.
otelhttp picks its tracer from the context span's TracerProvider(). A plain no-op span reports the no-op provider, so otelhttp would drop HTTP client spans made under an excluded scope. The excluded span reports its recording parent's provider, or the global provider under a remote parent, while staying non-recording itself.
TestTracerEnabledScopes covers the env parsing cases, parent linkage through an excluded scope (same trace and span ID), and an otelhttp client span under an excluded scope with a local and with a remote parent. Copied onto main, 5 of its 12 subtests fail, for example "span recorded = true, want false" for an unlisted scope. With the change all 12 pass. go test -race ./pkg/common/observability/... and make lint (golangci-lint and typos) pass.
Limits: the filter only covers tracers from tracing.Tracer. HTTP server and client spans created by otelhttp use the global provider and still record, and the docs row says so.
Which issue(s) this PR fixes:
Fixes #3372
Release note _(write NONE if no user-facing change)_:
Add the OTEL_TRACES_ENABLED_SCOPES environment variable. Set it to a comma-separated list of instrumentation scopes to record spans only from those scopes. Unset keeps every scope enabled.What type of PR is this?
/kind enhancement
What this PR does / why we need it:
Follow-up to #4780 addressing #4865.
Fixes two failure-attribution edge cases in speculativeLifecycleReleaser.ResponseBody and adds operational observability for early speculative hint releases:
prerequest.go):PrefillProfile().FirstEndpoint() != nil or x-prefiller-host-port / x-encoder-host-ports so untrusted x-llm-d-failed-stage headers on non-P/D requests are ignored), x-llm-d-failed-stage: decode and none-prefilled preserve the prefill pod's warm speculative hints.seedDecodeWhenDisaggregated (seedDecode) is enabled, only the decode pod's hints are released via ReleasePod; when false (default), prefill hints stay intact.x-llm-d-failed-stage: prefill (or unmarked failures) continues to release all hints for the request.prerequest.go):metadata.ServedEndpoint(response.ReqMetadata) (IPv6-safe net.SplitHostPort matching endpointhealth/filter.go). When the proxy served the request from a different endpoint than the primary target seeded at PreRequest, immediately withdraws the unserved primary pod's phantom hints via ReleasePod instead of leaving them alive for speculativeTTL.SpeculativeIndex per-pod release & tracking (pkg/kvcache/speculative.go):ReleasePod(requestID, pod string) bool, updates Release(requestID string) bool to report whether any tracked hints were actually withdrawn (preventing double-counting on duplicate callbacks), and adds TrackedRequests() int.producer.go, prefixmetrics/metrics.go):DumpState() (precisePrefixState) with speculativeLifecycleRelease and speculativeTrackedRequests.llm_d_epp_prefix_speculative_releases_total{plugin_name,plugin_type,reason} with reasons abandoned, failed_response, pre_first_token_abort, and served_elsewhere.Note on related open PRs (unstacked / merge-order dependency):
perf/speculative-index-lease-tombstone, fixing #4864) rewrites pkg/kvcache/speculative.go internals to an O(1) request-lease tombstone design. This PR is intentionally kept unstacked against main for independent review; whichever PR merges second will rebase ReleasePod, Release() bool, and TrackedRequests() cleanly onto the other.perf/eos-only-response-body-processor, fixing #4863) has a minor overlap in pkg/epp/framework/plugins/requesthandling/dataproducer/preciseprefixcache/prerequest.go and producer.go (ResponseBodyEndOfStreamOnly).Test plan:
go vet ./pkg/kvcache/... ./pkg/epp/framework/plugins/requesthandling/dataproducer/prefixmetrics/... ./pkg/epp/framework/plugins/requesthandling/dataproducer/preciseprefixcache/... ./pkg/epp/metrics/...go test -race -count=1 ./pkg/kvcache/... ./pkg/epp/framework/plugins/requesthandling/dataproducer/prefixmetrics/... ./pkg/epp/framework/plugins/requesthandling/dataproducer/preciseprefixcache/... ./pkg/epp/metrics/...TestSpeculativeIndexReleasePodAndTrackedRequests (pkg/kvcache/speculative_test.go)TestRecordSpeculativeRelease (pkg/epp/framework/plugins/requesthandling/dataproducer/prefixmetrics/metrics_test.go)TestSpeculativeLifecycleRelease_DisaggregatedStageAttribution, TestSpeculativeLifecycleRelease_EnvoyFailoverReleasesPrimaryPod (IPv4 + IPv6), and TestSpeculativeLifecycleRelease_DumpStateAndMetrics (pkg/epp/framework/plugins/requesthandling/dataproducer/preciseprefixcache/prerequest_test.go)Which issue(s) this PR fixes:
Fixes #4865
Related: #4780, #4042, #4857, #4863, #4864, #4902, #4940
Release note _(write NONE if no user-facing change)_:
NONEExtends speculativeLifecycleRelease to preserve prefill-pod speculative KV hints on decode-only disaggregated failures, release unserved primary-pod hints on Envoy failover, and expose early-release metrics and debug state. pkg/kvcache.SpeculativeIndex gains per-pod release (ReleasePod), boolean return on Release, and TrackedRequests(), while natural completions and mid-decode aborts on the primary endpoint keep their existing speculativeTTL.
pkg/kvcache/speculative.go): ReleasePod(requestID, pod) filters reqCurrent[requestID] and reqPrevious[requestID] for entries matching pod and decrements only those block leases while leaving other pods for the same request intact. Release(requestID) and ReleasePod return bool indicating whether tracked hints were withdrawn to prevent double-counting metrics.pkg/epp/framework/plugins/requesthandling/dataproducer/preciseprefixcache/prerequest.go): On non-error completions, servedElsewhere compares metadata.ServedEndpoint(response.ReqMetadata) via net.SplitHostPort against targetEndpoint and calls ReleasePod on the primary pod (served_elsewhere). On HTTP 4xx/5xx, non-zero gRPC status, or pre-first-token aborts for disaggregated requests with x-llm-d-failed-stage set to decode or none-prefilled, prefill hints are preserved and only targetEndpoint is released when seedDecode is enabled.pkg/epp/framework/plugins/requesthandling/dataproducer/preciseprefixcache/producer.go, pkg/epp/framework/plugins/requesthandling/dataproducer/prefixmetrics/metrics.go): DumpState() adds speculativeLifecycleRelease and speculativeTrackedRequests, and prefixmetrics registers counter llm_d_epp_prefix_speculative_releases_total{plugin_name,plugin_type,reason}.req-1 seeds block keys on prefill-1 (seedDecode=false).x-llm-d-failed-stage: decode.speculativeLifecycleReleaser.ResponseBody enters the disaggregated StageDecode branch, sees seedDecode=false, leaves prefill-1's speculative hints active for subsequent requests, and returns without releasing prefill-1.req-2 picked for pod-A, Envoy fails over to pod-B (x-gateway-destination-endpoint-served: pod-B) and returns HTTP 200; ResponseBody calls ReleasePod("req-2", pod-A) and increments llm_d_epp_prefix_speculative_releases_total{reason="served_elsewhere"}.prerequest.go:439, metrics.go:160 - [high] Checking routing.EncoderEndpointsHeader in isDisaggregatedRequest prevents releasing the decode pod's speculative hints...x-llm-d-mm-hashes gRPC metadata contract between the coordinator and EPP for multimodal prefix-cache routing (Part of #3988).What type of PR is this?
/kind feature
What this PR does / why we need it:
This change implements the x-llm-d-mm-hashes gRPC metadata contract between the coordinator and EPP for multimodal prefix-cache routing.
pkg/common/request): Defines MMHashesHeaderKey (x-llm-d-mm-hashes) and bounded ASCII encode/decode helpers (MaxMMHashesHeaderBytes = 16 KiB, MaxMMHashesEntries = 128). Each entry carries a modality, content hash, and optional placeholder token span (offset and length).x-llm-d-mm-hashes to coordinator internalForwardingHeaders so client copies are stripped on ingress and passthrough. Adds x-llm-d-mm-hashes to EPP InputControlHeaders so EPP preserves the header for parsers and removes it before forwarding requests to model servers.x-llm-d-mm-hashes on outbound vllm.Inference encode and prefill legs and outbound sglang.api.v1 prefill legs. The coordinator prefers populated RequestContext.MultimodalEntries and otherwise reads scanned wire media metadata.x-llm-d-mm-hashes in vllminference-parser and sglanggrpc-parser to populate MultiModalFeatures for token-producer and precise-prefix-cache-producer. Inline body features take precedence over metadata. The parsers ignore malformed or oversized values without failing requests.Test plan:
vllminference-parser / sglanggrpc-parser, token-producer, and precise-prefix-cache-producer.-race tests and make presubmit pass.Which issue(s) this PR fixes:
Part of #3988
Release note:
Coordinator attaches bounded `x-llm-d-mm-hashes` gRPC metadata on outbound vLLM encode/prefill and SGLang prefill calls, and EPP gRPC parsers consume it to populate multimodal prefix-cache features.constants.go:46, vllm_grpc.go:144 - [high] Do we need the new x-llm-d-mm-hashes wire contract and parser merge path here when no gRPC path populates...requestHandler.bodyFieldsSanitizationPolicy: trustCaller, which disables sanitization for every caller that... (Fixes #4824)What type of PR is this?
/kind feature
/kind security
What this PR does / why we need it:
An EPP behind a shared Gateway cannot distinguish Coordinator phase calls from direct client traffic without setting requestHandler.bodyFieldsSanitizationPolicy: trustCaller, which disables sanitization for every caller that reaches the EPP.
This change adds shared-secret HMAC-SHA256 caller authentication between Coordinator and EPP:
gateway.auth_secret_env or gateway.auth_secret_file enables per-request x-llm-d-trusted-caller-auth signatures on outbound pipeline calls (HTTP Request, HTTP decode proxy, and gRPC StreamGRPC). Signatures bind x-llm-d-epp-profile and raw wire body bytes. Passthrough requests are never signed, and client copies of the header are stripped and redacted in logs.requestHandler.trustedCallerAuth (secretEnv or secretFile, plus optional maxClockSkew, default 60s) verifies x-llm-d-trusted-caller-auth only when router-owned body fields appear and x-llm-d-unsanitized-body is not true. Valid requests preserve Coordinator-written fields without mutating the body while unauthenticated requests follow strip or reject. EPP always removes x-llm-d-trusted-caller-auth before forwarding upstream, including when forwardInputControlHeaders is enabled.kv_transfer_params or ec_transfer_params on a request carrying x-llm-d-epp-profile without x-llm-d-unsanitized-body: true, it logs a one-time warning per Director.Helm chart wiring for provisioning the shared Secret is deferred to a follow-up PR.
Test plan:
v1alpha1 conversion, and validation (mutual exclusion, maxClockSkew bounds, incompatibility with trustCaller)forwardInputControlHeaders: true pathsDirector preservation of signed requests, sanitization of missing/invalid/expired/tampered/unsanitized-marked requests, and one-time misconfiguration warning behaviormake presubmitWhich issue(s) this PR fixes:
Fixes #4824
Release note:
Added shared-secret HMAC-SHA256 caller authentication (`gateway.auth_secret_env`/`auth_secret_file` on Coordinator and `requestHandler.trustedCallerAuth` on EPP) so an EPP behind a shared Gateway can preserve Coordinator-written body fields without disabling sanitization via `trustCaller`.Adds optional shared-secret HMAC-SHA256 authentication between the Coordinator and EPP so EPP can keep bodyFieldsSanitizationPolicy set to strip or reject for direct clients while preserving Coordinator-written fields (kv_transfer_params, ec_transfer_params, prompt_token_ids). Coordinator signs outbound pipeline calls with x-llm-d-trusted-caller-auth, and EPP verifies the signature only when protected body fields appear and removes the header before forwarding upstream. Existing trustCaller deployments, passthrough sanitization via x-llm-d-unsanitized-body, and clean client requests without protected fields remain unchanged.
pkg/common/request/caller_auth.go, pkg/common/request/constants.go): TrustedCallerAuth loads newline-separated keys from env or file (keys[0] signs, all keys verify in constant time) and computes/verifies v1=<unix_ts>.<hex_hmac> over a domain tag, timestamp, length-prefixed normalized x-llm-d-epp-profile, and exact body bytes (supporting segmented gRPC frames) within maxClockSkew (default 60s, min 1s).cmd/coordinator/main.go, pkg/coordinator/config/config.go, pkg/coordinator/gateway/client.go, pkg/coordinator/steps/decode_proxy.go, pkg/coordinator/pipeline/context.go): GatewayConfig adds auth_secret_env / auth_secret_file; gateway.Client.SignRequest signs HTTP Request, StreamGRPC, and newDecodeProxyRequest calls; internalForwardingHeaders strips client-supplied x-llm-d-trusted-caller-auth, httplog.RedactedHeaders redacts it, and passthrough never signs.apix/config/v1, apix/config/v1alpha1, pkg/epp/config/loader, pkg/epp/handlers/request.go, pkg/epp/util/request/headers.go, pkg/epp/requestcontrol/director.go): requestHandler.trustedCallerAuth (mutually exclusive with trustCaller) wires *reqcommon.TrustedCallerAuth into Director. CallerAuthHeaders keeps x-llm-d-trusted-caller-auth on ingress for verifyTrustedCaller (skipped when x-llm-d-unsanitized-body: true) and always strips it via IsSystemOwnedHeader and eppOwnedHeaders even when forwardInputControlHeaders is enabled. A once-per-Director warning logs if transfer fields are sanitized on a request carrying x-llm-d-epp-profile./v1/chat/completions, strips any client x-llm-d-trusted-caller-auth, runs prefill, and constructs the decode body containing kv_transfer_params.newDecodeProxyRequest sets x-llm-d-epp-profile: decode and calls gwClient.SignRequest(proxyReq, bodyBytes), stamping x-llm-d-trusted-caller-auth: v1=<ts>.<mac> using key 0.HandleRequestHeaders retains x-llm-d-trusted-caller-auth) and body (RawBody). Director.sanitizeClientFields detects kv_transfer_params, calls verifyTrustedCaller, verifies the timestamp and HMAC against RawBody and decode, and returns without mutating the body.generateHeaders and unsetRoutingHeaders omit x-llm-d-trusted-caller-auth and add it to RemoveHeaders so the downstream worker never sees the auth header.configloader.go:194, coordinator_architecture.md:382 - [medium] Loading the secret file or env var inside InstantiateAndConfigure couples static config validation (...Routing strategy (e.g., llm-d-router, llm-d-autoscaling), telemetry components (e.g., Kubernetes, framework metrics), projection tools (inference-sim, AIConfigurator, heuristic logic, etc.)
llm-d already provides workload-aware request routing and autoscaling through components such as llm-d-router and KEDA/HPA. However, these mechanisms do not currently coordinate runtime P/D layout changes based on evolving workload characteristics and SLOs. We propose several features that build on the existing routing and autoscaling infrastructure to improve cluster utilization and SLO attainment under dynamic traffic patterns.
At a macro level, traffic patterns may vary periodically with user behavior. For example, users may run more diverse workloads, such as coding, path finding, and RAG, during the day, potentially resulting in higher BS, ISL, and OSL. At night, workloads may shift toward CI workflows and short conversations, potentially resulting in lower BS and ISL, partly due to prefix-cache hits, and moderate OSL. Although this is only one illustrative scenario, it shows that a P/D ratio optimized for traffic pattern A may not be optimal for pattern B. In such cases, an xP-yD layout could potentially be adjusted at runtime to (x-n)P-(y+n)D.
At a micro level, smaller peaks and valleys may occur within these broader periodic traffic changes. For example, during a short window with low BS and concurrency, the overhead of Prefill โ KV transfer โ Decode may outweigh the isolation benefits of P/D disaggregation, since concurrent prefills are less likely to interfere with ITL. In a 1P-1D deployment serving batches of one or two requests, two aggregated workers may therefore perform better. This motivates evaluating whether an xP-yD layout could temporarily transition to (x+y)M, where M denotes an aggregated worker that handles both prefill and decode.
Here are two features that we would like to work on, and please let us know if there are any existing studies or ongoing research that we are missing:
Current framework status:
vLLM: P/D instances can be launched symmetrically with kv_both, 43807 aims to deprecate this, but this is not definite.
sglang: P/D instances are launched with --disaggregation-mode, but it already supports runtime role switching 28403. However, a manual curl http://<inst>:8000/pd_role_switch request is currently required to trigger the flip, for any single instance. The instance must first be drained to idle, and the role transition must currently be triggered by an external operator or controller for correctness.
We will firstly leverage vLLMโs symmetric kv_both semantics to avoid role-specific KV-transfer structures within the serving framework, allowing instances to switch logical roles without becoming fully idle while preserving correctness.
Here we note a deployment as p_AtpX_d_BtpY_m_CtpZ: A prefill instances with TP=X (tensor parallel size X), B decode instances with TP=Y, and C mixed/aggregated-role instances with TP=Z
<img width="663" height="299" alt="Image" src="https://github.com/user-attachments/assets/1dda3ffe-4622-413d-8b01-142324650cd6" />
As shown above, we will implement three functionalities:
FIND_TRANSFER_GROUP: Find transferrable layout groups for the current deployment layoutPREDICT_THROUGHPUT: Plan the optimal layout based on runtime metrics and projected performance under the target layout.APPLY_LAYOUT: Execute workload-aware switching with the elastic LLM router.Our code change is currently adapted from a handwritten round-robin router (and should be possible to migrate to llm-d-router). We periodically fetch the vLLM metrics and calculate the current ISL/OSL/BS. Then, we use a projection tool to get the estimated performance when the ISL/OSL/BS pair varies. If the throughput gain is larger than the threshold, we switch to a new P/D ratio.
Our initial experiments:
<img width="975" height="542" alt="Image" src="https://github.com/user-attachments/assets/3f9466a9-54fb-43c9-8d12-cc76f71370dc" />
This shows that the proposed PD-switch mechanism can adapt to workload changes during the runtime lifecycle without restarting the serving system. By dynamically selecting workload-specific P/D layouts, it follows the best fixed configuration for each workload phase and maintains near-optimal throughput over the entire execution period.
Under low concurrency, the existing P/D disaggregated architecture might be suboptimal. As mentioned above, the router might see P/D as independent aggregated instances. This feature should also use FIND_TRANSFER_GROUP, but it involves another aggregated role that P/D instances can transfer to, which we denote as M.
Taking a cluster with n_gpus = 4 as an example, the 12 valid layouts can be partitioned into 4 transfer groups. Runtime P/D/M switching can be performed only among layouts within the same transfer group.
Total Groups: 4
--------------------------------------------------------------------------------
Group 1: 7 layouts
[003] p_none_d_none_m_4tp1
[005] p_1tp1_d_1tp1_m_2tp1
[006] p_1tp1_d_2tp1_m_1tp1
[007] p_1tp1_d_3tp1_m_none
[008] p_2tp1_d_1tp1_m_1tp1
[010] p_2tp1_d_2tp1_m_none
[011] p_3tp1_d_1tp1_m_none
--------------------------------------------------------------------------------
Group 2: 2 layouts
[001] p_none_d_none_m_2tp2
[009] p_1tp2_d_1tp2_m_none
--------------------------------------------------------------------------------
Group 3: 2 layouts
[002] p_none_d_none_m_2tp1-1tp2
[004] p_1tp1_d_1tp1_m_1tp2
--------------------------------------------------------------------------------
Group 4: 1 layout
[000] p_none_d_none_m_1tp4
p_2tp1_d_2tp1_m_none (2 Prefill with TP1 + 2 Decode with TP1) can be transferred to p_none_d_none_m_4tp1 (4 TP1 aggregated/mixed-role workers) at runtime without a restart.
We are currently working on further experiments on this, and any feedback is welcome.
P <-> D graph requires a recapture as shown in sglang's 28403I would like to contribute PRs.
NA
Addresses the Agentic serving (guides/agentic-api) portion of #1982 (per-guide observability and troubleshooting for well-lit paths). This PR covers only the Agentic API guide and does not close the broader tracking issue.
Add an Observability & Troubleshooting section to the Agentic API guide to make it easier to diagnose failures across the Agentic API, PostgreSQL, routing, and inference components.
kubectl commands to inspect deployments, PostgreSQL PVC status, and container logs.verify.py stages to targeted troubleshooting steps:function_call responsespython scripts/guide.py render guides/*/ guides/models/*/ guides/fast-model-actuation/fast-model-actuation-keda/ guides/batch-serving/asynchronous-processing/multitenant/ --checkpython scripts/guide.py check-manifest docs/well-lit-paths/guides.yamlDocumentation-only change; no runtime behavior or deployment configuration changes.
Adds an Observability & Troubleshooting section to guides/agentic-api/README.md mapping the 4 stages of verify.py to specific diagnostic steps across the Agentic API, PostgreSQL, router (EPP), and model-server components.
Structured as a 3-part troubleshooting guide: (1) a high-level signal matrix detailing observable metrics and log locations across agentic-api, postgres, vLLM, and EPP; (2) inspection commands for deployments, PVCs, logs, and transient debug logging rollouts; and (3) a stage-by-stage failure triage covering verify.py stages [1/4] through [4/4], distinguishing database persistence issues from model refusal behavior and WebSocket transport limitations.
When verify.py fails at stage [2/4] on conversation follow-up, the guide instructs the operator to check the Turn 1 response ID via GET /v1/responses/{response_id}: a successful retrieval proves PostgreSQL stored the turn (pointing to model prompt/reconstruction behavior), whereas a 404 indicates database persistence failure.
Design Doc: Session State Unification Design Proposal
What would you like to be added:
Unify per-session and per-endpoint session tracking into a shared SessionStateRegistry with a three-tier state architecture, DynamicRequestAttribute support for pre-FlowControl live access, and a SessionWriter / SessionReader capability split.
Why is this needed:
Three plugins maintain separate, overlapping session stores:
session-state-producer (#2531)thunder-agent (#2968, #3052, #3076)program-aware-fairnessDuplicating session tracking across plugins fragments lifecycle management, complicates reasoning about cross-plugin interactions, and prevents new session-aware plugins from building on a common foundation.
SessionStateRegistry as the foundational building block for existing and future session-aware plugins.DynamicRequestAttribute so admission, fairness, and scheduling plugins read consistent state.SessionWriter / SessionReader interface split so consumers cannot mutate shared session state.InferenceRequest): Per-request and per-turn attributes, including DynamicRequestAttribute for live pre-FlowControl lookups.SessionState + EndpointFootprint): Ground-truth session metadata and per-endpoint footprint tracked in SessionStateRegistry.EndpointSessionSummary): Aggregated per-endpoint session view with SessionIDs for fast scheduling and fairness evaluation.DynamicRequestAttribute and core request/attribute abstractions needed for pre-FlowControl live access.SessionStateRegistry & session-state-producer: Implement SessionStateRegistry with the SessionWriter / SessionReader split, SessionState, EndpointFootprint, and EndpointSessionSummary (with SessionIDs), and wire session-state-producer as the writer.program-aware-fairness and thunder-agent to read from SessionStateRegistry via SessionReader and remove their redundant session stores.main (62087d92) found that the per-request cost is dominated by a deep clone of every endpoint's attribute map when the scheduler snapshot is built, and that the...A performance review of the EPP request and response hot paths on main (62087d92) found that the per-request cost is dominated by a deep clone of every endpoint's attribute map when the scheduler snapshot is built, and that the per-token response path allocates and copies on every chunk when a model rewrite is active. This issue tracks ten items, ranked, with the numbers that back each one.
This is the EPP counterpart of #3960 (coordinator JSON pipeline). #3906 did the same for the coordinator's SGLang gRPC path. Item 3 below shares a helper with #3960 item 3.
pkg/epp were run with -benchmem (Go 1.26.8). Numbers below come from them unless marked new.handlers, parsers, requestcontrol, scheduling, approximateprefix, datalayer, flowcontrol.FULL_DUPLEX_STREAMED mode (config/charts/llm-d-router-standalone/values.yaml:280-286) with no in-code override, so every request body chunk and every response chunk passes through the EPP.These should stay:
sync.Pool of bytes.Buffer (handlers/server.go:459-464). releaseRequestBody drops the body after it is forwarded, so an in-flight stream does not hold it. BenchmarkProcessInFlightRetainedHeap guards this.messages, prompt, input, and instructions as raw bytes that alias the body (parsers/util/json.go:99-124) and forwards the original bytes when nothing changed.Prompt.UnmarshalJSON parses a flat token array in 2 allocations for 1M tokens.unsafe.Slice view of the tokens with no per-block allocation (prefixhash/hashing.go:107-135). The custom LRU takes 560 allocations for 72k entries against 72k for simplelru.usage before it parses. The SSE line carry copies only a split tail.TestHandleResponseBodyAllocs caps the director's per-response allocations. BenchmarkRetainedHeap tracks the indexer's memory at capacity.| Stage | Measured | Notes |
|---|---|---|
Parse chat request, 8K-token text (OpenAIParser_ChatCompletions/Text/ISL8K/ParseRequest) | 77 KB, 50 allocs, 241 ยตs | About 2ร the body: one typed decode that copies all message text, plus one raw clone |
| Parse chat request, 32K tokens, 32 turns | 296 KB, 148 allocs, 1.0 ms | |
| Parse chat request, 128K tokens | 1.08 MB, 50 allocs, 3.4 ms | Typed decode alone is 1.07 MB in 7 allocs |
Re-encode on model rewrite, 24 KB string prompt (ParseRequestAndRewrite/String/24KiB minus ParseRequest/String/24KiB) | +28 KB, +12 allocs | json.Marshal of the payload map clones and reformats each raw field on Go 1.26 |
| Re-encode on model rewrite, 32K token IDs | +220 KB | Token IDs re-encoded as JSON digits |
Scheduler snapshot, 100 endpoints, 0 attributes (ToSchedulerEndpoints/endpoints=100) | 9.8 KB, 201 allocs, 8 ยตs | The existing benchmark |
| Scheduler snapshot, 100 endpoints, 8 attributes (new) | 119 KB, 2,748 allocs, 177 ยตs | attr.Clone() per endpoint |
| Scheduler snapshot, 100 endpoints, 16 attributes (new) | 241 KB, 5,472 allocs, 348 ยตs | |
Prefix producer + PreRequest, 100 candidates (ProduceThenPreRequest/candidates=100) | 81 KB, 977 allocs, 117 ยตs | About 10 allocs per candidate |
Prefix producer, 96 pods (Produce/hotspot/pods=96) | 51 KB, 420 allocs, 105 ยตs | About 4 allocs per pod |
Schedule, 100 endpoints (Schedule/endpoints=100) | 56 KB, 152 allocs, 119 ยตs | Allocation count flat in N, about 400 B per endpoint |
| Schedule, 25 endpoints | 20 KB, 152 allocs, 46 ยตs |
For a 100-endpoint pool with a typical attribute set, the scheduler snapshot alone costs more allocations than parsing, prefix matching, and scheduling together.
| Site | Per chunk | Notes |
|---|---|---|
director.HandleResponseBody + streaming plugins (BenchmarkHandleResponseBody, 10 chunks) | ~5 allocs, 670 B | One Response struct, a mutex, a send on a 100-slot channel |
generateResponseBodyResponses + BuildChunkedBodyResponses (handlers/response.go:263-282) | ~7 allocs | Protobuf wrappers; chunk bytes are sliced, not copied |
rewriteModelName (handlers/server.go:1018-1034) | 2-4 allocs + 1-2 scans, full chunk copy on match | Only when TargetModelName != IncomingModelName. Every OpenAI chunk carries "model":"...", so the copy runs on every chunk |
RecordInterTokenLatency (handlers/response.go:70-77, metrics/metrics.go:376-386) | 3 global RWMutex.RLock + 5-label WithLabelValues | Plus an exemplar map when the span is sampled |
extractUsageStreaming (parsers/openai/openai.go:786-831) | 1 json.Unmarshal per data: line containing usage | With stream_options.include_usage, vLLM sends "usage":null on every chunk, so every chunk is parsed |
completeSSELines | 0-2 allocs | Only when a line is split across chunks |
extractFairnessAndPriority | 1 alloc when priority >= 100 | strconv.Itoa per chunk |
sglanghttp streaming usage (parsers/sglanghttp/sglanghttp.go:298-325) | 2-3 copies of the whole chunk + a []string | string(body), strings.Split, []byte(data) per line |
Rough total for an OpenAI chat stream with a model rewrite and include_usage: about 20 allocations, one chunk copy, and one JSON parse per token.
Where: pkg/epp/requestcontrol/director.go:662-669 โ pkg/epp/framework/interface/scheduling/types.go:140-150 โ pkg/epp/framework/interface/datalayer/attributemap.go:137-146.
Problem: NewEndpointFromSnapshot calls attr.Clone(), which builds a new sync.Map and Puts a clone of every value. The datalayer extractor writes one scalar attribute per extracted metric per poll (extractor/metrics/extractor.go:268-273), and the prefix producer writes its match data, so K is about 8 to 16 in a normal deployment. The comment on NewEndpointFromSnapshot says attributes are cloned because data producers write per-request values into the scheduling endpoint.
Cost: 100 endpoints ร 16 attributes: 241 KB, 5,472 allocations, 348 ยตs per request, before any plugin runs. BenchmarkToSchedulerEndpoints uses endpoints with no attributes and reports 201 allocations, which is why this did not show.
Fix: copy on write. The scheduling endpoint keeps a read-only reference to the shared per-pod map and an overlay for per-request writes. Put writes the overlay. Get and Peek check the overlay, then the base. Only data producers write per request, and they write few keys. Add an attribute count to BenchmarkToSchedulerEndpoints (0, 8, 16) so the benchmark tracks the real cost, and add an allocation ceiling test.
Risk: a plugin that mutates a value obtained from Get in place would affect the shared map. Today Get returns a clone, so in-place mutation is already unsafe to rely on, and the overlay keeps that contract.
Where: pkg/epp/datalayer/endpoint_scope.go:312-343, pkg/epp/datalayer/request_scope.go:77-111, pkg/epp/datalayer/endpoint_scope.go:274-293, pkg/epp/scheduling/scheduler_profile.go:256-272, pkg/epp/framework/plugins/scheduling/scorer/queuedepth/queue.go:89-118.
Problem: Each plugin call (filters, scorers, data producers, screeners, admitters, pre-request, response hooks) goes through ScopeInvocation or ScopeRequest: about 6 allocations, 2 to 3 slices of N ([]ScopedEndpoint, []Endpoint, Unscope), a TypedName().String() concatenation, and a global scopeSpecsMu.RLock. Each scorer returns a map[Endpoint]float64 keyed by an interface value, merged into another map. queuedepth builds two maps.
Cost: with 10 plugins and 100 endpoints, about 30 slices of 100 pointers and 60 small allocations per request, plus one map of N per scorer. BenchmarkSchedule/endpoints=100: 56 KB per request.
Fix: cache the *scopeSpec on the plugin instance or in a slice indexed by plugin position, which removes the concatenation and the global lock. Allocate the wrapper array and the scoped slice once per request and reuse them across plugins at the same extension point. Return scores as an index-aligned []float64 and merge by index.
Where: pkg/epp/framework/plugins/requesthandling/parsers/openai/openai.go:159-169, pkg/epp/framework/plugins/requesthandling/parsers/util/json.go:51-124, pkg/epp/framework/common/request/types.go:67. The Anthropic parser (parsers/anthropic/anthropic.go:93,114-116) has the same three passes.
Problem: extractRequestBody does a full typed json.Unmarshal that copies all message text and media into Go strings. UnmarshalEnvelope then runs json.Valid (pass 2) and a hand-rolled top-level split (pass 3). On a model rewrite, priority rewrite, or any other mutation, PayloadMap.Marshal runs json.Marshal on the map, which on Go 1.26 clones and reformats every RawMessage (pass 4, plus a body-sized allocation).
Cost: parse is about 2ร the body in allocations (1.08 MB for a 128K-token chat). The rewrite adds about 1.1ร the body for text prompts and 1.7ร for token-ID prompts.
Fix: fold validation into the split, or use jsontext.Decoder offsets to find top-level fields in one pass. On mutation, splice the changed top-level fields into the original bytes instead of re-marshaling the map. This is the same helper as #3960 item 3. The typed decode is harder to avoid because downstream code uses the typed messages. Check whether messages can be decoded lazily, since many requests only need model, stream, and token-count fields on the request path.
rewriteModelName builds its needles and scans on every response chunkWhere: pkg/epp/handlers/server.go:858 and :1018-1034.
Problem: When the target model differs from the client's model name, each chunk pays two to four string concatenations and []byte conversions, one or two bytes.Contains scans, and a bytes.ReplaceAll copy of the whole chunk. OpenAI chunks all carry the model field, so the copy runs on every chunk.
Fix: precompute the old and new byte slices once per request when the names differ, and store them on RequestContext. Replace in place when the lengths are equal. Otherwise use one bytes.Index and two appends into a reused buffer.
Test: an allocation test on a chunk with a model rewrite asserts at most one allocation (the output buffer) per chunk.
include_usage is setWhere: pkg/epp/framework/plugins/requesthandling/parsers/openai/openai.go:786-852.
Problem: The guard is bytes.Contains(content, "usage"). vLLM emits "usage":null on every chunk when stream_options.include_usage is true, so every chunk is unmarshaled into a struct with RawMessage fields, which copies the usage bytes. The final usage block is then parsed three times: the RawMessage copy, json.Marshal(map{"usage": raw}) in extractRawUsage, and extractUsage.
Fix: extend the guard to skip "usage":null and "usage": null. Decode the usage object directly from the RawMessage instead of wrapping it in a map and re-marshaling.
Test: an allocation test on a content chunk with "usage":null asserts zero JSON work (the existing openai_extractusage_test.go covers the semantic cases).
Where: pkg/epp/flowcontrol/controller/internal/processor.go:226-275 and :484-606.
Problem: dispatchCycle runs once per dispatched item and on a 1 ms ticker. Each run calls Locate (a PodList slice copy of N), partitions endpoints into three slices, calls the saturation detector two or three times over all endpoints, and writes about eight gauges. All of it runs on one goroutine, which is the serialization point for every admitted request.
Fix: compute the endpoint partition and saturation once per tick and reuse them for every item dispatched in that tick. Dispatch more than one item per cycle when capacity allows. Skip the work on an idle tick when the queues are empty.
Measure first: this was read, not measured. A benchmark that enqueues 1,000 items against 100 endpoints and measures the processor's allocations and time per dispatched item would size the gain.
Where: pkg/epp/handlers/request.go:215-225, pkg/epp/handlers/response.go:309-319, pkg/epp/handlers/server.go:644-646,659, pkg/epp/handlers/request.go:48,64,79.
Problem: On each request and each response, the EPP sends every non-system header back as a SetHeaders mutation: a []byte(value) copy plus two protobuf structs per header, with strings.ToLower and four set lookups per header in IsSystemOwnedHeader. Envoy then re-applies headers that did not change. Before that, the inbound header list is iterated about six times (:path, request ID, trace context, method, WebSocket check, copy into the map), each pass with strings.ToLower per key.
Fix: set only the headers the EPP added or changed. Lowercase once into reqCtx.Request.Headers and read the special headers from that map.
Where: pkg/epp/handlers/response.go:70-77, pkg/epp/metrics/metrics.go:376-386, pkg/common/observability/metrics/cardinality.go:60-70.
Problem: RecordInterTokenLatency takes three global read locks in the label limiters and hashes five labels on every chunk. RecordPluginProcessingLatency does the same per plugin per chunk.
Fix: resolve the prometheus.Observer children once per request after the labels are known and keep them on RequestContext. The per-chunk call becomes one Observe.
Where: pkg/epp/framework/plugins/requesthandling/dataproducer/approximateprefix/plugin.go:311-359, approximateprefix/indexer.go:102-125, pkg/epp/framework/plugins/scheduling/scorer/prefix/plugin.go:134-181, approximateprefix/plugin.go:515-560.
Problem: Produce writes a PrefixCacheMatchInfo into every candidate's attributes with Put, which clones the value (2 allocations per endpoint). MatchLongestPrefix builds two slices of N and takes a read lock per pod. The prefix scorer reads the value back with Get, which clones again, and once more in anyMMHit when tracing. PreRequest starts a goroutine per request that holds the pod's write lock while it adds every block hash.
Cost: ProduceThenPreRequest/candidates=100: 81 KB, 977 allocations, 117 ยตs.
Fix: keep the per-request match results in the plugin's scheduling context state (which already exists) and read them by index in the scorer, instead of round-tripping through the cloning attribute map. Batch the Add calls under the write lock so readers interleave.
sglanghttp streaming usage copies each chunk to a string, splits it into a []string, and copies each data line back to []byte (parsers/sglanghttp/sglanghttp.go:298-325). Use bytes.SplitSeq as the OpenAI parser does.Prompt.UnmarshalJSON falls back to json.Unmarshal into []any when any token is written in a non-canonical form such as 12345.0. The fallback costs 112 bytes and 2 allocations per token (PromptUnmarshalJSONTokenIDs/Fallback/1M: 112 MB, 2M allocs). A client that sends floats pays 28ร the memory of one that sends integers. Make the fast path tolerate a .0 suffix, or cap the fallback.dataproducer/tokenizer/estimate.go:343-372, 625-636).context.WithTimeout per request (requestcontrol/plugin_executor.go:88-118). With few producers a sequential run under one deadline is cheaper.prepareRequest builds a map[string]float64 with a net.JoinHostPort string per endpoint on every request (requestcontrol/director.go:607-614), used only when emitEndpointScores is on.proto.Unmarshal (parsers/vllmgrpc/vllmgrpc.go:230-231).RawBody (handlers/server.go:694-696, kept pristine for the tool-calling comparison), and protobuf marshal on send. The RawBody copy can be skipped when tool-calling telemetry is off.BenchmarkProcessInFlightRetainedHeap/body=64KiB: 64 streams retain 9 MB, about 140 KB per stream, most of it the typed decode and the payload map.BenchmarkRetainedHeap/pods=96: 320 MB at the benchmark's settings). By design. The per-entry size is what to watch when block size or capacity changes.requestcontrol/director.go:767-779).No leak found in the paths read.
Director and scheduler. The pieces exist: handlers/server_request_buffer_test.go:44-130 has a fake ext_proc stream and body builders, and scheduling/scheduler_bench_test.go:30-110 has a scheduler fixture. Wiring them together with -memprofile gives one number per request and catches what per-stage benchmarks miss.Metrics.Clone, one attribute Put per metric; source/metrics/datasource.go:202-237, extractor/metrics/extractor.go:130-273) was read but not measured. At 100 pods that is 2,000 expfmt parses per second. Background load, not request latency, but it is the steady-state CPU floor.Item 1 (new benchmark, add to pkg/epp/requestcontrol/director_bench_test.go):
func BenchmarkToSchedulerEndpointsWithAttrs(b *testing.B) {
for _, k := range []int{0, 8, 16} {
for _, n := range []int{25, 100} {
endpoints := makeBenchmarkDatastoreEndpoints(n)
for _, ep := range endpoints {
for i := range k {
ep.GetAttributes().Put(
attrmetrics.ScalarMetricDataKey(fmt.Sprintf("metric_%d", i)),
attrmetrics.ScalarMetricValue(float64(i)))
}
}
director := &Director{}
b.Run(fmt.Sprintf("attrs=%d/endpoints=%d", k, n), func(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
_ = director.toSchedulerEndpoints(endpoints)
}
})
}
}
}
Everything else: go test -run '^$' -bench . -benchmem ./pkg/epp/... and read the benchmarks named in the tables.
pkg/kvevents and sglanghttp-parser (#3991, PR #3992): SGLang sgl-project/sglang#47120 removed caller mm_hashes overrides on internal multimodal cache identities.What would you like to be added:
Support SGLang multimodal prefix-cache affinity across pkg/kvevents and sglanghttp-parser (#3991, PR #3992):
pkg/kvevents/engineadapter/sglang_adapter.go, decode caller multimodal routing spans (BlockStored.mm_routing_spans, sgl-project/sglang#45737) into ExtraKeys. SGLang reports the spans in the dynamo KV-event format only. precise-prefix-cache-producer then matches SGLang multimodal KV blocks across gRPC and HTTP routes.sglanghttp-parser, extract mm_hashes and placeholder spans into MultiModalFeatures as an HTTP /generate follow-up.sglanghttp-parser ParseResponse, increment StreamedEvents on SSE chunks and enable sglanghttp-parser in default SGLang profiles.Why is this needed:
SGLang sgl-project/sglang#47120 removed caller mm_hashes overrides on internal multimodal cache identities. Merged PR sgl-project/sglang#45737 reports caller mm_routing_labels in the KV events of Python workers instead, and sgl-project/sglang#48705 tracks the request field on sglang.api.v1. SGLang also scopes the prefix cache of a multimodal request to its ordered media set, so requests with different media share no prefix. Today sglang_adapter extracts cacheSalt only (sglang_adapter.go:173-174), and sglanghttp-parser ignores mm_hashes. Without both updates, SGLang multimodal requests miss precise prefix-cache affinity in EPP.
llm-d-router when prefix-cache-affinity-filter interacts with load_override after prefill worker failures:.Robert Shaw reported a cascading overload in llm-d-router when prefix-cache-affinity-filter interacts with load_override after prefill worker failures:
no_match), migrated to surviving or replacement endpoints, and created a localized load spike.maxTTFTPenaltyMs, the filter triggered load_override and bypassed prefix affinity.load_override decisions across the pool (overload -> load_override -> overload).load_override disabled (maxTTFTPenaltyMs: 0).prefillThroughput mode, Plugin.endpointTTFT divides only InFlightLoad.Tokens by PeakPrefillThroughput. It ignores UncachedRequestTokens, which InFlightLoadProducer.Produce already writes on each endpoint. For a long prompt cached on sticky endpoint S, Plugin.Filter can spill to cold endpoint C even when C's full prefill exceeds S's queue delay.Plugin.Filter compares bestStickyTTFT - bestNonStickyTTFT against MaxTTFTPenaltyMs. It checks neither cold endpoint load nor pool saturation, so it still breaks affinity when cold candidates are already congested. At the default peakPrefillThroughput (15928 tokens/s), maxTTFTPenaltyMs: 5000 equals 79,640 tokens, so one 80K cold spillover pushes its target past the threshold.Plugin.Filter returns all endpoints on load_override. WeightedRandomPicker.Pick then scatters concurrent requests for one hot prefix across all cold endpoints. Even with token-load-scorer and max-score-picker, precise-prefix-cache-producer defaults to speculativeIndexing: false (or a fixed 2s TTL). Request 1 adds full uncached tokens to C1 while C1 still reports zero cached blocks until prefill finishes. Subsequent requests for that prefix then spill across C2, C3, and the rest of the pool.load_override. injectFilterIntoProfiles appends utilization-detector after prefix-cache-affinity-filter. While affinity holds on [S], utilization-detector fails open and keeps [S]. Once load_override returns [S, C1, C2], utilization-detector drops S above QueueDepthThreshold (5) or KVCacheUtilThreshold (0.80). TokenLoadScorer.Score then never sees S, even when S would finish faster than a cold prefill on C1.no_match prefills for orphaned prefixes. Replacement endpoints simultaneously join the pool with InFlightLoad.Tokens == 0 and empty caches. Those empty endpoints force bestNonStickyTTFT to zero and pull load_override traffic from warm endpoints across the cluster.prefixcacheaffinity): Add UncachedRequestTokens to endpointTTFT so a cold endpoint pays for its full uncached prefill. Scale uncached tokens by 1 + alpha (alpha >= 0) to price cluster compute taken from later requests. In latencyPredictor mode, add only alpha * deltaUncachedTokens / PeakPrefillThroughput.prefixcacheaffinity): Require low cold-endpoint backlog (bestNonStickyBacklogMs <= maxSpillTargetTTFTMs) and low KV cache usage before load_override. Also require spare aggregate pool capacity before load_override fires. When peers are busy, keep sticky so requests pay cached prefill cost instead of extra cluster load.sticky + k via Rendezvous hash): On load_override, append at most maxSpillEndpoints (default 1) chosen deterministically from the request's prefix block hash. Spilled requests for one prefix then warm a single secondary endpoint and leave unrelated KV caches intact.load_override to a fraction of pool prefill throughput (10% to 15%). Charge uncached(selected) - uncached(bestSticky) in PreRequest only when the picker selects a non-sticky endpoint (as in #3927). When the bucket is empty, keep sticky and record a throttled decision outcome.preciseprefixcache, approximateprefix, inflightload): Retain pending prefix block keys from PreRequest until StartOfStream plus a short event-delivery grace window. Roll back pending keys immediately on RequestAbandoned or error responses. Update approximateprefix synchronously in PreRequest instead of in a background goroutine. Discount prefix blocks already in flight on the same endpoint in InFlightLoadProducer so concurrent requests coalesce.EndpointNotificationSource): On EventDelete, pause load_override or tighten the token bucket briefly while orphaned prefixes re-home once. When EventAddOrUpdate adds a new endpoint, cap concurrent cold spillovers onto that endpoint until its cache warms.sticky endpoints through utilization-detector after load_override so token-load-scorer can still pick S. With p2p-source-producer, apply separate override thresholds for confirmed P2P pulls (ReusablePrefixTokens > 0) and cold recomputes (ReusablePrefixTokens == 0).#4042. We now have #3514, #3421, #4846, #4780, and #3465...".POST /generate requests into sglang.api.v1.SglangService/Generate worker calls in Coordinator (Coord-Tok-Tok, #3991, PR #3992).What would you like to be added:
Translate HTTP POST /generate requests into sglang.api.v1.SglangService/Generate worker calls in Coordinator (Coord-Tok-Tok, #3991, PR #3992). This is a low-priority follow-up to #3901, and it mirrors the vLLM translation in #4013:
pipeline.worker_protocol: grpc (#4013) to SGLang pipelines, with http as the default.worker_protocol: grpc, build sglang.api.v1.GenerateRequest from the HTTP /generate JSON body (#3775). Follow the sglang.json.v1 field options in pkg/common/grpc/sglang/gen/jsonv1 for the JSON mapping.prefill and decode through the sglang.api.v1 worker steps of #3906.GenerateStreamItem frames into the HTTP /generate JSON and SSE responses, and map gRPC status codes to HTTP status codes.Why is this needed:
Coordinator disaggregates native sglang.api.v1.SglangService/Generate requests (#3906). PR #3775 registers HTTP POST /generate with HTTP workers. Coordinator cannot serve HTTP /generate from a pool of sglang.api.v1 workers. PR #4013 adds the same translation for vLLM, from POST /inference/v1/generate to vllm.Inference. Issue #3901 listed this translation as a follow-up that depends on user demand.
This translation also blocks SGLang Loopback mode (#4828) on sglang.api.v1 worker pools until sgl-project/sglang#45816 lands. Before sgl-project/sglang#45816, sgl-router sends HTTP POST /generate calls to the Coordinator callback listener.
needs-triage and no assignee/linked PR (by @ahg-g); assign owner or confirm scope.precise-prefix-cache-routing leave replaySocketPort unset, with a comment that SGLang has no replay buffer.The SGLang overrides for precise-prefix-cache-routing leave replaySocketPort unset, with a comment that SGLang has no replay buffer. SGLang's ZMQ publisher has had one since at least v0.5.6 - replay_endpoint in --kv-events-config binds a ROUTER socket that serves the buffered events, and the router's replay client reads it as is. On 11-18 a fresh router pool attached through that socket on an SGLang nightly rebuilt the same index as the live stream.
Without it a router restart or a subscriber reconnect leaves the pod's index empty until blocks are stored again, so the router misses whatever the pod already holds.
Suggested change:
"replay_endpoint":"tcp://*:<port>" to the SGLang --kv-events-config and expose the portpodDiscoveryConfig.replaySocketPort to match and drop the commentSeparately, the --page-size comment says it must match blockSizeTokens. That is true on router main today. With llm-d/llm-d-router#4466, a page size smaller than blockSizeTokens that divides it also works, including SGLang's default of 1, so the comment can be relaxed once that lands.
llm-d main, guides/precise-prefix-cache-routing (SGLang modelserver patch and precise-prefix-cache-routing.sglang.values.yaml).
Guides - precise prefix cache routing, SGLang.
kv_transfer_params, ec_transfer_params, forwarded prompt_token_ids) without trusting every caller that can reach it (part of #3979).What would you like to be added:
A way for an EPP behind the Coordinator to keep the fields the Coordinator writes (kv_transfer_params, ec_transfer_params, forwarded prompt_token_ids) without trusting every caller that can reach it. Today the only option is requestHandler.bodyFieldsSanitizationPolicy: trustCaller, which trusts the request body of anything that reaches the EPP's gateway listener.
Why is this needed:
Since #4583 (part of #3979), an EPP strips caller-supplied prompt token and KV transfer fields on text routes by default. That is right for the client's initial request, but the Coordinator's own prefill and decode calls also reach the EPP on the same text routes (use_openai_format, and decode always uses the client's path), carrying fields the Coordinator wrote. So every EPP behind a Coordinator has to choose one of two options:
strip: P/D silently stops working. The prefill call loses do_remote_decode, the prefill worker returns no kv_transfer_params, and the decode worker recomputes the whole prompt rather than pulling KV over NIXL. forward_prompt_token_ids is also lost, so the workers render the prompt again. Requests still succeed. The only signal is llm_d_epp_body_fields_sanitized_total, which is easy to miss. We hit this when moving a P/D deployment (Coordinator + prefill EPP + decode EPP, NIXL) to an EPP built after #4583: decode workers reported 0 NIXL transfers and all prompt tokens as local_compute. trustCaller on both EPPs fixed it.trustCaller: the EPP trusts any request that reaches it without x-llm-d-unsanitized-body. The docs say to "use trustCaller only when clients cannot reach the EPP directly", but in a standard layout the Envoy listener in front of the EPPs (the one the Coordinator calls) is a plain in-cluster port. Any pod that can reach it can send its own kv_transfer_params or prompt_token_ids and they go to the worker. The trust is implicit: a request is trusted when the "untrusted" marker is absent.Trusting the decode EPP alone is not enough: the prefill call carries kv_transfer_params (do_remote_decode: true) too, so both EPPs need trustCaller.
What we want: the client's initial request is always sanitized (at the Coordinator, which already does this by default), and the EPP trusts body fields only on calls that provably come from the Coordinator.
Possible approaches:
trustCaller, trust only the fields the Coordinator's configured steps write (for example kv_transfer_params on a call with x-llm-d-epp-profile: prefill|decode), and keep stripping input_ids and render fingerprints.Separately, it would help if an EPP that sees x-llm-d-epp-profile (a Coordinator call) and strips kv_transfer_params logged a warning at startup or on first occurrence, because that combination always means P/D is broken.
Related: #3979, #4583.
needs-triage and no assignee/linked PR (by @robertgshaw2-redhat); assign owner or confirm scope.Coord-Text-Tok (text client, token-out worker) for SGLang in Loopback mode, using sgl-router as a pod-local frontend sidecar over loopback TCP (127.0.0.1) (fixes #4943).What would you like to be added:
Tracks delivery of Coord-Text-Tok (text client, token-out worker) for SGLang in Loopback mode, using sgl-router as a pod-local frontend sidecar over loopback TCP (127.0.0.1). Parent proposal: #3991, PR #3992 (docs/tokenize-once-at-ingress.md).
Prerequisite: Token passthrough foundation in #4837 (#3979, #4824, #4842, sgl-project/sglang#38075 / sgl-project/sglang#45249). Items tagged (shared) also apply to vLLM (#4838).
Already available today:
lmsysorg/sgl-router:nightly multi-arch distroless frontend image (docker/sgl-router.Dockerfile)/v1/responses in sgl-router (alongside Chat, Completions, and Messages over HTTP /generate)lmsysorg/sgl-router:nightly already lowers common text Chat, Completions, Messages, and Responses (tool_choice: auto/none, non-strict tools) and calls HTTP POST /generate on --worker-urls http://127.0.0.1:<port>.@GoyalIshaan, coordinates with RFC sgl-project/sglang#55055): call sglang.api.v1.SglangService/Generate with stream = true for HTTP clients so non-streaming requests emit first-token frames and remove the interim HTTP /generate bridge (#4253)@0x412e42): add required and named tool_choice, strict: true tools, tool grammar, and remaining reasoning and tool-call parsers in sglang-processorthinking.display="updates" on /v1/messages in sgl-router (currently HTTP 400)sglang-processor (content hashes, image_grid_thw, and placeholder spans without pixel tensors)MediaRef entries (or transfer grid metadata from prefill) on disaggregated decode so decode skips redundant media preprocessingdynamo-multimodal): add Rust frontend multimodal parity (non-Qwen-VL image families, video/audio, --encoder-urls EPD) and accept mm_routing_labels on sglang.api.v1 (after merged sgl-project/sglang#45737)@bojiang-li): add a strict flag that rejects un-lowered requests without worker OpenAI fallbackx-request-id and trace headers forwarded as gRPC metadata on lowered api.v1 calls, and carry the caller request ID on GenerateRequest.ridx-render-fingerprint on sglang.api.v1 and export the worker digest info metric@1eonyg): attach x-render-fingerprint metadata in sgl-router (computed via sgl-project/sglang#52594) and map RENDER_FINGERPRINT_MISMATCH to HTTP 409 Conflict instead of 400@sagearc, sgl-project/sglang#52967): separate endpoint selection from forwarding and make multi-endpoint routing optional at build time so the loopback sidecar omits routing statellm-dsgl-router, serve its HTTP and gRPC worker contract on 127.0.0.1, and reject un-lowered text routes on the callback listenerPOST /generate callbacks to sglang.api.v1 behind worker_protocol: grpcsglang.api.v1 callback listener once sgl-project/sglang#55024 lands) and #4830 (/v1/messages ingress registration).prefill, pass metadata-only MediaRef to decode, and route via EPP mm_hashes metadatamm_routing_labels in sglang_adapter and extract mm_hashes in sglanghttp-parser/v1/responses rejection, x-request-id validation, internal and client x-render-fingerprint removal, token-route bypass, configurable loopback endpoint, /v1/messages)x-render-fingerprint, and screen endpoints in EPP during rolloutstrustCaller, and warn if EPP strips kv_transfer_params on a Coordinator callrouter.coordinator.*), native sidecar over loopback TCP, /readyz gate, crash cleanup, and render_inflight admission control (coordinate with Coordinator resilience fixes #4943 / #4948 and #4945 / #4950)model block (including --incremental-streaming-output), CPU/memory sizing, and ContainerResource HPA (coordinate with #4876 / #4899 unified P/D router config)n > 1 parallel sampling on sglang-server (also in #4837)llm-d/tokenize, /detokenize, and /v1/messages/count_tokens from the local sidecar/v1/models, /health, and other HTTP paths on gRPC-only poolsWhy is this needed:
Tracks SGLang Coord-Text-Tok (Loopback) delivery separately from vLLM and passthrough, grouped by upstream SGLang versus llm-d across delivery milestones from basic text MVP through full multimodal and production readiness.
lmsysorg/sgl-router:nightly (multi-arch linux/amd64 and linux/arm64, distroless gcr.io/distroless/cc-debian12:nonroot, < 100 MB budget, passing nightly CI)./usr/local/bin/sgl-router as uid 65532) configured purely by CLI flags (docker/sgl-router.Dockerfile:114-124). No Python or helper processes run inside the container.Start sgl-router bound strictly to loopback, pointing at Coordinator's callback listener, with Coordinator's /server_info omitting KV-event publisher config:
--host 127.0.0.1 --port <frontend-port> --model-id <model> --worker-urls http://127.0.0.1:<callback-port> --policy round_robin --disable-circuit-breaker (plus aligned timeout flags).DiscoveryBackend::StaticUrls skips pod discovery, and start_peer_watch returns immediately (sgl-router/src/main.rs:341-343).KvEventIndex::add_worker (sgl-router/src/state/kv_events/index.rs:522-543), when /server_info advertises no KV-event publisher, it logs that the worker is not publishing and returns without creating any ZMQ SUB task.bootstrap_coordinator only spawns when --kv-peer-selector is set (index.rs:454-460).--policy cache_aware with indexer (main.rs:79,206-223)./health polling loop: sgl-router/src/health/mod.rs only wires the passive circuit breaker.--policy round_robin and no --dp-aware, dp_rank_prefix_provider, prefix_index, and radix_tree_prefix_provider are all None (main.rs:396-418), and pending-prefix and media-affinity tracking stay off (main.rs:419-444). Selection runs plain RoundRobinPolicy over the single backend (sgl-router/src/policies/factory.rs:50-58) with zero radix-tree lookups, zero block hashing, and zero cache scoring.main.rs:75-76): Loads local tokenizer.json or pulls from HuggingFace. Required for prompt lowering.sgl-router/src/server/app.rs:217-260): Serves Chat, Completions, Messages, Responses, /healthz, /readyz, /metrics, plus /workers admin CRUD routes (app.rs:231-241).WorkerManager (sgl-router/src/workers/manager.rs:266-365): Calls /server_info once at startup (plus one extra fetch_event_config check in KvEventIndex::add_worker because event_config is None, index.rs:525-533). Runs a 30 s reconcile tick (RECONCILE_INTERVAL, manager.rs:31) that skips already-resolved workers, costing one 1-entry map scan every 30 s.KvEventIndex pump_loop (index.rs:401-430,875): Always spawns alongside an empty HashTree, but receives zero events and only wakes on an idle timer over empty maps (negligible CPU and RAM).RouterInflightLoadRegistry + janitor (main.rs:320-332): Tracks in-flight requests and runs a sweep every 60 s by default (stale_request_timeout_secs / 10).sgl-router/src/health/circuit_breaker.rs:32-38, manager.rs:57): After 3 consecutive 5xx or timeout failures, the breaker opens for 30 s (503 BreakerOpen) and drops all traffic on that Coordinator pod.--disable-circuit-breaker (circuit_breaker.rs:80-86).manager.rs:31,213-227, main.rs:160): Kubernetes starts native sidecars before the main Coordinator container. If sgl-router calls /server_info before Coordinator binds its callback listener, the worker stays unresolved (empty model_ids) until the next 30 s reconcile tick, even though sgl-router already reports /readyz ready (main.rs:160).sgl-router/src/config/types.rs:59-87): Defaults are request_timeout_secs = 300, stream_idle_timeout_secs = 180, and stale_request_timeout_secs = 600 (the janitor force-cancels long reasoning or streaming requests with 504 stale_request_expired).app.rs:150-175,231-241):--host 127.0.0.1 so /workers CRUD endpoints (POST/PUT/DELETE /workers) are unreachable outside the pod.sgl-router access logs (http_request) alongside Coordinator and Envoy logs unless log level is tuned.--disable-circuit-breaker, raise or align the three timeout flags, bind strictly to 127.0.0.1, and handle the 30 s startup /server_info race.needs-triage and no assignee/linked PR (by @ahg-g); assign owner or confirm scope.Coord-Text-Tok (text client, token-out worker) for vLLM in Loopback mode, using vllm-rs (GrpcLlm, --remote-generation-url) as a pod-local frontend sidecar over loopback TCP (127.0.0.1) (fixes #4943).What would you like to be added:
Tracks delivery of Coord-Text-Tok (text client, token-out worker) for vLLM in Loopback mode, using vllm-rs (GrpcLlm, --remote-generation-url) as a pod-local frontend sidecar over loopback TCP (127.0.0.1). Parent proposal: #3991, PR #3992 (docs/tokenize-once-at-ingress.md).
Prerequisite: Token passthrough foundation in #4837 (#3979, #4824, #4924, vllm-project/vllm#67430 / vllm-project/vllm#67604). Items tagged (shared) also apply to SGLang (#4839).
Already available today:
main as vllm-project/vllm@c62590e002f2, PR closed manually): Rust server over caller-built LlmGrpcLlm remote vllm.Inference client (--remote-generation-url, loopback TCP http://127.0.0.1:<port> works today)/v1/messages, count_tokens, SSE envelopes), alongside Chat, Completions, and stateless Responsespresence_penalty and frequency_penalty over gRPC (optional float in inference.proto and remote-llm/src/convert.rs)num_cached_tokens and num_cache_creation_tokens on PromptInfo (plus initial GrpcLlm integration tests)vllm-rs image (GrpcLlm over http://127.0.0.1:<port> already works on main for basic text without structured outputs, LoRA, or media)GrpcLlm)@hickeyma): forward sampling_params.structured_outputs (with reasoning gate) and sampling_params.stream_interval in GrpcLlm@hickeyma): forward and decode output logprobs / logprob_token_ids and prompt_logprobs in GrpcLlmtop_logprobs, include) in the Rust frontend@MilkFeng): forward lora_request (lora_name) without requiring a local engine-core clientMediaItem entries and mixed marker_offset on vllm.Inference (after merged vllm-project/vllm#66928)GrpcLlm): forward mm_features as metadata-only MediaItem entries or raw_bytes with mm_hashes and placeholder spans without pixel tensors--allowed-media-domains, --media-io-kwargs, and --mm-processor-cache-gb on vllm-rs startup for egress-hardened multimodal deploymentsGenerateRequest.request_id (instead of overwriting with a fresh UUID) and forward selected request headers@shimib): compute Rust render_fingerprint, check x-render-fingerprint and export the worker digest info metric on vllm.Inference, and map RENDER_FINGERPRINT_MISMATCH to HTTP 409 Conflict instead of 400 in GrpcLlm (vllm-project/vllm#71356)@chenzl25, vllm-project/vllm#71356): carry stop_strings and skip_special_tokens from GrpcLlm to workers so EPP receives a normal FinishInfo frame instead of outcome="cancelled" on stop-string workloadsGenerateRequest for exact KV-cache routing without re-hashing@hickeyma): expand GrpcLlm integration tests across Chat, Responses, Messages, cancellation, and error mappingllm-d127.0.0.1 default) and serve the vllm.Inference and grpc.health.v1 callback listener (GrpcLlm watches vllm.Inference serving status)/v1/messages ingress registration).encode/prefill, handle mixed marker_offset, and route via EPP mm_hashes metadata/v1/responses rejection, x-request-id validation, internal and client x-render-fingerprint removal, token-route bypass, configurable loopback endpoint, /v1/messages)x-render-fingerprint, and screen endpoints in EPP during rolloutstrustCaller, and warn if EPP strips kv_transfer_params on a Coordinator callrouter.coordinator.*), native sidecar over loopback TCP, /readyz gate, crash cleanup, and render_inflight admission control (coordinate with Coordinator resilience fixes #4943 / #4948 and #4945 / #4950)model block across workers and sidecars, CPU/memory sizing, and ContainerResource HPA (coordinate with #4876 / #4899 unified P/D router config)unix:// UDS support for --remote-generation-url (http://127.0.0.1:<port> works today)--grpc-services (also in #4837)NixlConnector KV retention for n > 1 (also in #4837)n > 1 on vllm.Inference, plus GrpcLlm wiring in vllm-project/vllm#71356 (also in #4837)repetition_detection (worker merged in vllm-project/vllm#71663) and extra_args on vllm.Inference, plus GrpcLlm wiring in vllm-project/vllm#71356 (also in #4837)mm_processor_kwargs and media_io_kwargs on vllm.Inference (also in #4837)llm-d/tokenize, /detokenize, and /v1/messages/count_tokens from the local sidecar/v1/models, /health, and other HTTP paths on gRPC-only poolsnum_sequences > 1 on vllm.InferenceWhy is this needed:
Tracks vLLM Coord-Text-Tok (Loopback) delivery separately from SGLang and passthrough, grouped by upstream vLLM versus llm-d across delivery milestones from basic text MVP through multimodal and production readiness.
needs-triage and no assignee/linked PR (by @ahg-g); assign owner or confirm scope.Coord-Tok-Tok and EPP-Tok-Tok) across vLLM and SGLang. Parent proposal: #3991, PR #3992 (docs/tokenize-once-at-ingress.md).What would you like to be added:
Tracks delivery of token passthrough modes (Coord-Tok-Tok and EPP-Tok-Tok) across vLLM and SGLang. Parent proposal: #3991, PR #3992 (docs/tokenize-once-at-ingress.md).
llm-dprecise-prefix-cache-producer from backend: vllmvllm.Inference parsing, disaggregation, and UNAVAILABLE re-run (#4008, #4010, #4011, #4013, #4492)sglang.api.v1 parsing, Helm wiring, disaggregation, and retryable error re-run (#3904, #3906, #3907, #3908, #4582)disagg_prefill_dp_rankNetworkPolicy, and drop client transfer fields on EPP token gRPC routestrustCaller, and warn when EPP strips kv_transfer_params on a call with x-llm-d-epp-profilebootstrap_host, bootstrap_port, and bootstrap_room in external-text sanitization and on sidecar decode-only forwardsEPP-Tok-Tok sidecar): strip caller do_remote_prefill / kv_transfer_params on decoder-only vllm.Inference gRPC requests so NIXL decoders do not exitforward_response_headers when vLLM gRPC conditional-decode defersEPP-Tok-Tok sidecar gRPC): hold streaming decode output until prefill completes, cancel hung prefill promptly, and replace rather than append x-request-id on gRPC P/D pathsmm_routing_labels in sglang_adapter and extract mm_hashes in sglanghttp-parserUNAVAILABLE on KV and EC load failures in vllm.Inference--allowed-media-domains, --media-io-kwargs, and --mm-processor-cache-gb on vllm-rs startupgrpc.health.v1 on sglang-servermm_routing_labels on sglang.api.v1 (after merged sgl-project/sglang#45737)llm-d127.0.0.1 bootstrap_host workaround on SGLang gRPC prefill once SGLang supports unset bootstrap_hostPOST /generate mapping to sglang.api.v1 (worker_protocol: grpc, also blocks SGLang Loopback HTTP callbacks on gRPC workers in #4839)/v1/models, /health, and other HTTP paths on gRPC-only poolsnum_sequences > 1 on vllm.Inference (EPP, Coordinator, and P/D sidecar)/v1/completions batch token arrays ([][]int) in Coordinatorvllmgrpc-parser (deprecation tracked in #4800)--grpc-services so worker data ports omit vllm.ControlNixlConnector KV blocks until every n > 1 decode sequence reads themn > 1 on vllm.Inferencerepetition_detection (merged in vllm-project/vllm#71663) and extra_args on vllm.Inference.GenerateRequestmm_processor_kwargs and media_io_kwargs on vllm.Inferencesglang.api.v1 with bootstrap_room and unset bootstrap_hostskip_detokenize on sglang.api.v1n > 1 parallel sampling on sglang-serverWhy is this needed:
Pre-tokenized clients need zero tokenizers in llm-d or on workers, and both Coord-Text-Tok trackers (#4838, #4839) build on this gRPC Generate foundation.
needs-triage and no assignee/linked PR (by @ahg-g); assign owner or confirm scope.Related: llm-d/llm-d-router#4790.
Propose an opt-in decoder-aware TTFT feature contract for streaming P/D
serving. The initial scope is selected-pair capture and offline/shadow
evaluation, without a scheduling or admission policy change.
The proposal includes same-sample feature ablation on an Ascend/Mooncake
deployment and reports both point-estimate error reductions and p90
coverage limitations. It describes compatibility, rollout, validation and
coordination with llm-d/llm-d-router#4218 and llm-d/llm-d-router#4735.
This is a design proposal only; no implementation is included. The
implementation should be split after the design is reviewed.
using a CPU-only evaluation of the original fixed held-out cohorts.
git diff --check.
No implementation or deployment is changed by this PR; implementation-level
compatibility, integration and performance testing is planned for follow-up.
speculativeLifecycleRelease), I identified two failure-attribution edge cases in speculativeLifecycleReleaser.ResponseBody plus two observability gaps: Verified with unit probes in...While working on #4780 (speculativeLifecycleRelease), I identified two failure-attribution edge cases in speculativeLifecycleReleaser.ResponseBody plus two observability gaps:
seedDecodeWhenDisaggregated is false (default), PreRequest seeds speculative hints only on the prefill pod. If prefill succeeds (x-llm-d-failed-stage is decode or none-prefilled, per pkg/common/routing/common.go:111-121) and decode later fails with HTTP 5xx or aborts pre-first-token, ResponseBody releases all hints for the requestโevicting the prefill pod's valid warm blocks. (When seedDecodeWhenDisaggregated is true, only the decode pod's hints should be released.)maxNumOfEndpoints > 1), PreRequest seeds TargetEndpoints[0] (pod-A). If Envoy fails over to pod-B (metadata.ServedEndpoint(response.ReqMetadata) reports pod-B, as checked in endpointhealth/filter.go:436-439) and pod-B returns HTTP 200, ResponseBody keeps pod-A's phantom hints alive for the full speculativeTTL. (Direct sibling of #4857 for approximateprefix.)DumpState() (producer.go) omits speculativeLifecycleRelease and the tracked request count, and there is no Prometheus counter tracking speculative releases by reason (abandoned, failed_response, pre_first_token_abort, served_elsewhere).Verified with unit probes in pkg/epp/framework/plugins/requesthandling/dataproducer/preciseprefixcache (8 seeded blocks):
| Probe / Check | Before | After (Prototyped Fix) |
|---|---|---|
Mode A: P/D x-llm-d-failed-stage: decode + HTTP 500 (seedDecode: false) | Prefill 8 -> 0 (evicted) | Prefill 8 -> 8 (preserved) |
Mode A: P/D x-llm-d-failed-stage: none-prefilled + HTTP 500 (seedDecode: false) | Prefill 8 -> 0 (evicted) | Prefill 8 -> 8 (preserved) |
Mode A: P/D x-llm-d-failed-stage: decode + pre-first-token disconnect | Prefill 8 -> 0 (evicted) | Prefill 8 -> 8 (preserved) |
Mode A: P/D x-llm-d-failed-stage: none-prefilled + pre-first-token disconnect | Prefill 8 -> 0 (evicted) | Prefill 8 -> 8 (preserved) |
Mode A (control): P/D x-llm-d-failed-stage: prefill + HTTP 500 | Prefill 8 -> 0 | Prefill 8 -> 0 |
Mode A (seedDecode: true): P/D decode + HTTP 500 | Prefill 8 -> 0, Decode 8 -> 0 | Prefill 8 -> 8, Decode 8 -> 0 |
Mode A (non-P/D control): untrusted x-llm-d-failed-stage: decode + HTTP 500 | Pod 8 -> 0 | Pod 8 -> 0 (header ignored) |
Mode B: Envoy failover [pod-A, pod-B] -> ServedEndpoint=pod-B, HTTP 200 | pod-A 8 -> 8 (phantom for TTL) | pod-A 8 -> 0 (released immediately) |
Mode B (control): Primary pod-A served (ServedEndpoint=pod-A), HTTP 200 | pod-A 8 -> 8 | pod-A 8 -> 8 (TTL preserved) |
DumpState() (2 tracked reqs, 12 blocks) | Omits speculativeLifecycleRelease & tracked count | Reports speculativeLifecycleRelease: true & speculativeTrackedRequests: 2 |
| Prometheus release counter | None | llm_d_epp_prefix_speculative_releases_total{plugin_name,plugin_type,reason} (no double-counting) |
ReleasePod(requestID, pod string) bool, Release(requestID string) bool, and TrackedRequests() int on kvcache.SpeculativeIndex.preciseprefixcache:metadata.ServedEndpoint(response.ReqMetadata) (IPv6-safe net.SplitHostPort matching endpointhealth/filter.go:491-520) on non-disaggregated requests to call ReleasePod on the unserved primary pod.routing.FailedStageHeader (only when the request is disaggregated so untrusted headers are ignored): preserve prefill hints on StageDecode/StageNonePrefilled and release only decode hints when seedDecode is enabled.speculativeLifecycleRelease and speculativeTrackedRequests in DumpState(), and emit llm_d_epp_prefix_speculative_releases_total via prefixmetrics.I already have a clean prototype verified with go test -race across ./pkg/kvcache/..., ./pkg/epp/framework/plugins/requesthandling/dataproducer/prefixmetrics/..., ./pkg/epp/framework/plugins/requesthandling/dataproducer/preciseprefixcache/..., and ./pkg/epp/metrics/..., and am happy to open a follow-up PR once #4780 lands.
Related: #4780, #4042, #4857, #4593
monitoring.googleapis.com/v1 PodMonitoring for the decode pods on port sc-metrics, same as the coordinator one #2879 added in guides/coord-disaggregation/coordinator/monitoring/gmp-podmonitoring.yaml, and wire it into...Observability / Monitoring
#2990 turns on the routing sidecar's /metrics (sc-metrics, 9095) and adds it to the decode PodMonitors, but GMP doesn't read prometheus-operator PodMonitors, so on GKE llm_d_disagg_sidecar_* still isn't collected.
add a monitoring.googleapis.com/v1 PodMonitoring for the decode pods on port sc-metrics, same as the coordinator one #2879 added in guides/coord-disaggregation/coordinator/monitoring/gmp-podmonitoring.yaml, and wire it into the GKE P/D paths.
_No response_
Yes, I can submit a PR
follow-up from the #2990 review. related: #2989.
p2p-source-producer with transport: kvcr (#4303) should send the source pod's real KV block hashes in the kv.fetch hint. Today it sends one placeholder hash (Part of #4194).What would you like to be added:
p2p-source-producer with transport: kvcr (#4303) should send the source pod's real
KV block hashes in the kv.fetch hint. Today it sends one placeholder hash.
Part of #4194. Depends on vllm-project/vllm#68217.
A kv.fetch hint names a source pod and a list of block_hashes. What KVCR does with
the list depends on opportunistic_query:
of the request as fetchable from the source. The placeholder works here.
nothing, so no blocks are pulled.
kv.prefetch and kv.move (the "Later" row in #4194) have no request on the
destination, so they always need the real hashes.
Two things stop llm-d from sending real hashes today:
vllm.Inference gRPC API carries the hint payload as a protobuf Struct. AStruct number is a double, so a 64-bit hash cannot be sent exactly. vLLM rejects
any hash above 2^53 - 1. vllm-project/vllm#68217 addsrepeated uint64 block_hashes = 5 to KVHintAction to fix this.
vLLM publishes in its KV events (the engine key). The KV index stores
engine key -> request key, but not request key -> engine key, andPrefixCacheMatchInfo only carries block counts.
VLLM_REF and regenerate vllmpb(make generate-proto-vllm).
can return the engine keys of the matched prefix on a given pod. This adds
memory per index entry. Speculative entries have no engine keys and are skipped.
have p2p-source-producer read them for the chosen source.
KVHintAction.block_hashes and drop the placeholder. If thesource has no engine keys for the prefix, write no hint and record an outcome
for it.
encode_to_router invllm/v1/kv_offload/tiering/kvcr/manager.py). Do the hashes in the cpu tier KV
events from KVCR match that value, including when the offload block size differs
from the GPU block size? This needs a check on a real setup before the index change.
in the cpu tier), to bound hint size on long prompts?
many:1 and 1:many engine to request block ratios. The producer writes them intoKVHintAction.block_hashes, including values above 2^53.
opportunistic_query off: a request routedaway from the pod that holds the prefix pulls the blocks from that pod. The
placeholder hint pulls nothing on the same setup.
Why is this needed:
Without real hashes, KVCR peer fetch only works with opportunistic_query on, andkv.prefetch and kv.move from #4194 cannot be built.
needs-triage and no assignee/linked PR (by @kaushikmitr); assign owner or confirm scope.With a pool of heterogeneous GPUs (same model, same vLLM settings, different throughput), the endpoint picker (EPP) distributes a synchronized burst almost evenly across endpoints. The slowest endpoints cannot drain their share in time and some requests exceed our latency target.
The built-in scorers only compare endpoints with each other, and none of them knows how much load a given endpoint can actually sustain. The vLLM metrics also lag behind a burst. In addition, the EPP ran out of memory because it buffered the bodies of all concurrent requests.
llm-d-router-endpoint-picker:v0.9.0, run as an ext-proc behind agentgateway v1.5.0 (InferencePool + HTTPRoute)passthrough-parser (the request body is not parsed)queue-scorer, kv-cache-utilization-scorer (weight 2 each)active-request-scorer (weight 1)/metrics/ of each podFor comparison, static weighted backendRefs sized from measured capacity gave no request over the target on consecutive runs, including the first burst.
Every scorer and detector we looked at in v0.9.0 either compares endpoints with each other or applies the same limit to all of them:
(value - min) / (max - min)). Two endpoints with the same queue length get the same score, even if one drains its queue twice as fast as the other.For a heterogeneous pool, the same queue length therefore means very different drain times depending on the endpoint.
The gateway sends the full request body to the EPP, which keeps it in memory, even though passthrough-parser does not need it. Memory therefore grows with the number of concurrent requests multiplied by the body size.
With a conservative memory limit, the EPP was OOMKilled and went into CrashLoopBackOff during a burst. The gateway then returned 500 ext_proc failed: failed to send request. failureMode: FailOpen did not apply with agentgateway 1.5.0.
After raising the memory limit significantly, the EPP was stable.
The EPP logs token-producer: unsupported request body type for multipart requests, even with passthrough-parser. This is harmless but noisy.
For a pool of heterogeneous endpoints, the EPP should be able to:
passthrough-parser).inflight / capacity), with the capacity coming from a pod label or annotation, combined with weighted-random-picker? Or is there an existing way to give endpoints a static weight or capacity that I missed?passthrough-parser is used, or is there a documented way to bound its memory?Static weighted backendRefs per GPU type, sized from measured capacity.
needs-triage and no assignee/linked PR (by @mfournioux); assign owner or confirm scope._No response_
Description
We observed a significant regression in prefix-cache performance after enabling Fastokens 0.3.6 in our vLLM deployments integrated with llm-d.
With the default Hugging Face tokenizer backend, prefix-cache hit rate is consistently around 97โ98%. After switching to Fastokens, the hit rate drops to as low as 80%.
We also observe a significant increase in llm-d prefix-cache affinity filter decisions resulting in no match.
The issue persists over several hours of operation and is resolved after rolling back to the default Hugging Face tokenizer.
Environment
Software
Infrastructure
Two inference deployments are running simultaneously:
Deployment| Hardware| Nodes
Deployment 1| NVIDIA B300| 4
Deployment 2| NVIDIA B200| 3
Both deployments:
Vllm b200 configuration
- '--served-model-name=GLM-5.3-NVFP4'
- '--host=0.0.0.0'
- '--model=/mnt/model/glm53-nvfp4'
- '--port=8000'
- '--tensor-parallel-size=8'
- '--pipeline-parallel-size=1'
- '--data-parallel-size=1'
- '--load-format=runai_streamer'
- '--trust-remote-code'
- '--enable-expert-parallel'
- '--attention-backend=FLASHINFER_MLA_SPARSE'
- '--kv-cache-dtype=fp8_e4m3'
- '--block-size=64'
- '--max-model-len=400000'
- '--max-num-seqs=256'
- '--max-num-batched-tokens=8192'
- '--gpu-memory-utilization=0.9'
- '--enable-auto-tool-choice'
- '--reasoning-parser=glm45'
- '--tool-call-parser=glm47'
- '--enable-prefix-caching'
- '--disable-uvicorn-access-log'
- '--enable-prompt-tokens-details'
- '--speculative-config={"method":"mtp","num_speculative_tokens":5}'
- '--model-loader-extra-config={"concurrency":32,"memory_limit":10737418240,"distributed":true}'
- '--enable-scale-out'
- '--kv-transfer-config={"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"spec_name":"TieringOffloadingSpec","cpu_bytes_to_use":1099511627776,"block_size":256,"eviction_policy":"lru","self_describing_kv_events":true,"canonical_layout":true,"secondary_tiers":[{"type":"fs","root_dir":"/mnt/nvme-cache/kv/model-cache/models","enable_kv_events":true,"locality":"LOCAL","n_read_threads":16,"n_write_threads":16}]}}'
- '--kv-events-config={"enable_kv_cache_events":true,"publisher":"zmq","endpoint":"tcp://*:5557","replay_endpoint":"tcp://*:5558","topic":"kv@glm53-nvfp4-b200@GLM-5.3-NVFP4","buffer_steps":2000000,"hwm":500000}'
Vllm b300 configuration is the same but with b300 in the topic for the zmq.
llm-d configuration
apiVersion: llm-d.ai/v1alpha1
kind: EndpointPickerConfig
dataLayer:
sources:
- extractors:
- pluginRef: precise-producer
pluginRef: endpoint-notifier
featureGates:
- flowControl
flowControl:
defaultPriorityBand:
fairnessPolicyRef: program-aware-fairness-policy
maxBytes: 1Gi
maxRequests: 1k
orderingPolicyRef: fcfs-ordering-policy
defaultRequestTTL: 180s
enableEviction: false
maxBytes: "0"
maxRequests: 1k
priorityBands:
- fairnessPolicyRef: program-aware-fairness-policy
maxBytes: 1Gi
maxRequests: "349"
orderingPolicyRef: fcfs-ordering-policy
priority: 100
- fairnessPolicyRef: program-aware-fairness-policy
maxBytes: 256Mi
maxRequests: "87"
orderingPolicyRef: fcfs-ordering-policy
priority: -10
saturationDetector:
pluginRef: cc-sla-detector
plugins:
- name: program-aware-fairness-policy
parameters:
lasHalfLifeSeconds: 3600
strategy: las
type: program-aware-fairness
- type: fcfs-ordering-policy
- name: cc-sla-detector
parameters:
headroom: 0.25
maxConcurrency: 20
type: concurrency-detector
- name: prefix-affinity
parameters:
affinityThreshold: 0.5
maxTTFTPenaltyMs: 0
prefixMatchInfoProducerName: precise-producer
type: prefix-cache-affinity-filter
- name: endpoint-notifier
type: endpoint-notification-source
- name: precise-producer
parameters:
indexerConfig:
kvBlockIndexConfig:
enableMetrics: true
inMemoryConfig:
podCacheSize: 128
kvCacheBackendConfigs:
- name: gpu
weight: 1
- name: cpu
weight: 0.8
- name: storage
weight: 0.3
kvEventsConfig:
discoverPods: true
engineType: vllm
podDiscoveryConfig:
podNamespace: production
replaySocketPort: 5558
socketPort: 5557
topicFilter: kv@
speculativeIndexing: true
tokenProcessorConfig:
blockSizeTokens: 512
type: precise-prefix-cache-producer
- name: token-producer
parameters:
modelName: GLM-5.3-NVFP4-CC
vllm:
url: http://glm53-nvfp4-cc-pool-render:8000
type: token-producer
- type: queue-scorer
- type: kv-cache-utilization-scorer
- name: prefix-cache-scorer
parameters:
prefixMatchInfoProducerName: precise-producer
type: prefix-cache-scorer
- parameters:
insecureSkipVerify: true
path: /metrics
scheme: http
type: metrics-data-source
- type: core-metrics-extractor
- type: anthropic-parser
- type: openai-parser
- type: passthrough-parser
requestHandler:
parsers:
- pluginRef: anthropic-parser
- pluginRef: openai-parser
- pluginRef: passthrough-parser
schedulingProfiles:
- name: default
plugins:
- pluginRef: cc-sla-detector
- pluginRef: prefix-affinity
- pluginRef: queue-scorer
weight: 2
- pluginRef: kv-cache-utilization-scorer
weight: 1
- pluginRef: prefix-cache-scorer
weight: 3
Command:
- '--pool-name'
- llmd-router-glm53-nvfp4
- '--pool-namespace'
- 885-llms
- '--pool-group'
- inference.networking.k8s.io
- '--zap-encoder'
- json
- '--config-file'
- /config/default-plugins.yaml
- '--grpc-health-port'
- '9003'
- '--tracing=false'
The "glm-pool-render" Service routes requests to both inference deployments.
Request flow
Observed behavior
We compared the default Hugging Face tokenizer against Fastokens 0.3.6.
Metric| Hugging Face| Fastokens 0.3.6
"llm_d_epp_prefix_cache_affinity_filter_decisions_total" (no-match rate)| ~0.1 op/s| ~0.8 op/s
vLLM prefix-cache hit rate| 97โ98%| As low as 80%
The affinity filter reports approximately 8 times more no-match decisions with Fastokens.
The reduced cache hit rate persists during several hours of operation; it is not simply an initial cache warm-up effect.
What we have verified
Expected behavior
Enabling Fastokens should preserve tokenization semantics and prefix-cache behavior compared with the default Hugging Face tokenizer.
We would expect comparable:
The purpose of enabling Fastokens is to improve tokenization performance without degrading prefix-cache efficiency.
Actual behavior
Enabling Fastokens 0.3.6 results in:
Questions
We would appreciate guidance on how to debug this and identify whether the regression originates in tokenization, rendering, or llm-d prefix-cache affinity handling.
V.1.0.0
KV Cache / Prefix Caching
Observability / Monitoring
The EPP's metrics port is unauthenticated in file-discovery mode and also serves
pprof, and neither fact is documented.
runWithFileDiscovery (cmd/epp/runner/runner.go) registers the metrics server
as:
g.Add("metrics", func(ctx context.Context) error {
return serveMetrics(ctx, opts.MetricsPort, opts.EnablePprof)
})
serveMetrics builds a plain http.ServeMux with no authentication and no TLS.
The authenticating handler, newMetricsServerOptions withfilters.WithAuthenticationAndAuthorization, is only wired up on the Kubernetes
path, so a file-discovery deployment has no equivalent.
EnablePprof defaults to true (pkg/epp/server/options.go), so the same port
also serves /debug/pprof/, including /debug/pprof/heap, which dumps process
memory.
pprof does not appear anywhere under docs/.
In docs/operations/observability/metrics.md:
outside the Kubernetes path;
--enable-pprof defaults to true and mounts /debug/pprof/ on themetrics port, and recommend --enable-pprof=false outside development;
Documenting it only in guides/no-kubernetes-deployment. The behavior belongs
with the metrics documentation, since the pprof default is not specific to
file discovery.
Yes, I can submit a PR
Mapping issue for item 3 of #3074, which notes the unauthenticated port and the
pprof default.
SIGS.md gives every SIG a charter and a key-areas list. SIG Agentic Inference has TODO for both: Of the SIGs listed, it is the only one with neither filled in.Documentation / Community
SIGS.md gives every SIG a charter and a key-areas list. SIG Agentic Inference
has TODO for both:
**Charter**: TODO
**Key Areas**:
- TODO
Of the SIGs listed, it is the only one with neither filled in. Someone arriving
from the SIG table, the #sig-agentic-inference Slack channel, or thearea/agentic label finds no statement of what the SIG covers or where its work
lives, and has to reconstruct it from meeting recordings.
The information exists โ the North Star design document linked from the SIG
entry, the area/agentic label description in .github/area_taxonomy.md
("Stateful OpenAI Responses API and multi-turn priority fairness"), theguides/agent-substrate and guides/thunder-agent guides, and theagentidentity, sessionstate, thunderagent and flowcontrol packages inllm-d-router โ but it is not stated in the one place readers are pointed to.
Fill in the Charter and Key Areas for SIG Agentic Inference in SIGS.md,
matching the shape the other SIG entries use.
The charter wording should come from the SIG leads. I am happy to draft both
from the North Star document and the meeting recordings and open the PR for
review, so the leads only have to correct rather than compose.
Leaving the entry as TODO and directing readers to the Slack channel. That
relies on someone being available to answer, and leaves the area/agentic label
description as the only written scope statement, in a file about labels rather
than about the SIG.
Yes, I can submit a PR
Part of #4851 (scenarios 8 and 9).
Killing one tokenizer pod fails in-flight renders with 502 internal error, most of them after the full render timeout, with no retry even though another tokenizer pod is healthy. With the tokenizer pool at 0, every request gets an opaque 502. Proposal: retry a render once after a transport error, timeout or 5xx (never after a 4xx), and answer 503 with a reason and the request id when the render service can't be reached at all.
Part of #4851 (scenarios 6 and 7).
When the Envoy in front of the coordinator, or the gateway it calls, dies without closing its TCP connections, the coordinator keeps writing to the dead peer until the kernel's retransmission timeout ends it, about 15 minutes later. TCP keepalive doesn't help because the connection isn't idle while unacknowledged data is in flight, and the server deliberately sets no write deadline. Proposal: set TCP_USER_TIMEOUT (30s) on connections the coordinator accepts and on the connections it dials to the gateway and the render service, on Linux.
Part of #4851 (scenario 5).
When the decode leg's ext_proc call fails, the gateway answers 500 with an empty body, and the coordinator passes that to the client unchanged. The same failure on the prefill leg already reaches the client as 502 with a JSON error carrying the request id. Proposal: give empty-body decode-leg 5xx responses the prefill leg's error format (OpenAI or Anthropic envelope, with request id). Also include the request id in the 400 for a malformed JSON body.
docs/create_new_scorer.md, modeled on docs/create_new_filter.md, that walks through writing and wiring a scheduling scorer.What would you like to be added:
A tutorial docs/create_new_scorer.md, modeled on docs/create_new_filter.md, that walks through writing and wiring a scheduling scorer.
The filter tutorial covers the plugin factory, plugin.Register with plugin.StabilityAlpha in runner.go, and the EndpointPickerConfig YAML. It does not cover what is specific to scorers:
scheduling.Scorer interface and Category (Affinity, Distribution, Balance);metrics-data-source and core-metrics-extractor plugins are required for fields such as the waiting queue size, and Consumes() declares the dependency;--allow-experimental-plugins.The tutorial would reference an existing scorer (for example queuedepth) as the worked example, as the filter tutorial does with bylabel. It would not add a new scorer.
Why is this needed:
There is no entry point for someone who wants to write a scorer. Per-plugin READMEs describe existing scorers, and the filter tutorial stops at filters. Writing the first scorer requires reading the scheduling framework code to find the score range, the category semantics and the metrics wiring.
I followed this path for a scorer and would be glad to contribute the tutorial. Related: #917 (plugin README template) and #888.
Question: should this live in docs/ or on llm-d.ai, given the audience discussion in #917?
needs-triage and no assignee/linked PR (by @mfournioux); assign owner or confirm scope.Optimized baseline
Operators need a way to inspect the scores assigned to candidate endpoints
and understand how they relate to request routing.
Add a documentation page showing how to:
Calculated score logs.missing scores, and picker behavior.
Use generic examples and explain that an observed request distribution alone
does not establish that a scorer caused it.
score logs.
Yes, I can submit a PR
_No response_
ResponseBody (pkg/epp/framework/plugins/requesthandling/dataproducer/predictedlatency/requestcontrol_hooks.go, around line 180) as...What happened:
The predicted-latency plugin computes average TPOT in ResponseBody (pkg/epp/framework/plugins/requesthandling/dataproducer/predictedlatency/requestcontrol_hooks.go, around line 180) as (lastTokenTimestamp - requestReceivedTimestamp - ttft) / (generatedTokenCount - 1). generatedTokenCount goes up once per ResponseBody call (processTokenForLatencyPrediction, line 325), so it counts streamed body chunks, not generated tokens. When a chunk carries several tokens (speculative decoding, SGLang --stream-interval, or SSE events merged into one data frame), the TPOT is too high by about the tokens-per-chunk factor.
That value feeds the plugin's TPOT and TPOT-SLO metrics and the ActualTPOT training sample sent to the latency predictor, so the predictor learns TPOT values that are too high. The core EPP TPOT histogram (metrics.RecordRequestTPOT) divides by Usage.CompletionTokens - 1, so the two TPOT numbers disagree for the same request.
What you expected to happen:
When the final chunk reports usage, TPOT should be decode time divided by completion_tokens - 1, the same as the core EPP metric. The chunk count should only be a fallback when the stream reports no usage.
How to reproduce it (as minimally and precisely as possible):
I added this test in pkg/epp/framework/plugins/requesthandling/dataproducer/predictedlatency/. It streams a first token and two more chunks, then sends a natural end of stream with Usage.CompletionTokens = 9:
func TestPredictedLatency_TPOTDividesByChunksNotTokens(t *testing.T) {
router := createTestRouter()
router.config.StreamingMode = true
predictor := new(mockPredictor)
router.latencypredictor = predictor
endpoint := createTestEndpoint("tpot-pod", 1, 1, 1)
request := createTestInferenceRequest("tpot-request", 100, 50)
state := newPredictedLatencyContext(request)
router.setPredictedLatencyContextForRequest(request, state)
require.NoError(t, router.PreRequest(context.Background(), request, createTestSchedulingResult(endpoint.GetMetadata())))
state.requestReceivedTimestamp = time.Now().Add(-time.Second)
t0 := state.requestReceivedTimestamp
processFirstTokenForLatencyPrediction(context.Background(), predictor, true, router.config.EndpointRoleLabel, state, t0.Add(100*time.Millisecond))
processTokenForLatencyPrediction(context.Background(), state, t0.Add(180*time.Millisecond))
processTokenForLatencyPrediction(context.Background(), state, t0.Add(260*time.Millisecond))
predictor.capturedTrainingEntries = nil
const completionTokens = 9
router.ResponseBody(context.Background(), request, &fwkrh.Response{
EndOfStream: true, TerminationCause: fwkrh.TerminationCauseNatural, StreamedEvents: 3,
Usage: fwkrequest.Usage{PromptTokens: 100, CompletionTokens: completionTokens},
}, endpoint.GetMetadata())
decodeMs := float64(state.lastTokenTimestamp.Sub(state.requestReceivedTimestamp).Milliseconds()) - state.ttft
require.Len(t, predictor.capturedTrainingEntries, 1)
assert.InDelta(t, decodeMs/float64(completionTokens-1), predictor.capturedTrainingEntries[0].ActualTPOT, 1.0)
}
Result on main:
avgTPOT recorded: 300.00 ms, decode time / (completion_tokens-1): 112.50 ms
Error: Max difference between 112.5 and 300 allowed is 1, but difference was -187.5
--- FAIL: TestPredictedLatency_TPOTDividesByChunksNotTokens
Anything else we need to know?:
A possible fix: at a natural end of stream with response.Usage.CompletionTokens > 1, divide by CompletionTokens - 1, and keep generatedTokenCount - 1 as the fallback when no usage is present. #2430 mentions this chunk counter in passing. #3298 and #3299 fixed a different overcount (synthetic completions).
Environment:
I find the docs is not that clear for the first time user since I don't know how to do when I turn on flow control feature gate especially the defaultDelayTTS so i'd like to trace the code in llm-d-router. And I find there are more thing I can contribute than I originally thought.
This PR aligns the Flow Control section of docs/architecture/router/configuration.md and docs/api-reference/endpointpickerconfig.md with the API types:
defaultRequestTTL was documented as defaulting to "0s". The code defaults it to 60s; an explicit "0s" disables the queue-wait bound.noEndpointRequestTTL and the band-level defaultRequestTTL.maxBytesPerFlow and maxRequestsPerFlow. Unlike maxBytes and maxRequests, 0 disables them.defaultNegativePriorityBand, usageLimitPolicyPluginRef and bandSelectionPolicyPluginRef to the configuration guide. The API reference already lists them.flowControl.crossReplica.One commit per item, so any of them can be dropped on request.
I can follow up the CrossReplicaConfig section of the API reference describes the dataLayer. Other sections of the configuration guide (featureGates, requestHandler, dataLayer, metrics) also have undocumented fields.
Docs only; AI is used to hint me how to trace the code and write the files below. I was checked llm-d-router at 2188d9f:
docs/architecture/router/custom-scorer.md, a tutorial for writing a custom scorer plugin for the EPP.Adds docs/architecture/router/custom-scorer.md, a tutorial for writing a custom scorer plugin for the EPP. It uses the built-in queue-scorer as the worked example and covers the Scorer interface, score range and categories, factory and data dependencies, plugin registration and stability levels, EndpointPickerConfig wiring, building a custom EPP image, Helm values, and reading Calculated score debug logs. The page links to the existing scheduling, configuration and data layer pages instead of repeating them. The page is registered in docs/menu-config.json.
Related: #<issue>
Docs-only change; no guide or cluster was run.
main.markdownlint passes on the new page; menu-config.json parses as valid JSON.Add LMetric https://arxiv.org/html/2603.15202v1#S5.SS1 as an optional policy for precise-prefix-cache-routing and add a router values overlay that replaces the default scoring profile with lmetric-scorer.
Also update the XPU example to use Qwen3-32B with FP8 quantization and TP=2 so it matches the guide's 32B baseline model.
Depends on https://github.com/llm-d/llm-d-router/pull/2351.
mm-embeddings-cache-producer and mm-embeddings-cache-scorer plugins to both vLLM e-disaggregation router profiles (E/PD and E/P/D), so repeated multimodal media routes to the encode worker that already holds the... (Fixes #1952)Adds the mm-embeddings-cache-producer and mm-embeddings-cache-scorer plugins to both vLLM e-disaggregation router profiles (E/PD and E/P/D), so repeated multimodal media routes to the encode worker that already holds the embeddings.
Fixes #1952
router/vllm/e-pd-disaggregation.values.yaml and router/vllm/e-p-d-disaggregation.values.yaml: add mm-embeddings-cache-producer and mm-embeddings-cache-scorer, with the scorer referenced in the encode scheduling profile at weight 4 (matching the plugin README example). cacheSizeInMBPerServer is left unset (plugin default 4096 MiB) with a comment explaining the relationship to the vLLM num_ec_blocks this guide configures.README.md: new "Encoder-Cache Affinity" section covering what the plugins do, the three EPP metrics (encoder_cache_queries_total, encoder_cache_hits_total, encoder_cache_hit_ratio), and how to tune cacheSizeInMBPerServer relative to num_ec_blocks.e-p-d-disaggregation.values.yaml:86 awaiting @acardace's response.What type of PR is this?
kind test
What this PR does / why we need it:
We need to test which responses API features are supported llm-d ( as oppose to front end agentic API).
I run it with simulator with the following tests based on compliance tests of responses API published here
https://github.com/openresponses/openresponses/blob/main/src/lib/compliance-tests.ts
streaming-response is the one real gap. Nothing in test/e2e covers SSE framing on /v1/responses today.
all other tests from
https://github.com/openresponses/openresponses/blob/main/src/lib/compliance-tests.ts
are not relevant since those API specs in responses API are not supported in llm-d as defined in responses API
Which issue(s) this PR fixes:
Fixes ](https://github.com/llm-d/llm-d-router/issues/3059)
Release note _(write NONE if no user-facing change)_:
NONEThis PR adds an end-to-end integration test verifying that the router correctly proxies streaming SSE requests on the /v1/responses endpoint when stream: true. It deploys a single-replica decode server and validates that incoming SSE chunks adhere to data: formatting, terminate before data: [DONE], and conclude with a response.completed event carrying valid output. Core request handling, routing logic, and P/D disaggregation pipelines remain unchanged.
A client sends POST /v1/responses with body {"model": "food-review", "input": pdTextInput, "stream": true}. The gateway routes to the decode model server, which returns an SSE stream starting with event chunks and ending with data: {"type": "response.completed", "response": {"status": "completed", "output": [...]}} followed by data: [DONE]. The test verifies HTTP status 200, parses each SSE frame into an event object, and asserts that the terminal response.completed payload has status completed with non-empty output.
Fits prefill, transfer, transferFixedMs, sourceWaitMs and requeueMs from the minCachedTokenDelta crossover table plus a loaded fixed-delta run (inference-perf per-request output joined to the EPP p2p decision log), and warns when the loaded run cannot pin down the fixed costs.
Adds guides/recipes/router/calibration/fit-cost-model.py and documentation in guides/recipes/router/calibration/README.md to fit five p2p-source-producer costModel parameters (prefillMicrosecondsPerToken, transferMicrosecondsPerToken, transferFixedMs, sourceWaitMs, requeueMs) from an idle crossover run and a loaded fixed-delta benchmark. Existing calibration scripts (calibrate.sh and calibrate-min-cached-token-delta.sh) and router configs remain unchanged, and fleetWeight stays a manual choice.
idle_fit in guides/recipes/router/calibration/fit-cost-model.py:44-53): Parses the tokens / recompute_ms / pull_ms / delta% table from calibrate-min-cached-token-delta.sh and fits linear slopes (ms/ktok = us/token) for prefillMicrosecondsPerToken (P) and transferMicrosecondsPerToken (T).load_decisions and load_requests at fit-cost-model.py:55-82): Strips the cmpl- prefix on both sides via norm_rid so inference-perf per_request_lifecycle_metrics.json rows join to EPP "p2p decision" log records, computing TTFT from output_token_times[0] - start_time.loaded_fit at fit-cost-model.py:84-129): Subtracts T_idle * delta from pulled TTFTs and fits [1, uncached/1000, busy_dst, pulled, pulled*busy_src, pulled*busy_dst] across pulled and local requests (floored at 0), plus 200-sample request bootstrapping to flag >250 ms 80% intervals.calibrate-min-cached-token-delta.sh on an idle pod pair and save the table to crossover.log.costModel, set report.request_lifecycle.per_request: true in inference-perf, capture EPP "p2p decision" logs, and run ./fit-cost-model.py --crossover crossover.log --per-request run1/per_request_lifecycle_metrics.json --epp-log epp-decisions.log.P and T from crossover.log, joins requests to decisions, prints diagnostics and 80% bootstrap intervals to stderr, and writes the ready-to-paste costModel: YAML block to stdout.Motivation: the monitoring-pd component only ships PodMonitors for the
decode (via the base monitoring component) and prefill roles. The
multimodal E/PD and E/P/D topologies use monitoring-pd and deploy pods
labelled llm-d.ai/role: encode, so Prometheus never scrapes the Encode
tier (reported: 0 encode targets).
Approach: add encode-podmonitor.yaml, same shape as the prefill one
(selector llm-d.ai/role: encode, port "modelserver", /metrics, 30s), and
list it in the component's resources. The multimodal encode containers
expose a port named "modelserver" (8000) in both topologies. Topologies
without encode pods are unaffected: the PodMonitor simply matches nothing.
Validation: ran kustomize build on a scratch kustomization that uses
the monitoring-pd component; it renders PodMonitors decode, encode and
prefill, with the encode one selecting llm-d.ai/role: encode. I did not
deploy to a cluster or check Prometheus targets, so scraping of live
encode pods is not confirmed here; no dashboards were changed.
Report: https://github.com/llm-d/llm-d/issues/2845
Signed-off-by: Pujitha Paladugu <10557236+pujitha24@users.noreply.github.com>
Assisted-by: claude-sonnet-5-5 (via Claude Code)
Fixes #2845
Bug: make test and make lint returned success without running any checks. The Kubernetes, OpenShift, and RBAC install targets tried to render a nonexistent deploy/ directory, so they could not deploy this guide-based repository.
Fix: wire test to the Python and snapshot suites used by CI, run the repository's prek configuration for lint, and remove the obsolete generic cluster install targets. Direct users to the supported guide instructions.
Test: make -n test and make -n lint show the expected commands. Test: python -m unittest discover -t . -s docker/scripts/snapshot -q
(40 passed).
Test: make test reached all pytest suites (421 passed, 10 failed because
this macOS host lacks GNU realpath and has kubectl/Kustomize v4.5.4).
Test: uvx prek --version succeeded; git diff --check passed.
Makefile:69 awaiting @tangming1996's response.Bug: the interactive pod's namespaced Role listed namespaces, clusterroles, and clusterrolebindings. A RoleBinding cannot authorize requests for those cluster-scoped resources, so inspection was denied.
Fix: move those reads into a dedicated ClusterRole and bind it to the pod's ServiceAccount. Keep cluster access read-only and set an explicit namespace for the binding subject; document how to change it.
Test: kubectl kustomize rendered the manifests successfully. Test: asserted the cluster binding, RoleBinding, and Deployment target
the same namespace and the ClusterRole has the intended resources.
Test: git diff --check passed.
README.md:12 awaiting @tangming1996's response.program-aware-fairness recomputed Jain's fairness index on every Pick by ranging over the plugin's entire per-program map (Fixes #3734).What type of PR is this?
/kind performance
What this PR does / why we need it:
program-aware-fairness recomputed Jain's fairness index on every Pick by ranging over the plugin's entire per-program map. The map retains every fairness ID seen within evictionTtlSeconds (1 h by default), so Pick cost grew with the resident ID base instead of with the active flows. At 200,000 resident IDs a single active flow measured ~23 ms p50, against ~0.4 ยตs cold.
This maintains the index inputs incrementally. RecordDispatched folds each program's change in average wait time into shared sums, eviction removes the evicted program's contribution, and an evicted value cannot re-add itself when a dispatch races the sweep. Pick and DumpState read the index in O(1).
Benchmarks with a single active flow (Windows, i7-13650HX):
| IDs | before: mean / p50 | after: mean / p50 |
|---|---|---|
| 0 | 779 ns / 381 ns | 686 ns / 368 ns |
| 200,000 | 26.9 ms / 23.2 ms | 530 ns / 381 ns |
Prewarming 0/1k/10k/100k/200k IDs measures 650/597/556/481/484 ns per Pick, flat in the number of resident IDs.
New tests compare the maintained index against a full scan and cover eviction and an eviction-racing dispatch.
Which issue(s) this PR fixes:
Fixes #3734
Release note:
NONE
make presubmit was not run because this machine has no container runtime; targeted go test and go vet were run instead. go test -race was not run because the host's mingw gcc is 32-bit only. The benchmark p50 is a batched estimator on Windows, not the Linux numbers from the issue.
programmetrics.go:76, plugin.go:343 awaiting @3431481073's response.p2p-source-producer picks a pull source by cache shortfall and waiting queue, but it can't see the pulls it has already pointed at a source.What type of PR is this?
/kind feature
What this PR does / why we need it:
Item 1 of 3 in #3856 (child 2 of #2273). p2p-source-producer picks a pull source by cache shortfall and waiting queue, but it can't see the pulls it has already pointed at a source. This PR counts those pulls and the tokens they pull; the next PR adds that load to source selection.
With trackInFlightPulls: true (off by default):
PreRequest counts a pull against the source when it sets the source header.RequestAbandoned releases one that was never sent.llm_d_epp_p2p_inflight_pulls and llm_d_epp_p2p_inflight_pull_tokens export the count and the pulled tokens per source. A source's series is removed when its count reaches 0.With the flag off, the factory returns the same *Producer as before, so the director doesn't call it per response chunk. Counts are per EPP replica. The first response chunk is a signal the EPP already has, so unlike Appendix B.3 of #2273 this needs no duration estimate.
#3441 moves the source into kv_transfer_params in the same PreRequest; whichever lands second needs a rebase.
Tests (CPU only): counting, the three release paths, a repeated PreRequest, the flag off, the token gauge and metric registration. go test -race, go build ./cmd/epp and golangci-lint pass.
Which issue(s) this PR fixes:
Part of #3856
Release note _(write NONE if no user-facing change)_:
p2p-source-producer: optional `trackInFlightPulls` counts the P2P pulls directed at each source endpoint and the prompt tokens they pull, and exports them as `llm_d_epp_p2p_inflight_pulls` and `llm_d_epp_p2p_inflight_pull_tokens`.Introduces an optional trackInFlightPulls configuration flag in p2p-source-producer that tracks active in-flight P2P KV cache pulls and transferred prompt tokens per source endpoint, exporting them as llm_d_epp_p2p_inflight_pulls and llm_d_epp_p2p_inflight_pull_tokens Prometheus gauges. Tracking is dormant by default with zero response-hook overhead and zero allocations when disabled. Source selection algorithms remain unchanged in this PR, establishing the telemetry foundation for future load-aware peer ranking.
trackingProducer Decorator (pkg/epp/framework/plugins/requesthandling/dataproducer/p2psource/pulls.go:218):*Producer only when trackInFlightPulls: true.ResponseBodyProcessor, RequestAbandoned, Registrant, and EndpointExtractor.PluginFactory returns the raw *Producer, completely bypassing director response chunk calls.pullTracker & Mutex Protection (pkg/epp/framework/plugins/requesthandling/dataproducer/p2psource/pulls.go:66):loads map[fwkdl.ID]*pullLoad and endpoints map[fwkdl.ID]fwkdl.Endpoint.PluginState.BindLiveness(ctx, requestID) so active requests are not prematurely evicted by the background janitor.PreRequest): When a P2P peer is selected and header x-llm-d-kv-cache-source is attached, pullTracker.acquire increments the source's load and registers an evictable pullEntry in PluginState. Duplicate calls for the same request ID are rolled back atomically.ResponseBody): On streaming responses, the pull is released upon the first chunk (response.StartOfStream == true), signaling the computing pod completed prefill. Non-streaming responses release on the single chunk where both StartOfStream and EndOfStream are true.StartOfStream == false && EndOfStream == false) evaluate to false immediately, performing zero lock acquisitions, zero allocations, and zero map operations.RequestAbandoned; requests dropped during transmission trigger EndOfStream. Unhandled disconnects are reclaimed by the PluginState janitor TTL sweep, with pullEntry.OnEvicted decrementing load exactly once.fwkdl.EndpointExtractor subscribing to sourcenotifications.EndpointNotificationSourceType. When an endpoint leaves the pool or pull count returns to zero, inFlightPulls.DeleteLabelValues and inFlightPullTokens.DeleteLabelValues delete both series. Pointer identity tracking (registered != ep) prevents stale delete events from decrementing replacement endpoints reusing the same ID.trackInFlightPulls: true under p2p-source-producer.req-101 targets destination pod-a. Produce evaluates prefix cache entries and selects pod-b as the best P2P source with 4,096 uncached prefix tokens.x-llm-d-kv-cache-source: 10.0.0.2:7777 is set. pullTracker.acquire sets llm_d_epp_p2p_inflight_pulls{endpoint_name="pod-b",...} = 1 and llm_d_epp_p2p_inflight_pull_tokens{endpoint_name="pod-b",...} = 4096.StartOfStream: true). ResponseBody calls p.pulls.release("req-101"), deleting the state entry. OnEvicted decrements count to 0, which deletes both Prometheus series for pod-b.pod-b is deleted while a pull is in flight, Extract intercepts EventDelete, drops loads[pod-b], and prunes Prometheus series immediately. A replacement pod reusing pod-b starts at count 0, and late releases from the old pod are safely ignored.session-prefix-cache-producer to resolve externally supplied engine-block paths against live GPU residency, without rendering or tokenization.What type of PR is this?
/kind feature
What this PR does / why we need it:
Add session-prefix-cache-producer to resolve externally supplied engine-block paths against live GPU residency, without rendering or tokenization. It forwards request stamps and publishes the existing cache-match attributes for scoring, affinity, and load accounting.
Builds on #3910 and #3911. The producer binds to a kv-events-source through kvEventsSourceRef, same as the precise producer. This replaces the cache-producer portion of #2716.
Session identity and lineage policy remain with #2852. The request contract preserves its field names and types. A stamp without a known prompt length is forwarded without overriding the load estimate. Uncertain paths supply affinity; only exact paths discount prefill work.
kvEventsSourceRef, and creates no default token-based cache path.Validation: race-enabled producer, load, attribute, index, and runner tests; make presubmit. Event integration uses a local ZMQ publisher; this change has no new engine benchmark result.
Which issue(s) this PR fixes:
Related to #1979.
Release note _(write NONE if no user-facing change)_:
Add the Alpha session-prefix-cache-producer for externally managed session block paths. It consumes shared KV events and supports routing with real or estimated token counts without requiring prompt rendering.events.go, producer_test.go; not yet resolved.What type of PR is this?
/kind bug
/kind cleanup
What this PR does / why we need it:
Enforce queue-wait budgets exclusively through the processor's periodic expiry sweep, eliminating the dual-timer race where an exact context deadline timer beat the polling sweep and misattributed empty-pool expiries to saturation backpressure.
context.WithCancel in createRequestContext, deleting the synthetic backstop deadline and its 2-interval padding.saturationTTL to caller deadlines so the sweep enforces the operator queue-wait budget only. A caller deadline expiring while queued maps to ErrContextCancelled (QueueOutcomeEvictedContextCancelled -> 503) rather than ErrTTLExpired (429).poolEmpty probe in translateFlowControlError to pre-queue expiries (ErrRejected + ErrTTLExpired) from tryDistribution, which do not carry an endpoint-availability regime; queued EvictedTTL expiries map to 429 unconditionally.pkg/epp/flowcontrol/README.md to document sweep-interval latency (expiryCleanupInterval), budget resets across empty/non-empty pool transitions, and using a gateway request timeout to cap total client wait.pkg/epp/flowcontrol/... and pkg/epp/requestcontrol/... pass under go test -race, including caller-deadline eviction while queued, pre-admission TTL expiry with populated and empty pools, and queued empty-pool expiry attribution../cmd/epp/... builds and ./test/integration/epp test binary compiles cleanly.Which issue(s) this PR fixes:
Fixes #2419
Release note:
Flow control queue-wait budgets are now enforced solely by the periodic cleanup sweep without a per-request hard deadline across empty/non-empty pool transitions, so a flapping pool restarts the budget in force on each transition (set a gateway request timeout to bound total client wait), and a caller deadline expiring while queued is now reported under the `EvictedContextCancelled` metric outcome (HTTP 503) instead of `EvictedTTL` (HTTP 429).Enforces flow-control queue-wait budgets exclusively through the processor's periodic expiry sweep rather than a dual context backstop timer, preventing exact context timers from racing the sweep on empty pools. Caller-supplied context deadlines that expire while queued now classify as ErrContextCancelled (EvictedContextCancelled, HTTP 503) instead of ErrTTLExpired (HTTP 429). Pre-queue distribution in tryDistribution remains bounded by saturationTTL, and translateFlowControlError narrows its live poolEmpty probe to that pre-queue ErrRejected path while queued EvictedTTL expiries map to 429 unconditionally.
controller.go#L477-L494): FlowController.createRequestContext derives reqCtx via context.WithCancel(ctx) without a synthetic backstop deadline and stops clamping saturationTTL to caller deadlines. tryDistribution still bounds handoff via context.WithDeadlineCause(reqCtx, enqueueTime.Add(saturationTTL), types.ErrTTLExpired) (controller.go#L414-L419).item.go#L209-L229): wrapCause folds context.DeadlineExceeded alongside context.Canceled into types.ErrContextCancelled, reserving types.ErrTTLExpired for explicit TTL-cause expiries from distributeCtx or the processor sweep (processor.go#L769-L845).admission.go#L297-L302): translateFlowControlError invokes poolEmpty() only when errors.Is(err, types.ErrTTLExpired) and errors.Is(err, types.ErrRejected) (pre-queue handoff expiry); queued empty-pool expiries already carry types.ErrNoEndpoints from the processor sweep (503), and other queued ErrTTLExpired expiries map directly to 429.EnqueueAndWait with a 50ms caller context.WithTimeout while DefaultRequestTTL and NoEndpointRequestTTL are 5m and the pool is saturated.createRequestContext returns reqCtx preserving the 50ms caller deadline and an unclamped saturationTTL of 5m; the item enters the queue.awaitFinalization observes <-reqCtx.Done() with cause context.DeadlineExceeded, calls item.Finalize(cause), and wrapCause produces ErrEvicted: ErrContextCancelled: context deadline exceeded (QueueOutcomeEvictedContextCancelled).translateFlowControlError maps ErrContextCancelled to HTTP 503 with x-llm-d-drop-reason: ContextCancelled instead of misreporting queue saturation (429).controller_test.go, README.md awaiting @samosa-sundays's response.guides/models/kimi-k3-1 for agentic, multi-turn serving. Router values are unchanged.Sizes the Kimi-K3.1-Pro TPU 7x (SGLang) engine in guides/models/kimi-k3-1 for agentic, multi-turn serving. Router values are unchanged.
--max-mamba-cache-size=384. The SGLang Kimi-K3.1 recipe sizes 708 KDA recurrent-state slots. Under multi-turn agentic load they sat at 1โ3% use while holding about as much HBM as the KV pool. Capping them at 384 grows the HBM KV pool from 532,352 to 751,104 tokens per replica (engine boot log). A cached prefix also needs a KDA state snapshot, and too few slots stop prefix-cache hits (seen at 256), so the patch comment documents the floor.--weight-loader-drop-cache-after-load: drops checkpoint pages from the page cache after loading (read by the image's safetensors loader).SGLANG_TPU_VIT_PRECOMPILE_SIZES="": skips the vision-encoder bucket compile at startup. The guide serves text only (SGLANG_TPU_VL_TEXT_ONLY_EXTEND=1).SGLANG_TPU_OVERLAP_PROFILE, TPU_ENABLE_TELEMETRY, TPU_ENABLE_TELEMETRY_HARVESTING, ENABLE_TPU_TELEMETRY, TPU_TELEMETRY_INTERVAL_SEC, TPU_TELEMETRY_INTERVAL_SECONDS. No runtime reader exists for them in the image's Python, shell or native libraries.--scheduler-recv-interval stays at the recipe default (16). An earlier revision of this PR set it to 8 together with four prefill/decode overlap env vars. Those env vars are not read by this image (or, for TPU_PREMAPPED_BUFFER_SIZE, do not serve the raiden HiCache path), and a 3-run A/B with everything else equal showed no measurable effect from 8, so both changes are dropped.lruCapacityPerServer: 12478 was sized before the KDA cap and is kept unchanged.Benchmark Results are not part of this PR. They will follow separately.
Unchanged: model guide, tpu ยท sglang: community.
tpu7x 2x2x4 node pools (16 chips per replica).docker.io/lmsysorg/sglang@sha256:84fa8579cfb609d383a64fdd64c0036045140c905b7bd8a5ee9e6cadfe3cf433 (unchanged).TORCH_TPU_TIER3_COMPILATION_CACHE_ROOT on a node volume) to shorten repeat boots; it does not change serving behaviour.scripts/guide.py render --recursive --check guides, check-manifest, and the overlay lint: 0 critical / 0 high. The one medium finding is the existing Benchmark Results placeholder.InferencePool object were not exercised on the test cluster.lruCapacityPerServer is not yet recomputed for the larger pool (about 17.6K if the host tier stays at 2ร HBM). That needs its own validation run.Rebalances TPU HBM allocation and startup behavior for the SGLang Kimi-K3.1-Pro guide by capping KDA recurrent-state slots at 384, dropping checkpoint pages from the OS page cache after loading, skipping unused vision-encoder compilation, and removing six env vars unread by the pinned image. Context length (491,520), HiCache ratio (2x HBM), and router lruCapacityPerServer (12478) stay unchanged.
guides/models/kimi-k3-1/modelserver/tpu/sglang/patch-sglang.yaml:105): Adds --max-mamba-cache-size=384 (down from SGLang's 708-slot recipe default), expanding the HBM KV pool from 532,352 to 751,104 tokens per replica and scaling the --hicache-ratio=2 host-DRAM tier proportionally.patch-sglang.yaml:108,198-199): Adds --weight-loader-drop-cache-after-load (paired with --weight-loader-disable-mmap) to release checkpoint page cache inside the 800Gi pod limit, sets SGLANG_TPU_VIT_PRECOMPILE_SIZES="" to skip ViT bucket compiles in text-only mode (SGLANG_TPU_VL_TEXT_ONLY_EXTEND=1), and drops six unread telemetry/overlap env vars.patch-sglang.yaml:70,121,280-281): Both leaderTemplate and workerTemplate share &args and &env, applying all flag and env changes uniformly across the 4-pod LeaderWorkerSet.README.md:50-51,312,431-432, inference-perf.yaml:44): Updates HBM KV pool numbers to 751K and notes that lruCapacityPerServer: 12478 predates the KDA cap.tpu7x 2x2x4 LeaderWorkerSet launches sglang.launch_server via shared *args/*env with --max-mamba-cache-size=384, --weight-loader-drop-cache-after-load, and SGLANG_TPU_VIT_PRECOMPILE_SIZES=""./models, the loader drops checkpoint pages from the OS page cache, and Torch TPU skips ViT precompilation.CONCURRENCY_LEVEL=16 in inference-perf.yaml, active prefixes exceeding the 751,104-token HBM KV pool spill into the 2x HiCache host tier while retaining 384 HBM KDA state slots.patch-sglang.yaml, README.md:312 awaiting @syeda-anjum's response.What type of PR is this?
/kind feature
What this PR does / why we need it:
Part of the KV block index representation series (#4529).
Adds a kvevents record/replay package: a pool config path captures every received wire event to a file sink, and the replayer feeds a captured file back through the pool deterministically, so index changes can be validated against production-shaped event streams instead of synthetic loops. Later PRs in the series use it for trace-driven benches, and a production trial would re-run captured events against a candidate backend.
Replay is a library facility: Pool.ReplayFile has no operator flag, so a replay session is driven by a caller holding the pool (tests and capture tooling today); wiring an operator entry point is a follow-up if wanted.
Also adds a parent-hash resolution contention bench: GetRequestKey runs on every block store under write contention, and the bench measures that path with concurrent writers so representation changes to the engine-key map (for example #4663) can show their effect on it.
Which issue(s) this PR fixes:
Part of #4529.
Release note _(write NONE if no user-facing change)_:
Added optional KV-event recording to a file (kvEventsConfig.eventRecordingPath) for offline replay and validation.
Test plan:
/v1/models nothing tells you. This adds a gauge and two log lines for that case (Fixes #4429).What type of PR is this?
/kind feature
What this PR does / why we need it:
An InferencePool is meant to serve one base model, but if its endpoints report different base models on /v1/models nothing tells you. This adds a gauge and two log lines for that case. Routing does not change.
llm_d_epp_pool_base_models{name} is the number of distinct base models (entries with no Parent) across the pool's ready endpoints. It uses the same name label as the other pool gauges.The check lives in pkg/epp/datalayer/logger next to the other pool gauges, since the models extractor only sees one endpoint at a time. I can rename the metric or the label if you prefer something else.
The table test in pkg/epp/datalayer/logger/base_models_test.go covers start, clear, re-entry, LoRA entries, endpoints that have not reported, the 10-endpoint cap and pool deletion. go test -race ./pkg/epp/datalayer/... ./pkg/epp/metrics/..., golangci-lint and make verify-telemetry pass.
I also ran it on kind with two llm-d-inference-sim pods and the EPP in selector mode. With one sim on Llama and one on Qwen, the warning fired once with both endpoint=model pairs and the gauge read 2. Switching the second sim to Llama plus a LoRA adapter logged the clear line once and the gauge went to 1. Adding a third ready endpoint that serves /metrics but returns 404 on /v1/models left the gauge at 1 with no new log line.
Limits: promtool's metric lint flags the new gauge for "abbreviated units". It flags every llm_d_* metric the same way, because it reads the d in the prefix as days.
Which issue(s) this PR fixes:
Fixes #4429
Release note _(write NONE if no user-facing change)_:
EPP exports llm_d_epp_pool_base_models{name} and logs a warning when ready endpoints in a pool report different base models.Adds an llm_d_epp_pool_base_models{name} Prometheus gauge and transition-only mismatch/recovery logs to EPP's periodic metrics refresher so operators can detect when ready endpoints in an InferencePool serve different base models on /v1/models. LoRA adapters (Parent != ""), entries without an ID, and endpoints that have not reported /v1/models are excluded from the distinct base-model count. Request scheduling and routing behavior remain unchanged.
llmdInferencePoolBaseModels (llm_d_epp_pool_base_models) with label name (ALPHA) in pkg/epp/metrics/llm_d_router_metrics.go#L249-L256 and pkg/epp/metrics/metrics.go#L479-L481, documented in docs/metrics.md#L422.mismatchedPools map[string]bool inside runPrometheusRefresher in pkg/epp/datalayer/logger/logger.go#L54-L68 and clears it whenever datastore.PoolGet() returns an error so a recreated pool warns again.recordPoolBaseModels reads attrmodels.ModelsAttributeKey from each ready endpoint returned by PodList(podsWithFreshMetrics(...)), collects unique m.ID values where m.ID != "" && m.Parent == "", updates the gauge (even when len(podMetrics) == 0), and logs once on transitions between len(bases) > 1 (capped at 10 sorted endpoints plus and N more) and len(bases) == 1, keeping mismatch state when len(bases) == 0.default/pod0 (reporting base llama and LoRA sql-lora with Parent: "llama") and default/pod1 (reporting qwen) are scraped by models-data-source.recordPoolBaseModels sets llm_d_epp_pool_base_models{name="test-pool"} to 2 and logs one warning listing baseModels=["llama" "qwen"] and endpoints=["default/pod0=llama" "default/pod1=qwen"].default/pod1 is replaced by a llama endpoint, the gauge updates to 1 and one recovery log (Endpoints in the pool report the same base model again) is emitted; if all ready endpoints disappear transiently (len(bases) == 0), the gauge becomes 0 without clearing mismatchedPools.logger.go:157 (all CI checks in ci.json passed (unit-tests, lint, e2e-tests, CodeQL, DCO, typos); 0 existing reviews or open threads) awaiting @chethanuk's response.v1.19.6 actor + loopback tracing adapter under shared guides/agent-substrate/actors/opencode/ (Dockerfile, adapter.py, entrypoint.sh, opencode.json.tmpl, test_adapter.py) aligned to the...Adds a pluggable OpenCode v1.19.6 actor + loopback tracing adapter under shared guides/agent-substrate/actors/opencode/ (Dockerfile, adapter.py, entrypoint.sh, opencode.json.tmpl, test_adapter.py) aligned to the harness-neutral agent protocol:
X-Session-Id (with X-Hermes-Session-Id compatibility fallback) and forwards session + x-llm-d-inference-objective headers to llm-d.stream: true), live event: agent.tool.progress tool-execution updates bridged from OpenCode's /event bus, keepalive heartbeats, and AGENT_TURN_TRACE=1 telemetry (X-Agent-Turn-Trace JSON header on non-streaming turns and trailing event: agent.turn.trace SSE frame before data: [DONE] on streaming turns).guides/agent-substrate/always-on-agents/README.md and guides/agent-substrate/README.md to document both actors/hermes and actors/opencode side by side with the gateway's dynamic Harness Runtime selector.Part 3 of 3 for #3167 (Topology 1 in Agent Substrate x llm-d: Co-Design Ideas, stacked on #3161). Proves the Always-On Sandboxed Agents zero-wake gateway, dynamic Harness Runtime UI selector, real-time SSE streaming UX, IdleSuspender, and Dual-Plane Observability Dashboard are genuinely harness-agnostic: Hermes and OpenCode sessions run concurrently behind the same unmodified gateway under default SESSION_ID_HEADER=X-Session-Id with zero gateway restarts.
actors/opencode/ and doc additions until #3160 and #3161 merge.OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS=300000, OPENCODE_DISABLE_LSP_DOWNLOAD=1, bounded max_tokens context-overflow clamping, and non-starving SSE keepalive scheduling in adapter.py.132/132 unit tests passing (23/23 in actors/opencode/test_adapter.py including X-Session-Id forwarding, SSE token streaming, event: agent.tool.progress, event: agent.turn.trace, X-Agent-Turn-Trace, and error/disconnect handling + 37/37 in always-on-agents/gateway/test_server.py + 72/72 in scripts/tests/test_agent_substrate_*.py); offline --internal Docker E2E verified.python3 scripts/guide.py render guides --recursive --check, check guides/agent-substrate, and check-manifest exit 0.hermes-dev-e2e + OpenCode opencode-e2e simultaneously on one unmodified session-gateway, SESSION_ID_HEADER=X-Session-Id, AGENT_TURN_TRACE=1, Qwen/Qwen3-32B):GET /api/templates discovered both hermes-dev-e2e and opencode-e2e (ready: true, zero secret fields).Run go version using bash and report the version.): 3 live tool.progress events via event: agent.tool.progress, 7 incremental assistant.delta chunks (go1.27.4), and turn.done trace via event: agent.turn.trace (llm_call_count=2, inference_ms=713.47 ms, actor_exec_ms=1906.47 ms, latency_ms=5928.39 ms).uname -a (2 tool.progress, 80 assistant.delta, llm_call_count=2) and Turn 2 recalled PINEAPPLE-42 (15 assistant.delta, latency_ms=441.42 ms).GET /api/telemetry reported both hermes-dev-e2e and opencode-e2e sessions side by side; clean DELETE (200 OK) for both sessions.1116.1 ms resume), manual suspend (754 ms memory checkpoint) -> 0.11 ms zero-wake read, Turn 2 warm MEMORY resume (772.92 ms, live max_tokens 400 clamping retry), and clean DELETE (HTTP 200).guides/agent-substrate/always-on-agents/ sub-guide (Always-On Sandboxed Agents) layered directly onto the shared guides/agent-substrate/ base guide: Part 2 of 3 for #3167 (Topology 1 in Agent Substrate x llm-d...Adds the guides/agent-substrate/always-on-agents/ sub-guide (Always-On Sandboxed Agents) layered directly onto the shared guides/agent-substrate/ base guide:
always-on-agents/gateway/{server.py,test_server.py,Dockerfile}, always-on-agents/manifests/session-gateway.yaml) with:GET /api/templates, optional ACTOR_TEMPLATES allowlist, per-session actor_template selection on POST /api/sessions, and secret-free template metadata).SESSION_ID_HEADER=X-Session-Id, X-Agent-Turn-Trace, event: agent.turn.trace, event: agent.tool.progress with backward-compatible acceptance of event: hermes.tool.progress).Accept: text/event-stream emitting turn.started, turn.status, live tool.progress, incremental assistant.delta, and turn.done), SQLite WAL history + trace.tool_events storage, SPIFFE mTLS atenet-router forwarding, 60s IdleSuspender, and read-only vLLM + kubectl-ate telemetry.always-on-agents/gateway/static/index.html) with a dynamic Harness Runtime selector in the sidebar/new-session flow, per-session template badges, live streaming token rendering, real-time collapsible tool activity pills, live sidebar actor states, harness-neutral inline 3-way latency breakdown pills (Resume | llm-d | Actor), stacked request-latency bars, llm-d prefix-cache KPIs, and per-LLM-call routing traces.always-on-agents/README.md, always-on-agents/docs/images/{chat-view,dashboard-view}.png) reusing shared ../actors/hermes (--target dev) and ../manifests/, linked from guides/agent-substrate/README.md.Part 2 of 3 for #3167 (Topology 1 in Agent Substrate x llm-d: Co-Design Ideas, stacked on #3160). Layers interactive, zero-wake, multi-runtime streaming cloud agent sessions directly onto the shared base guide with zero duplicated inference, actor, or prerequisite docs.
always-on-agents/ additions and parent README link until #3160 merges.actors/opencode/ on this exact same unmodified gateway and harness-neutral protocol.109/109 unit tests passing (37/37 in always-on-agents/gateway/test_server.py covering /api/templates discovery, per-session actor_template selection, SESSION_ID_HEADER boundary validation, SSE streaming, live tool.progress, tool_events SQLite persistence, inflight cleanup, and error paths + 72/72 in scripts/tests/test_agent_substrate_*.py).python3 scripts/guide.py render guides --recursive --check, check guides/agent-substrate, and check-manifest exit 0.session-gateway under default SESSION_ID_HEADER=X-Session-Id, Qwen/Qwen3-32B):GET /api/templates discovered 6 templates (default_template="hermes-dev-e2e", both hermes-dev-e2e and opencode-e2e ready: true, zero secret fields leaked).hermes-dev-e2e) and OpenCode (opencode-e2e) sessions on the same gateway without restarts.uname -a + PINEAPPLE-42): 2 live tool.progress events, 80 assistant.delta chunks, turn.done trace (llm_call_count=2, inference_ms=2029.02 ms, actor_exec_ms=251.46 ms, latency_ms=14303.01 ms).PINEAPPLE-42 under X-Session-Id (15 assistant.delta chunks, llm_call_count=1, latency_ms=441.42 ms).go version): 3 live tool.progress events (agent.tool.progress), 7 assistant.delta chunks (go1.27.4), turn.done trace (llm_call_count=2, inference_ms=713.47 ms, actor_exec_ms=1906.47 ms, latency_ms=5928.39 ms).GET /api/telemetry listed both sessions side by side with exact actor_template values; clean DELETE (200 OK) for both sessions.go test -bench=. -benchmem -benchtime=200ms ./pkg/epp/datalayer (234.07 s total = 919.01 ms resume + 6.47 s llm-d across 3 calls + 226.68 s tools), manual suspend -> zero-wake SQLite read (served_from="sqlite_zero_wake", read_ms=0.24 ms), Turn 2 warm MEMORY resume (1383.86 ms), and clean DELETE (HTTP 200).guides/agent-substrate/ into a zero-duplication shared foundation (base README.md + guide.yaml, multi-stage actors/hermes, parameterized manifests/) plus the focused fleet-benchmark/ sub-guide: Part 1 of 3...Refactors guides/agent-substrate/ into a zero-duplication shared foundation (base README.md + guide.yaml, multi-stage actors/hermes, parameterized manifests/) plus the focused fleet-benchmark/ sub-guide:
llm-d + Agent Substrate deployment, metrics, and shared cleanup in guides/agent-substrate/README.md + guides/agent-substrate/guide.yaml.hermes/actor/ -> actors/hermes/ with a 2-stage Dockerfile (base for 1,000-agent benchmark, dev adding git, curl, ripgrep, Go 1.27.4, /workspace), env-driven HERMES_TOOLSETS / HERMES_CWD, harness-neutral session header support (X-Session-Id bridged to X-Hermes-Session-Id inside aiohttp middleware when X-Hermes-Session-Id is absent, while forwarding validated x-session-id / x-hermes-session-id / x-llm-d-inference-objective outbound only to requests matching MODEL_BASE_URL's host and port), and opt-in AGENT_TURN_TRACE=1 in sitecustomize.py supporting both non-streaming (X-Agent-Turn-Trace header <= 6144 B) and real-time SSE streaming (Accept-Encoding: identity, router x-request-id preservation with body id fallback, streaming outbound token/usage capture, and trailing event: agent.turn.trace frame before data: [DONE]).manifests/hermes-workerpool.yaml.tmpl and manifests/hermes-template.yaml.tmpl (noting that envsubst requires exporting listed variables), keeps manifests/hermes-egress-policy.yaml.tmpl strictly router-only for fleet-benchmark/, and adds manifests/egress-policy-dev.yaml.tmpl for developer sandboxes.hermes-driver.yaml, hermes_fleet_driver.py, and benchmark walkthrough) into guides/agent-substrate/fleet-benchmark/ and updates scripts/tests/test_agent_substrate_*.py.Part 1 of 3 for #3167 (Topology 1 in Agent Substrate x llm-d: Co-Design Ideas). Eliminates duplicated actor/manifest/guide files and standardizes the harness-neutral session/trace protocol (X-Session-Id, AGENT_TURN_TRACE, X-Agent-Turn-Trace, event: agent.turn.trace) so both Always-On Sandboxed Agents (#3161, #3162) and the 1,000-agent fleet benchmark layer cleanly on one shared foundation.
docs/well-lit-paths/guides.yaml.always-on-agents/ gateway, dynamic Harness Runtime selector, SSE streaming, dashboard, docs) and #3162 (Part 3: pluggable actors/opencode/ harness on the same harness-neutral protocol).83/83 tests passing in scripts/tests/test_agent_substrate_{fleet_driver,manifests,sitecustomize}.py with real aiohttp and httpx installed (82 passed, 1 skipped via pytest.importorskip in stdlib-only CI), covering router-only vs dev egress policies, MODEL_BASE_URL host-scoping and fail-closed behavior, router x-request-id preservation, X-Session-Id -> X-Hermes-Session-Id middleware bridging, SSE event: agent.turn.trace framing before [DONE], streaming usage/finish-reason capture, and identity encoding.docker build --target base and docker build --target dev on guides/agent-substrate/actors/hermes both pass.python3 scripts/guide.py render guides --recursive --check, check guides/agent-substrate, check-manifest, and emit --context ci all exit 0.fleet-benchmark/ at reduced scale HERMES_AGENTS=3): built actors/hermes --target base, golden snapshot ready (48.9s), --agents 3 --turns 2 --concurrency 3 passed (3/3 codename recall, Turn 2 0.49s), 3/3 suspended to ACTOR_STATE_SUSPENDED, and --recall-only passed (3/3 post-suspend recall, 0.84s).hermes-dev-e2e with AGENT_TURN_TRACE=1, Qwen/Qwen3-32B, default SESSION_ID_HEADER=X-Session-Id):uname -a + codename PINEAPPLE-42): 2 live tool.progress events, 80 incremental assistant.delta chunks, event: agent.turn.trace delivered (llm_call_count=2, inference_ms=2029.02 ms, actor_exec_ms=251.46 ms, latency_ms=14303.01 ms).What was the secret codename I just told you?): recalled PINEAPPLE-42 via X-Session-Id -> X-Hermes-Session-Id middleware bridge (15 assistant.delta chunks, llm_call_count=1, latency_ms=441.42 ms).agent-identity, for requests that carry no identity headers or only a session header the operator added. Design and trade-offs are in the linked issue (Fixes #4785).What type of PR is this?
/kind feature
What this PR does / why we need it:
Adds an opt-in content-derived thread identity to agent-identity, for requests that carry no identity headers or only a session header the operator added. Design and trade-offs are in the linked issue.
token-producer: new produceAtRequestHeader parameter to tokenize at the RequestHeader extension point. Off by default; without it the plugin is unchanged.agent-identity: new implicitIdentity parameter, with settings under implicitIdentityConfig. A request with no thread header, and either no session header or one from additionalSessionHeaders, gets its thread-id from its content; a request with no session header also gets that id as its agent-identity. All other requests behave as before.implicitidentity package: matches a request to the thread whose previous request it extends, in a bounded in-memory table with TTL eviction.Test plan (new tests):
implicitIdentity on.additionalSessionHeaders requests get content-derived threads; requests without usable tokens still get a thread-id.produceAtRequestHeader: tokens at the header step, Produce skips, and a render failure is fail-open.agent-identity, and invalid combinations fail to load.Which issue(s) this PR fixes:
Fixes #4785
Release note _(write NONE if no user-facing change)_:
agent-identity: new opt-in `implicitIdentity` parameter derives `thread-id` from the request content for requests without a thread header and without a built-in session header; a request without a session header also gets that id as `agent-identity`. Settings are under `implicitIdentityConfig`. token-producer: new `produceAtRequestHeader` parameter tokenizes at the RequestHeader extension point, which `implicitIdentity` requires.vllm.Inference, sglang.api.v1) in the EPP and the Coordinator.What type of PR is this?
/kind feature
What this PR does / why we need it:
Part of #3979. #4583 covered JSON bodies. This PR covers native gRPC routes (vllm.Inference, sglang.api.v1) in the EPP and the Coordinator.
1. gRPC method allowlist
A model server serves admin RPCs on its generation port. vLLM serves vllm.Control (Shutdown, LoadLora, UpdateWeights, and others). SGLang serves Abort, weight updates, and SetInternalState on sglang.api.v1.SglangService. The EPP sends a path that no parser claims to the fallback parser, and the charts put passthrough-parser last for gRPC pools. The Coordinator forwards each unregistered path to the gateway. A client can therefore call these RPCs through the router.
PERMISSION_DENIED (HTTP 403) unless a parser claims the method or the allowlist names it. The check runs first in the request-headers phase. It therefore also covers a request without a body, which the EPP otherwise routes to a random endpoint./grpc.health.v1.Health/Check, /grpc.health.v1.Health/Watch, /sglang.api.v1.SglangService/HealthCheck, and /vllm.grpc.engine.VllmEngine/HealthCheck.requestHandler.grpcAllowedMethods (EPP) and server.grpc_allowed_methods (Coordinator) add methods by full name, for example /vllm.Control/GetModelInfo. The match is exact.The Coordinator sends only vllm.Inference/Generate, vllm.Inference/GenerateStream, and sglang.api.v1.SglangService/Generate to workers. Parsers claim all three, so a Coordinator deployment needs no entry on either engine.
2. Transfer fields on native gRPC generate routes
Under strip and reject, the EPP drops the client's transfer fields. These fields name the peer that a worker pulls KV blocks or encoder outputs from.
| Engine | Fields |
|---|---|
vllm.Inference | kv.kv_transfer_params, kv.ec_transfer_params |
sglang.api.v1 | bootstrap_host, bootstrap_port, bootstrap_room |
Under trustCaller the EPP keeps them, unless the request carries x-llm-d-unsanitized-body: true. As on JSON token routes, the EPP drops the fields and never rejects the request. The EPP logs the drop and does not count it in body_fields_sanitized_total.
The parsers remove the fields through a new optional interface, TransferFieldsDropper, with the wire helpers vllmwire.DropTransferParams and sglangwire.DropBootstrap. The EPP forwards a request without these fields as the same frame, with no allocation.
PERMISSION_DENIED from the EPP and from the Coordinator passthrough. The exceptions are the health checks and the methods that the new setting names. The rule covers admin RPCs, inference RPCs without a parser (for example sglang.api.v1.SglangService/OpenAiChatCompletions), and gRPC reflection. A deployment that calls such a method through the gateway must list it. A pool whose only parser is passthrough-parser has no claimed method, so it must list each gRPC method that it serves. The charts render such a pool for router.modelServers.type: triton and for payload-agnostic.yaml.requestHandler.bodyFieldsSanitizationPolicy: trustCaller. docs/coordinator_architecture.md already requires this setting for each EPP behind the Coordinator. Without it, the EPP now drops the fields on gRPC legs too.Two tests asserted that a vllm.Control RPC passes through:
TestVLLMGRPC_DecodeOnlyTLSAndControlPassthrough (Coordinator) now lists GetServerInfo, still asserts its passthrough over TLS, and asserts PermissionDenied for GetModelInfo.vllm.Control now sends the gRPC content type and lists the method. A new subtest asserts the denial.TestDirector_VertexAIPrefixCache built a StreamingServer without a parser registry. It now gets a registry with the Vertex AI parser, as in production.
trustCaller, and the worker gRPC NetworkPolicy template. A second PR adds them.application/grpc, application/grpc+<subtype>). The gRPC over HTTP/2 specification tells a server to answer other content types with HTTP 415.routed_dp_rank, disagg_prefill_dp_rank), which #4533 covers.-race for ./pkg/..., ./cmd/..., ./internal/..., and ./apix/...../test/integration/...), with new cases for the method check and for the field drop on both engines under strip and trustCaller.make lint and make lint-security.test/e2e suites run in CI only.Which issue(s) this PR fixes:
Part of #3979
Release note:
The EPP and the Coordinator answer a gRPC call with PERMISSION_DENIED unless a parser or route handles the method, the method is a health check, or `requestHandler.grpcAllowedMethods` (EPP) or `server.grpc_allowed_methods` (Coordinator) names it. The EPP drops client-supplied `kv.kv_transfer_params` and `kv.ec_transfer_params` on `vllm.Inference` and `bootstrap_host`, `bootstrap_port`, and `bootstrap_room` on `sglang.api.v1`, unless `requestHandler.bodyFieldsSanitizationPolicy` is `trustCaller`. An EPP behind a Coordinator must set `trustCaller` on gRPC pools. A gRPC pool whose only parser is `passthrough-parser` must list each method that it serves.Restricts unmatched gRPC calls at both the EPP and Coordinator passthrough to four default health-check methods plus explicitly configured grpcAllowedMethods / grpc_allowed_methods, returning PERMISSION_DENIED otherwise. On native gRPC generate routes (vllm.Inference and sglang.api.v1), the EPP now drops client-supplied transfer/bootstrap fields under strip and reject (or when x-llm-d-unsanitized-body: true is set under trustCaller), leaving clean requests and HTTP JSON sanitization paths unchanged.
pkg/common/request/grpc_methods.go:48-85): GRPCMethodAllowlist allows /grpc.health.v1.Health/Check, /grpc.health.v1.Health/Watch, /sglang.api.v1.SglangService/HealthCheck, and /vllm.grpc.engine.VllmEngine/HealthCheck by default and validates full /package.Service/Method entries at startup.pkg/epp/handlers/request.go:52-54,111-121, pkg/epp/handlers/parsers.go:124-134): HandleRequestHeaders runs rejectDisallowedGRPCMethod first when Content-Type is application/grpc*, permitting methods claimed by a non-fallback parser or allowed by GRPCMethodAllowlist and returning errcommon.Forbidden (codes.PermissionDenied) before responders or bodyless random-endpoint fallback run.pkg/coordinator/server/passthrough.go:103-107): passthroughHandler.ServeHTTP enforces the same GRPCMethodAllowlist on unregistered application/grpc* paths before proxying to the gateway.pkg/epp/framework/interface/requesthandling/parser.go:102-108, pkg/epp/requestcontrol/director.go:633-674): Director.sanitizeClientFields delegates non-map payloads to TransferFieldsDropper.DropTransferFields (vllmwire.DropTransferParams in pkg/common/grpc/vllm/vllmwire/rewrite.go:52-107 and sglangwire.DropBootstrap in pkg/common/grpc/sglang/sglangwire/sglangwire.go:461-483), returning the original frame unallocated when no transfer fields are present and marking body.Mutated = true for repackage when stripped.POST /vllm.Control/Shutdown with Content-Type: application/grpc: StreamingServer.HandleRequestHeaders sees no parser claims the path and grpcMethods.Allows is false, so it immediately returns Forbidden (PERMISSION_DENIED) without routing to a pod.POST /vllm.Inference/Generate carrying kv.kv_transfer_params under the default strip policy: vllminference-parser claims the method, Director.sanitizeClientFields invokes VllmInferenceParser.DropTransferFields -> vllmwire.DropTransferParams, strips kv_transfer_params (removing the kv submessage if empty), and sets body.Mutated = true so repackage forwards the sanitized frame.bodyFieldsSanitizationPolicy: trustCaller on vllm.Inference/Generate: sanitizeClientFields returns early without inspecting or copying the frame unless x-llm-d-unsanitized-body: true is present.## Benchmark section with them, between Verification and Cleanup.The [E-Disaggregation guide](guides/multimodal-serving/e-disaggregation/README.md) described
when encode disaggregation should help, but carried no measurements. This adds a ## Benchmark
section with them, between Verification and Cleanup.
guides/multimodal-serving/e-disaggregation/README.md โ new ## Benchmark section:Decode, aggregation-epp) and E/PD (an encode-only pod plus a prefill+decode pod,e-disaggregation-epp), and why the comparison is E/PD and not E/P/D.
token lengths, request count, concurrency, rates, seed.
guides/multimodal-serving/e-disaggregation/benchmark-results/ โ the three comparisonplots and summary.csv (one row per run).
Fix: #1954
Processor.Run polls a 1 ms ticker and runs a full dispatchCycle on every tick.The EPP flow-control processor now polls its dispatch ticker once per 100 ms instead of once per millisecond while its queues are empty, which removes the CPU burn and allocation churn of a full dispatch cycle on every idle tick. A new request still dispatches immediately, and a queue that holds work keeps the 1 ms cadence.
Processor.Run polls a 1 ms ticker and runs a full dispatchCycle on every tick. A cycle locates the endpoint pool, partitions it into prefill/decode/interleaved, runs the saturation detector over every endpoint two or three times, and rewrites about eight gauges. On an idle processor โ no requests at all โ all of that is pure waste, and it runs 1000 times per second per pool.
Measured on 2188d9fa with the benchmark added in this PR (BenchmarkDispatchCycleIdle, Apple M4, empty queues):
| Endpoints | ns/cycle | B/cycle | allocs/cycle | CPU at 1 kHz | Garbage at 1 kHz |
|---|---|---|---|---|---|
| 0 | 1033 | 496 | 16 | 1.0 ms/s | 0.5 MB/s |
| 10 | 1236 | 1,168 | 22 | 1.2 ms/s | 1.2 MB/s |
| 100 | 2625 | 6,768 | 25 | 2.6 ms/s | 6.8 MB/s |
| 1000 | 11497 | 52,081 | 28 | 11.5 ms/s | 52 MB/s |
The allocation column matters as much as the CPU one: an idle replica generating 52 MB/s of garbage at 1000 endpoints keeps the GC running for no reason.
dispatchCycle now reports whether it found something it could have dispatched. Run reads that flag and, while it is false, polls once per idleCycleEvery ticks (100 ms) instead of every tick. The 1 ms cadence is kept otherwise.
Two properties prevent a latency regression:
enqueueChan case calls dispatchCycle directly and resets the idle counter, so a fresh request never waits for the slow cadence.selectItem returns an item, and also when a band is held back by the saturation gate: the cycle cannot see behind the gate, so it assumes the band may hold work. That is the case where a blocked request waits for capacity to free up, and it must keep polling at 1 ms.Only the idle sampling rate changes. The saturation gauges, the capacity-utilization gauges and the regime sample are still refreshed every 100 ms, and drainEstimator.syncBusy derives its intervals from timestamps rather than assuming a tick length, so the Retry-After estimate is unaffected.
TestProcessor_IdleTickerCadence drives a real ticker with an empty queue for 300 ms and asserts the saturation detector ran at most 30 times. On main it runs 300 times; with this change it runs a handful.TestProcessor_BusyTickerKeepsFastCadence queues an item behind a saturated band (gated, so it cannot dispatch) and asserts the cycle keeps running at the fast cadence.newTestHarness now takes a testing.TB so the benchmark can reuse it. No test behaviour changed.
go test ./pkg/epp/...
golangci-lint run ./pkg/epp/flowcontrol/...
Refs #3961 (item 6).
processor.go:632 awaiting @zhouyou9505's response.x-data-parallel-rank) (Fixes #4936).What type of PR is this?
/kind bug
What this PR does / why we need it:
Under hybrid/external DP LB, vLLM runs one bootstrap server per prefill instance and the MooncakeConnector registers workers keyed by LOCAL dp rank, while the EPP picks a GLOBAL rank (x-data-parallel-rank). On any prefill pod started with --data-parallel-start-rank > 0 the sidecar's lookup of that global rank against the bootstrap registry missed, and every request routed to the pod failed with 502 (mooncake prefill <pod>:8000 has no engine_id for dp_rank "6"). Prefill pods at start-rank 0 kept working, so the bug only shows in multi-node DP prefill groups.
This PR indexes each bootstrap registry entry by the global dp rank parsed from the vLLM engine_id suffix <uuid>_dpN in addition to its raw key:
fetchMooncakeEngineMap now builds a mooncakeEngineMap with byRank (raw registry keys) and byGlobal (rank from the _dpN suffix).dp_size_local 6, start-rank 2), which would pick the wrong engine._dpN suffix (e.g. SGLang) fall back to the raw keys, preserving today's behavior.The bootstrap registry map cache (mooncakeEngineIDs LRU) now stores *mooncakeEngineMap; existing tests were updated for the new cache type.
Which issue(s) this PR fixes:
Fixes #4936
Release note _(write NONE if no user-facing change)_:
Fixes PD-disaggregation mooncake routing returning 502 for every request routed to a prefill pod with --data-parallel-start-rank > 0 under hybrid/external DP LB.connector_mooncake.go:308 awaiting @SteeveRan's response.prepareMooncakeKVParams auto-picks a bootstrap registry entry and pins prefill with its raw key as X-Data-Parallel-Rank (Fixes #4938).What type of PR is this?
/kind bug
What this PR does / why we need it:
When the EPP provides no prefill rank, prepareMooncakeKVParams auto-picks a bootstrap registry entry and pins prefill with its raw key as X-Data-Parallel-Rank. Under hybrid/external LB the raw registry keys are the LOCAL dp ranks while the prefill frontend routes the header by GLOBAL rank, so on pods started with --data-parallel-start-rank > 0 the auto-pinned header named another pod's rank space and could disagree with the engine_id handed to decode in kv_transfer_params.remote_engine_id.
The fix translates the picked engine_id through its _dpN suffix (mooncakeGlobalRank, an independent implementation of the same parsing) and emits that global rank in the header, so the pinned header names the same engine whose engine_id decode receives:
main, whose registry is a plain raw-key map. When #4937 merges, this PR rebases onto its mooncakeGlobalRank with a trivial conflict resolution._dpN suffix (e.g. SGLang) keep the raw key โ today's behavior. The existing TestMooncakePrefillDPRankNoneSelectsRandomRank covers exactly that path and is untouched.TestMooncakePrefillDPRankNoneUsesGlobalRankFromSuffix: no EPP rank, local keys 0โ1 with engine_ids suffixed _dp6/_dp7 โ prefill header is a global rank (6/7) whose engine_id matches remote_engine_id sent to decode.Which issue(s) this PR fixes:
Fixes #4938
Release note _(write NONE if no user-facing change)_:
Fixes the PD-disaggregation mooncake path auto-pinning a LOCAL dp rank in X-Data-Parallel-Rank when no EPP rank is provided, which misrouted prefill on pods with --data-parallel-start-rank > 0.connector_mooncake.go:135 awaiting @SteeveRan's response.docs/coordinator_architecture.md lists the 503 case in the error... (Fixes #4944)What type of PR is this?
/kind bug
What this PR does / why we need it:
Chaos testing in #4851 (scenarios 8 and 9) found two problems in the coordinator's render step:
internal error. 7 of them failed only after the full render timeout (15s in that deployment). There was no retry, although the other tokenizer pod was healthy.internal error, which does not tell the client the cause.This PR changes the render step's HTTP call:
503 with render service unavailable (request_id: <id>). A new pipeline.ErrServiceUnavailable sentinel carries this from the step to classifyPipelineError. Other final failures keep their 502.timeout, capped at 30s. With the two equal, a dial to an address that drops SYNs hit the client deadline first and surfaced as a context error with no dial error, so it got 502 instead of 503. The coordinator.yaml comment documents the cap.Tradeoffs for review:
timeout. The coordinator.yaml comment documents this. A retry that skips timeouts would miss 7 of the 10 failures measured in scenario 8.pipeline.max_step_reruns, which defaults to 0 and covers only the gRPC prefill and decode legs.error_code=upstream_transport instead of internal. A final timeout or dropped connection after the connection was established stays internal.timeout, connecting to the render service gives up after 15s instead of 30s.docs/coordinator_architecture.md lists the 503 case in the error mapping.
Test plan:
render service unavailable and the request id, for both the step error and the client response10.255.255.1)go test -race ./pkg/coordinator/... and make presubmit passWhich issue(s) this PR fixes:
Refs #4851
Fixes #4944
Release note _(write NONE if no user-facing change)_:
The coordinator retries a failed render request once after a connection error, timeout, or 5xx from the tokenizer, so a request can wait up to twice the render `timeout`. When no tokenizer can be reached, clients get 503 `render service unavailable` with the request id instead of 502 `internal error`.render.go:142 awaiting @roytman's response.precise-prefix-cache-producer, every KV event produces an index_add or index_evict span even when kvEventsConfig.tracing is off (Fixes #4962).What type of PR is this?
/kind bug
What this PR does / why we need it:
With router tracing on and the precise-prefix-cache-producer, every KV event produces an index_add or index_evict span even when kvEventsConfig.tracing is off. No span is running when a KV event is processed, so each one is the root of its own trace, and these traces make up almost all of the exported volume.
When Config.Tracing is off, NewPool now uses the index without its tracing wrapper, through a new kvblock.WithoutTracing helper that returns the index NewTracedIndex wrapped. With event tracing on, the pool keeps the traced index and the index spans nest under events_process as before. The request path keeps the traced index, so index_walk spans are unchanged, and the index metrics sit below the tracing wrapper, so they are unchanged too. The comment on Config.Tracing and the producer README describe the index spans as part of event tracing.
Benchmark on the same workload (one vLLM pod, Qwen3-30B-A3B, 55 agentic sessions, 1,150 requests, always_on, kvEventsConfig.tracing unset):
main | This PR | |
|---|---|---|
| KV-event messages received | 65,720 | 62,790 |
| Traces | 155,541 | 1,151 |
Request traces (each with its index_walk) | 1,150 | 1,150 |
Single-span index_add / index_evict traces | 154,390 | 0 |
| Exported spans as OTLP JSON | 100 MB | 14 MB |
Tests:
index_add under events_process with it on.WithoutTracing returns the wrapped index for both traced wrappers, and returns an index without the wrapper unchanged.make presubmit passes.Which issue(s) this PR fixes:
Fixes #4962
Release note _(write NONE if no user-facing change)_:
With `kvEventsConfig.tracing` off (the default), the precise prefix cache producer no longer emits an `index_add` or `index_evict` span, each its own trace, for every KV event. These spans are emitted with event tracing on, under `events_process`.pool.go:366 awaiting @pavanipenumalla's response.docs/operations/components/router-high-availability.md, one page for the router's HA features. Router Operations summarizes the HA modes, and the rest lives across the llm-d-router repo.Adds docs/operations/components/router-high-availability.md, one page for the router's HA features. Router Operations summarizes the HA modes, and the rest lives across the llm-d-router repo. The page covers:
p2p-syncer or redis-syncer, peer discovery with k8s-peer-discovery, and request-level coordination of rollout revisions.router.md links to the page, and its plugin compatibility note says that per-replica plugins such as approximate prefix caching need a cross-replica syncer in active-active mode, instead of telling readers to avoid them. The page sits under Operations in docs/menu-config.json and docs/operations/README.md.
Docs only. Not run on a cluster.
llm-d-router main (2188d9fa): chart values.yaml and templates, pkg/epp/server/options.go, and the p2p-syncer, redis-syncer, k8s-peer-discovery and flow control READMEs.uvx prek run --from-ref origin/main --to-ref HEAD passes (markdownlint, check json).Limits: the failover times and scaling factors in the HA modes table are the numbers from the router's operations guide, which the page cites.
router-high-availability.md, router.md awaiting @vMaroon's response.llm-d-incubation/llm-d-infra-providers, the community-owned home for per-provider infrastructure provisioning tooling and guides (everything up to "the cluster is ready...This is the concrete execution step for RFC #2168: create llm-d-incubation/llm-d-infra-providers, the community-owned home for per-provider infrastructure provisioning tooling and guides (everything up to "the cluster is ready to host llm-d"). One sub-folder per provider, each with its own OWNERS reviewing its own PRs. Any provisioning method is acceptable (guided docs, scripts/IaC, AI skills), and per the discussion in #2168 a provider sub-folder may link out to externally hosted tooling; this repo is the centralized discovery entry point. Provisioning tooling is qualified against a dimension-labeled conformance/validation suite rather than by prescribing a method.
Running llm-d has two layers: infrastructure provisioning (accelerators, RDMA networking, drivers, CRDs) and stack installation (well-lit path guides). The guides are maintained and CI-validated; docs/infrastructure is loosely maintained, and core llm-d cannot own provisioning tooling for every provider and accelerator without stalling core velocity (see #2168 for the full problem statement; feedback there has been supportive, including from project maintainers).
In scope:
providers/<name>/ with per-provider OWNERS), including links to externally hosted provider toolingllm-d/docs/infrastructure provider and gateway contentOut of scope:
https://github.com/yangligt2/llm-d-infra-providers-poc - ready to transfer as the initial content:
docs/infrastructure and awaiting owners.llmd-infra-check runner, static checks and NCCL/NIXL fabric micro-tests labeled with the same dimensions the guides use (infra_provider, accelerator, rdma, dra, router_mode, gateway_provider).conformance/examples/.llm-d-incubation/llm-d-infra (helm charts for deploying llm-d); this repo is about cluster readiness, not stack deployment.llm-d-incubation/hermes (cluster configuration scanning / self-test generation) is adjacent to the validation suite; we propose reconciling the two in sig-installation as part of the first milestone rather than blocking repo creation on it.llm-d/docs/infrastructure provider contentThe ownership model is per-provider: each providers/<name>/ sub-folder carries its own OWNERS file, and contributions touching a given provider's infrastructure are approved by that provider's maintainers, not by the repo-level maintainers. We explicitly want a maintainer from each infra provider to own approvals for their sub-folder, and ask each provider to nominate at least one. Repo-level maintainers only curate repository structure and the shared conformance framework.
Bootstrap (repo-level and GKE provider):
Create llm-d-incubation/llm-d-infra-providers as an incubation repository. SIG: Installation.
/cc @liu-cong @gushob21 @ahg-g @chcost @robertgshaw2-redhat @xiaojun-zhang @chewong
No description provided.
Extends precise-prefix-cache-routing and predicted-latency-routing to SGLang on AMD ROCm (MI355X), adds centralized ROCm 10 image components while bumping existing rocm720/rocm724 SGLang image tags to v1.0.0, and wires nightly E2E and Slack notification workflows. Router Helm values and the shared CPU tokenizer deployment template remain unchanged.
rocm10-mi355x/kustomization.yaml (v1.0.0-rocm10-mi35x-20261201) and updates optimized-baseline/modelserver/amd/sglang/base/patch-sglang.yaml with --watchdog-timeout=1800, 128Gi memory limit, and /health httpGet startup/readiness probes.predicted-latency-routing/modelserver/amd/sglang/base/kustomization.yaml inherits optimized-baseline/modelserver/amd/sglang/base (llm-d.ai/guide: optimized-baseline) and pins rocm10-mi355x.precise-prefix-cache-routing/modelserver/amd/sglang/base/patch-sglang.yaml enables --page-size=64 and ZMQ KV-events on port 5556 (kv@$(POD_IP):$(POD_PORT)@Qwen/Qwen3-32B), paired with amd/sglang/tokenizer/kustomization.yaml (cpu-vllm/release).consolidate-status-*, and slack-channels.yaml / notify-slack-nightly.yaml triggers for both new ROCm SGLang lanes.ACCELERATOR_TYPE=amd and MODEL_SERVER=sglang in precise-prefix-cache-routing (INFRA_PROVIDER=base, MODEL=Qwen/Qwen3-32B).deploy.tokenizer applies guides/precise-prefix-cache-routing/modelserver/amd/sglang/tokenizer/, standing up the CPU vllm launch render pool so EPP's token-producer can tokenize prompts at http://precise-prefix-cache-routing-tokenizer:8000.deploy.modelserver applies guides/precise-prefix-cache-routing/modelserver/amd/sglang/base/, running 2 Qwen/Qwen3-32B (TP=2) SGLang replicas that publish 64-token KV-cache events over ZMQ port 5556 to EPP.What type of PR is this?
/kind bug
What this PR does / why we need it:
The vllmgrpc response parser decoded only the first length-prefixed gRPC frame of each response body chunk and ignored the rest. The handler's completeGRPCFrames already hands the parser whole frames and carries a split frame to the next chunk, but one chunk can still hold several frames. When a GenerateComplete shares a chunk with the preceding GenerateStreamChunk, its usage was dropped and the request was recorded with no token counts.
ParseResponse now walks every frame with grpcframe.ForEachPayload, the same iterator the sglanggrpc parser uses. Per-frame decoding (GenerateResponse, falling back to EmbedResponse) is unchanged and moved into parseResponsePayload. When several frames carry usage, the last one wins, matching the vertexai parser. A frame that cannot be decoded is reported in the returned error, and the usage of the other frames in the chunk is still returned. The single-frame toGenerateResponse and toEmbedResponse helpers are removed since they have no other callers.
The empty end-of-stream body handling from #3652 is unchanged.
Which issue(s) this PR fixes:
Fixes #3644
Test plan:
GenerateComplete reports the complete frame's usage (fails on main with no usage).go test ./pkg/epp/framework/plugins/requesthandling/... ./pkg/epp/handlers/... passes; golangci-lint run on the package reports 0 issues.Release note _(write NONE if no user-facing change)_:
Fixed the vLLM gRPC response parser dropping token usage when several gRPC frames arrive in one response body chunk.Fixes vllmgrpc response parsing where multiple length-prefixed gRPC frames arriving in a single chunk caused frames after the first to be ignored. It adopts grpcframe.ForEachPayload to iterate through all frames in the chunk, reporting the last usage observed and aggregating parse errors while preserving prior usage. The empty end-of-stream body handling remains unchanged.
grpcframe.ForEachPayload in pkg/epp/framework/plugins/requesthandling/parsers/vllmgrpc/vllmgrpc.go#L150 to sequentially extract each uncompressed message payload from multi-frame chunks.parseResponsePayload, testing GenerateResponse first and falling back to EmbedResponse.errors.Join.GenerateResponse_Chunk with 0 usage tokens, followed immediately by GenerateResponse_Complete with prompt: 20, completion: 15, cached: 5.grpcframe.ForEachPayload executes the callback for the first frame (no usage written) and then the second frame, recording completeUsage into result.Usage.ParseResponse returns result with complete token metrics intact, preventing the request from recording zero tokens.LMCache in-process mode is deprecated.
Migrate the Intel XPU CPU and filesystem overlays to LMCache MP mode with one cache server per node and inline transfers. Update the XPU Dockerfile to LMCache 0.5.8 and select the published PR image for the guide and nightly workflow.
Also, this PR is part of issue #3071 . Need to fix LMCache related issues for XPU before migrating xpu to use upstream images.
Note: I suppose we should migrate to MP mode for other platforms as well, but keep this PR for XPU only.
router inference and CPU cache reuse after a vLLM restart on Intel XPU B60 card:
LMCache server log
2026-11-20T13:06:57.412850656-08:00 [2026-11-20 21:06:57,412] LMCache INFO: Registered non-GPU context for instance 3377433928789861399 (model=Qwen/Qwen3-8B, world_size=1) (engine_driven_transfer.py:463:lmcache.v1.multiprocess.modules.engine_driven_transfer)
2026-11-20T13:09:20.414955092-08:00 [2026-11-20 21:09:20,414] LMCache INFO: Retrieved 2560 tokens in 1.233 seconds (engine_driven_transfer.py:734:lmcache.v1.multiprocess.modules.engine_driven_transfer)
vLLM log
2026-11-20T13:06:38.275770885-08:00 (APIServer pid=1) [2026-11-20 21:06:38,275] LMCache INFO: torch_dev=<module 'torch.xpu' from '/opt/venv/lib/python3.12/site-packages/torch/xpu/__init__.py'>, torch_device_type=xpu (_device_detect.py:311:lmcache.v1.platform._device_detect)
2026-11-20T13:06:54.640620268-08:00 (EngineCore pid=246) [2026-11-20 21:06:54,640] LMCache INFO: torch_dev=<module 'torch.xpu' from '/opt/venv/lib/python3.12/site-packages/torch/xpu/__init__.py'>, torch_device_type=xpu (_device_detect.py:311:lmcache.v1.platform._device_detect)
2026-11-20T13:06:57.340015505-08:00 (EngineCore pid=246) INFO 11-20 21:06:57 [factory.py:62] Creating v1 connector with name: LMCacheMPConnector and engine_id: 813c399b-93b8-45cd-86bf-1f5a6436469b
2026-11-20T13:06:57.411953103-08:00 (EngineCore pid=246) [2026-11-20 21:06:57,411] LMCache INFO: Creating transfer context (device_type=xpu, mode=engine_driven) (worker_transfer.py:1685:lmcache.v1.multiprocess.transfer_context.worker_transfer)
2026-11-20T13:06:57.413168026-08:00 (EngineCore pid=246) [2026-11-20 21:06:57,413] LMCache INFO: Worker engine-driven context registered (instance_id=3377433928789861399, mode=inline, groups=1) (worker_transfer.py:1092:lmcache.v1.multiprocess.transfer_context.worker_transfer)
2026-11-20T13:07:59.749819203-08:00 (EngineCore pid=246) INFO 11-20 21:07:59 [factory.py:62] Creating v1 connector with name: LMCacheMPConnector and engine_id: 813c399b-93b8-45cd-86bf-1f5a6436469b
2026-11-20T13:07:59.769758910-08:00 (EngineCore pid=246) [2026-11-20 21:07:59,769] LMCache INFO: Bind GPU block pool in LMCacheMPConnector scheduler (lmcache_mp_connector.py:1281:lmcache.integration.vllm.lmcache_mp_connector)
2026-11-20T13:09:21.740932383-08:00 (APIServer pid=1) INFO 11-20 21:09:21 [loggers.py:315] Engine 000: Avg prompt throughput: 4.1 tokens/s, Avg generation throughput: 0.6 tokens/s, Running: 0 reqs, Waiting: 0 reqs, XPU KV cache usage: 0.0%, Prefix cache hit rate: 0.0%, External prefix cache hit rate: 98.4%
2026-11-20T13:09:21.740956855-08:00 (APIServer pid=1) INFO 11-20 21:09:21 [metrics.py:107] KV Transfer metrics: LMCache MP lookup count=1, LMCache MP lookup avg latency (ms)=3.847This document defines the process for releasing llm-d-router.
@llm-d/router-release-managers team. Tag protection onrefs/tags/v* restricts who can push release tags, which is what triggers
the release build.
v0.9.0-rc.1): export VERSION=v0.9.0-rc.1
export BRANCH_VERSION=0.9
export REMOTE=origin
v0.9.0): export VERSION=v0.9.0
export BRANCH_VERSION=0.9
export REMOTE=origin
export LATENCY_PREDICTOR_TAG=v0.8.0-rc.1
export LLM_D_ASYNC_TAG=v0.11.0
git clone -o ${REMOTE} git@github.com:llm-d/llm-d-router.git
Create a new release branch from the main branch. The branch should be named release-${BRANCH_VERSION}, for example, release-0.9:
git checkout -b release-${BRANCH_VERSION}
A release branch should already exist. In this case, check out the existing branch:
git fetch ${REMOTE}
git reset --hard ${REMOTE}/release-${BRANCH_VERSION}
LATENCY_PREDICTOR_TAG in the Makefile resolves from the router release tag (via BUILD_REF). If the latency predictor tag does not align with the router version, update the default value of LATENCY_PREDICTOR_TAG in the Makefile to match your exported ${LATENCY_PREDICTOR_TAG}.Commit the change (if modified):
# Update LATENCY_PREDICTOR_TAG ?= vX.Y.Z in Makefile
git commit -a -s -m "release: set LATENCY_PREDICTOR_TAG to ${LATENCY_PREDICTOR_TAG}"
go.mod pins the github.com/llm-d/llm-d-async/api and /producer modules at ${LLM_D_ASYNC_TAG}. If not, bump them, read the release's RELEASE-NOTES.md section in llm-d-async for entries marked Breaking (the async-broker step builds api.RequestMessage and calls the producer directly), and run the coordinator tests before committing: go get github.com/llm-d/llm-d-async/api@${LLM_D_ASYNC_TAG} github.com/llm-d/llm-d-async/producer@${LLM_D_ASYNC_TAG}
go mod tidy
go test ./pkg/coordinator/...
git commit -a -s -m "release: bump llm-d-async api and producer to ${LLM_D_ASYNC_TAG}"
git push ${REMOTE} release-${BRANCH_VERSION}
git tag -s -a ${VERSION} -m "llm-d-router ${VERSION} Release"
git push ${REMOTE} ${VERSION}
ghcr.io/llm-d/llm-d-router-endpoint-picker) and sidecar image (ghcr.io/llm-d/llm-d-router-disagg-sidecar) to the [ghcr registry].Official v* tags receive :latest.
Release-candidate tags (-rc, for example v0.9.0-rc.1) do not.
Publishing the GitHub release sets the title, notes, and GitHub's pre-release listing.
It does not start the image pipeline or change image tags.
The tag push already built and published the images and uploaded the artifacts.
v0.1.0.RELEASE-NOTES.md with the following prompt: Please summarize these release notes into three clear sections:
1. Highlights (key features, performance wins, bug fixes)
2. Upgrade Steps & Deprecations (configuration changes, deprecated flags/metrics)
3. Known Issues (if any, otherwise omit)
Review the generated content, edit it if necessary to ensure accuracy, and then copy and prepend this summary at the very top of the release description box on GitHub.
This does not affect image tags.
Use the following steps to announce the release.
${VERSION} is set in your current shell): cat <<EOF
Subject: [ANNOUNCE] llm-d-router ${VERSION} is released
Hi all,
We are pleased to announce the release of llm-d-router ${VERSION}!
### Container Images
* Endpoint Picker: ghcr.io/llm-d/llm-d-router-endpoint-picker:${VERSION}
* Disaggregated Sidecar: ghcr.io/llm-d/llm-d-router-disagg-sidecar:${VERSION}
### Helm Charts (OCI)
* Standalone Chart: oci://ghcr.io/llm-d/charts/llm-d-router-standalone (version ${VERSION})
* Gateway Chart: oci://ghcr.io/llm-d/charts/llm-d-router-gateway (version ${VERSION})
### Release Notes
For more details, please see the GitHub release notes: https://github.com/llm-d/llm-d-router/releases/tag/${VERSION}
EOF
llm-d-contributors@googlegroups.com.[repo]: https://github.com/llm-d/llm-d-router
[ghcr registry]: https://github.com/orgs/llm-d/packages?repo_name=llm-d-router
[new release]: https://github.com/llm-d/llm-d-router/releases/new
[issue]: https://github.com/llm-d/llm-d-router/issues/new/choose
[CI release workflow]: https://github.com/llm-d/llm-d-router/actions/workflows/ci-release.yaml
[latency predictor releases]: https://github.com/orgs/llm-d/packages?repo_name=llm-d-latency-predictor
[llm-d-async releases]: https://github.com/llm-d/llm-d-async/releases
Part of #1982 (Phase 3, flow control).
Adds an Observability & Troubleshooting section to the flow-control guide, following the P/D, optimized-baseline and tiered-prefix-cache sections.
guides/flow-control/README.md: step 4 after "Enable monitoring" โ the signals for this path plus five failure modes. Removes the old one-line ## Observability section, which the precedents fold into step 4.docs/well-lit-paths/foundations/flow-control.md: Observability paragraph linking to the guide section.Interpretation only. Definitions stay in the architecture doc's Metrics & Observability table and queries in the shared PromQL reference. The path-specific points: flow control is work-conserving, so the queue is empty until the pool is under contention; the queue limits that reject to protect the EPP's memory are independent of the saturation detector that holds dispatch to protect the GPUs; and failureMode: "FailOpen" means an unhealthy EPP is bypassed with no queuing or fairness, which reads the same as a healthy idle pool.
Checked against docs/architecture/core/router/epp/flow-control.md, the shared {metrics,promql}.md, and this guide's router/flow-control.values.yaml (maxBytes: 10Gi, maxRequests: 1k, maxConcurrency: 132) and objectives.yaml (100/0/-10).
Not covered: the revocation/reclaim metrics, which need enableEviction: true and are linked out. No bundled flow-control alert rules exist; the section says so.
Docs only. Links and anchors resolve; make verify passes; no new markdownlint findings. No cluster run โ the failure modes come from the architecture docs and this guide's shipped values, not a live saturated pool.
alerting.md is updated, and the metric reference gains Coordinator and...Three pieces of router v1.0.0 documentation drift, all in docs:
docs/architecture/router/scheduling.md โ data-parallel-profile-handler was removed in llm-d Router v1.0.0 (llm-d/llm-d-router#3395), but the page still says it is deprecated and kept for backward compatibility. A configuration that references it now fails EPP startup. The note now says so and points at single-profile-handler.docs/operations/observability/metrics.md โ Coordinator โ router-metrics.md says coordinator metrics are scraped by following the Collect Metrics page, but that page stopped after the model servers and the EPP. This adds a coordinator step with the named metrics port the selector needs, an OSS PodMonitor, a GKE PodMonitoring, and the llm_d_coordinator_request_total check query.docs/operations/observability/metrics.md โ Disaggregation Sidecar โ same broken promise for llm_d_disagg_sidecar_* / moriio_dns_*. The sidecar's --metrics-port is 0 (disabled) by default, which neither page mentioned, so following the docs yielded no series. The new step documents enabling it, the named sidecar metrics port, both monitoring resources, and notes that the request counter appears only after traffic.The Prometheus query step is renumbered to Step 5, the one inbound link to the old anchor in alerting.md is updated, and the metric reference gains Coordinator and Sidecar rows.
PodMonitor (monitoring.coreos.com/v1) and PodMonitoring (monitoring.googleapis.com/v1) for both components, selecting the documented labels and named ports.step-3-query / step-4-query references remain.v1.37.0, kube-prometheus-stack 92.13.1):llm-d-router-coordinator:v1.0.0: applied the OSS PodMonitor as written, target up at http://<pod-ip>:9090/metrics, llm_d_coordinator_request_total scraped;llm-d-router-disagg-sidecar:v1.0.0 started with --metrics-port=9091: applied the OSS PodMonitor with that port, target up at http://<pod-ip>:9091/metrics, llm_d_disagg_sidecar_prefill_duration_seconds_count and moriio_dns_* scraped. (The checked-in example now uses the guides' 9095 / sc-metrics; the flag and named-port shape are the same.)PodMonitoring shape already checked in for the async multitenant guide; I did not run them on a GKE cluster.Docs only. This does not touch the guide manifests from #2879 (coordinator PodMonitor/PodMonitoring overlays) or the dashboard work in #2909. It also does not enable sidecar metrics in the guides โ the sidecar step documents the opt-in flag rather than changing eight guides' manifests.
/cc @sallyom
IsSampled() in llm-d-router's pkg/common/observability/metrics/exemplars.go).The router attaches a trace exemplar to a metric only when the request's span is head-sampled (IsSampled() in llm-d-router's pkg/common/observability/metrics/exemplars.go). If the OpenTelemetry Collector also tail-samples, it can drop a trace after its exemplar was recorded, so the exemplar link in the dashboard opens a trace that was never exported.
This adds a short note to Step 3 of docs/operations/observability/setup.md. It sits after the platform tabs because it applies to every backend. Docs only; no commands or manifests change.
Related to llm-d/llm-d-router#3584 (item 4, tail sampling). The GKE part of that item will come in a separate PR.
Validation: markdownlint passes on the changed file.
docs/operations.md describes standby EPP pods under priority routing and GKE preferred backends as "warm and synced". That reads as if standbys hold the primary's routing state.What type of PR is this?
/kind documentation
What this PR does / why we need it:
docs/operations.md describes standby EPP pods under priority routing and GKE preferred backends as "warm and synced". That reads as if standbys hold the primary's routing state. In practice only the datastore is synced: each replica watches the InferencePool and model server pods on its own, and its gRPC health port reports SERVING once PoolHasSynced() is true.
Request-derived routing state is built only from requests a replica schedules. That covers the approximate prefix-cache index (approx-prefix-cache-producer adds to its indexer in PreRequest), in-flight load, and flow control queues. A standby that received no traffic starts without it after failover.
This PR:
CrossReplicaSyncer is the only sharing path and shares only a capped recent prefix window;router.epp.crossReplica selects haMode: all-active, so the chart rejects it together with priority routing or GKE preferred backends (_epp-ha.tpl);Which issue(s) this PR fixes:
Release note _(write NONE if no user-facing change)_:
NONEWhat type of PR is this?
/kind bug
What this PR does / why we need it:
The in-memory index stores residency and engine-to-request mappings in separate bounded LRUs. An engine mapping can expire while its residency remains indexed, so a later block-removal event cannot resolve the mapping and leaves stale confirmed prefix-match credit.
Track distinct engine references by request key and full PodEntry. Capacity eviction and explicit removal release the departing engine's references and preserve entries owned by a live sibling. Repeated Add is idempotent. Mapping replacement, request-key eviction, per-key entry overflow and pod Clear clean up reference state.
Engine blocks that jointly form one canonical block (many:1) are constituents rather than independent replicas. Removing a constituent invalidates that cohort's entry; a surviving independent owner can still preserve it. Tier updates resolve complete mappings and insert entries under the same invalidation lock, including through metrics/tracing wrappers. Parent-hash lookup retains its terminal-key contract and speculative insertion remains mapping-free.
The sibling regression fixture is based on ptimizeroracle's review and reproducer in this PR. This is an independent implementation addressing the shared-ownership behavior described in #3574; no code or commits from #3609 were imported.
Scope: InMemoryIndex only. CostAware and Redis changes are excluded. Ownership metadata has additional memory cost, and Clear serializes ownership cleanup with writers. No serving throughput, latency or memory-overhead improvement is claimed.
Test plan:
Validation: make presubmit with LINT_NEW_ONLY=false (full lint, without the new-issues filter), make build, go mod tidy -diff, and the affected-package full race suite passed in the repository-pinned builder using its default Go1.27.3. Focused regressions also passed with -race -count=100 after rebasing. No toolchain override, repository dependency upgrade, or lint suppression is used. The unused PodCache.size method was removed after reproducing the CI lint failure; rollback reproduces the same diagnostic and reapplying the patch restores a clean lint result.
AI assistance was used to investigate, implement and test this change. The human submitter confirmed review of the current patch and remains responsible for its substance.
Which issue(s) this PR fixes:
Fixes #3503
Fixes #3574
Release note _(write NONE if no user-facing change)_:
Keep in-memory cache residency consistent with engine mappings without dropping shared prefix credit for live sibling blocks. Device-tier updates cannot restore unmapped residency and cover all canonical keys mapped to an engine block.Tracks per-entry engine ownership (owners and engineEntries) and many:1 block cohorts (constituents) inside InMemoryIndex so capacity eviction or explicit removal of an engine mapping drops only entries with no remaining live owner. Also adds an optional EngineKeyAdder interface (AddByEngineKeys) so Pool.handleDeviceTierUpdate resolves engine mappings and inserts confirmed tier entries under one m.mu hold, while CostAwareMemoryIndex and RedisIndex remain unchanged on the fallback path.
InMemoryIndex (https://github.com/llm-d/llm-d-router/blob/d8d06ad2e6a65ecbc3e9ed3f4b987bc426af3d58/pkg/kvcache/kvblock/in_memory.go#L82-L168) wires onEvict callbacks on both lruStore (forgetRequestOwners) and engineToRequestKeys (releaseEngine), tracking bidirectional ownership between (requestKey, PodEntry) and engineKey under m.mu (sync.RWMutex).promoteReadKeys (https://github.com/llm-d/llm-d-router/blob/d8d06ad2e6a65ecbc3e9ed3f4b987bc426af3d58/pkg/kvcache/kvblock/in_memory.go#L430-L471) takes m.mu.RLock(), promotes data, collects deduplicated engine keys via bounded pooled promotionBuffer (collectPromotionEngineKeys), and refreshes engineToRequestKeys in last-occurrence order on Lookup and WalkKeys.AddByEngineKeys (https://github.com/llm-d/llm-d-router/blob/d8d06ad2e6a65ecbc3e9ed3f4b987bc426af3d58/pkg/kvcache/kvblock/in_memory.go#L497-L551) and addLocked (https://github.com/llm-d/llm-d-router/blob/d8d06ad2e6a65ecbc3e9ed3f4b987bc426af3d58/pkg/kvcache/kvblock/in_memory.go#L553-L661) skip EmptyBlockHash interior sentinels, record all cohort peers in pending[requestKey], detect mapping replacement (!slices.Equal), skip residency insertion when a batch mapping is capacity-evicted mid-add, and prune owners on PodCache overflow.Evict (https://github.com/llm-d/llm-d-router/blob/d8d06ad2e6a65ecbc3e9ed3f4b987bc426af3d58/pkg/kvcache/kvblock/in_memory.go#L667-L725) calls removeDependentOwners so losing any many:1 constituent invalidates that cohort's ownership while independent siblings survive.EngineKeyAdder (https://github.com/llm-d/llm-d-router/blob/d8d06ad2e6a65ecbc3e9ed3f4b987bc426af3d58/pkg/kvcache/kvblock/index.go#L163-L189) is implemented by InMemoryIndex, instrumentedIndex, and tracedIndex, and consumed by Pool.handleDeviceTierUpdate (https://github.com/llm-d/llm-d-router/blob/d8d06ad2e6a65ecbc3e9ed3f4b987bc426af3d58/pkg/kvevents/pool.go#L775).[1001] -> [11, 12, 13, 14] and [1002] -> [11, 12, 23, 24] on pod1, recording both 1001 and 1002 in owners[11][pod1] and owners[12][pod1].1001 is capacity-evicted from engineToRequestKeys, releaseEngine(1001) removes 1001 from owners: 13 and 14 have empty owner sets and are deleted from data, while 11 and 12 retain 1002 and stay resident.Pool.handleDeviceTierUpdate receives a CPU tier event for [1002], AddByEngineKeys resolves 1002 and inserts the CPU PodEntry (plus all cohort peers for many:1 groups) while holding m.mu, preventing a concurrent capacity eviction from recreating unmapped residency.in_memory.go; not yet resolved.--kv-connector=mooncake, decode counts the KV it pulls from prefill as its own prompt-cache hits, so clients see cached_tokens โ prompt_tokens - 1 on every request, whether or not the prompt was cached (Fixes #3833).What type of PR is this?
/kind feature
What this PR does / why we need it:
Under --kv-connector=mooncake, decode counts the KV it pulls from prefill as its own prompt-cache hits, so clients see cached_tokens โ prompt_tokens - 1 on every request, whether or not the prompt was cached.
This reads usage.prompt_tokens_details.cached_tokens from the prefill response and uses it in the decode usage, the same way nixlv2 does, for JSON and SSE. Prefill and decode run concurrently, so if prefill hasn't responded when decode writes usage, decode's own count is kept rather than waiting. SGLang is unchanged.
New Mooncake specs cover non-streaming and streaming usage with prefill finishing first, prefill slower than decode, and a prefill response without usage; the first two fail without the Mooncake opt-in. The full pkg/sidecar/proxy suite hangs for me on main too, so I ran focused subsets (Mooncake, SGLang, NIXL, cached tokens). make presubmit not run (no builder container).
AI assistance (Claude) was used.
Which issue(s) this PR fixes:
Fixes #3833
Release note _(write NONE if no user-facing change)_:
The mooncake connector now reports the prefill worker's cached_tokens in decode usage.Under Mooncake concurrent P/D, decode counts KV blocks pulled from prefill as its own cache hits, inflating cached_tokens on every response. This change extracts usage.CachedTokens from the prefill response once it completes and passes CachedTokensFn into usage.NewResponseWriter via runConcurrentPDWithUsage so decode usage frames rewrite cached_tokens when prefill finishes in time and reports a measurement. Other runConcurrentPD callers (SGLang HTTP/gRPC) and Mooncake vLLM gRPC remain unchanged with rewriteCachedTokens set to false.
usage.Options keeps cachedTokensUsageRewriter on the rewrite path and resolves the count per JSON body or SSE usage frame.count + 1 in atomic.Int64 so concurrent record and get calls stay race-free and distinguish unset (false) from 0.decodeWriter (layered over deferredCommitWriter when streaming) when rewriteCachedTokens is true; handleMooncake passes streaming and opts in while runConcurrentPD passes false./v1/chat/completions to Mooncake; handleMooncake calls runConcurrentPDWithUsage(..., streaming, ..., true).cached_tokens: 7 and prefillCached.record(pw) stores 8.cached_tokens: 49; cachedTokensUsageRewriter calls prefillCached.get(), gets (7, true), and rewrites prompt_tokens_details.cached_tokens to 7 (or keeps 49 if prefill has not finished or omitted details).connector_pd_common.go awaiting @luoyuctl's response.What type of PR is this?
/kind feature
What this PR does / why we need it:
Item 1 of 3 for #1702 (group-aware prefix matching for hybrid models such as gpt-oss). On main, pool.go skips every store and removal of a sliding-window group as unsupported_cache_kind, although GroupCatalog already learns each group's kind and window size from the same events. The router therefore credits a gpt-oss pod with its full-attention prefix even when the sliding-window group no longer holds the window vLLM needs for a hit.
With kvEventsConfig.indexSlidingWindowGroups: true:
sliding_window group whose window size is known go to a second in-memory index, Pool.WindowIndex(), with the group on each entry; removals of that group evict from it, and clearing a pod clears it;unknown_sliding_window.Nothing reads the window index in this PR, so scores don't change, and the cache-format catalog still learns only from prefix-index stores. The option is off by default; with it off, nothing changes.
I kept the window entries out of the prefix index because the matcher doesn't look at groups: there they would count as hits wherever the full-attention entry is gone. Item 2 can fold them into one index if you'd rather have that.
Next: item 2 matches per group (the full-attention prefix, cut back to the last point where each sliding-window group still holds a full window); I'll post that rule on #1702 before the PR. Item 3 makes speculative entries group-aware, which is #1702 as written.
Limits: the window index is in memory even when the prefix index uses Redis. kvEventsConfig.windowIndexConfig sizes it and defaults to the prefix index's inMemoryConfig. sliding_window_mla groups stay skipped. Several open PRs touch pool.go; this change stays in processEventBatch, clearPod and one new helper.
Tests (CPU only; I haven't run a hybrid model):
unknown_sliding_windowAllBlocksCleared later in the batch applies after the storewindowIndexConfig sizes the window index, and the producer defaults it to the prefix index's inMemoryConfigAllBlocksCleared clears the pod's window entriesgo test -race on pkg/kvevents and the precise-prefix producer: ok; go build ./cmd/epp: ok. go1.27.3 darwin/arm64.golangci-lint v2.14.0 with the repo config on pkg/kvevents: 0 issues. make presubmit: not run locally.Which issue(s) this PR fixes:
Part of #1702
Release note _(write NONE if no user-facing change)_:
precise-prefix-cache-producer: optional `kvEventsConfig.indexSlidingWindowGroups` indexes the sliding-window KV cache groups of hybrid models (for example gpt-oss) into a separate window index that scoring does not read; `kvEventsConfig.windowIndexConfig` sizes it.emitSSEChunk built each SSE event by cloning the chunk's non-streaming response, so events had object: "chat.completion", the id and created of each chunk's own decode request (changing... (Fixes #3858)What type of PR is this?
/kind bug
What this PR does / why we need it:
In streaming chunked decode, emitSSEChunk built each SSE event by cloning the chunk's non-streaming response, so events had object: "chat.completion", the id and created of each chunk's own decode request (changing mid-stream), and role on every delta. runChunkedDecodeFromMap also always sent {"choices":[],"usage":...} before [DONE], without id/object/created/model, even when the request did not set stream_options.include_usage. Client code that reads chunk.choices[0] on every event fails on that event.
Now:
chat.completion.chunk carrying the first chunk's id, created and model;role is on the first delta only;include_usage is read before stream_options is dropped from the chunk requests, and the cumulative usage event is sent only when it is set, with the same envelope.This matches what vLLM streams for the same request without chunking.
Before (--decode-chunk-size 5, no include_usage):
data: {"choices":[{"delta":{"content":"hello ","role":"assistant"},"finish_reason":null,"index":0}],"created":1793598881,"id":"chatcmpl-001","model":"fake-model","object":"chat.completion"}
data: {"choices":[{"delta":{"content":"world","role":"assistant"},"finish_reason":"stop","index":0}],"created":1793598881,"id":"chatcmpl-002","model":"fake-model","object":"chat.completion"}
data: {"choices":[],"usage":{"completion_tokens":10,"prompt_tokens":10,"total_tokens":20}}
data: [DONE]
After, same request:
data: {"choices":[{"delta":{"content":"hello ","role":"assistant"},"finish_reason":null,"index":0}],"created":1793747580,"id":"chatcmpl-001","model":"fake-model","object":"chat.completion.chunk"}
data: {"choices":[{"delta":{"content":"world"},"finish_reason":"stop","index":0}],"created":1793747580,"id":"chatcmpl-001","model":"fake-model","object":"chat.completion.chunk"}
data: [DONE]
After, with "stream_options":{"include_usage":true}:
data: {"choices":[{"delta":{"content":"hello ","role":"assistant"},"finish_reason":null,"index":0}],"created":1793747589,"id":"chatcmpl-003","model":"fake-model","object":"chat.completion.chunk"}
data: {"choices":[{"delta":{"content":"world"},"finish_reason":"stop","index":0}],"created":1793747589,"id":"chatcmpl-003","model":"fake-model","object":"chat.completion.chunk"}
data: {"choices":[],"created":1793747589,"id":"chatcmpl-003","model":"fake-model","object":"chat.completion.chunk","usage":{"completion_tokens":10,"prompt_tokens":10,"total_tokens":20}}
data: [DONE]
Two existing tests expected the usage event on a request without include_usage ("emits one SSE event per chunk" in decode_test.go and TestChunkedDecodeToolCallingMetrics in sidecar_metrics_test.go); they now expect it to be absent. docs/architecture.md describes the new behavior.
#3565 also changes emitSSEChunk (reasoning and logprobs in the delta); whichever merges second will need a small rebase.
Which issue(s) this PR fixes:
Fixes #3858
Test plan:
decode_test.go cover the shared id/created/model, object: chat.completion.chunk and role on the first event only, and the usage event with its envelope when include_usage is set.go test -race -timeout 30m -skip TestServeMetrics_ListenError ./pkg/sidecar/... passes. TestServeMetrics_ListenError blocks on macOS, where listening on :port succeeds while 127.0.0.1:port is held; it is unrelated to this change.gofmt, go vet ./pkg/sidecar/...Release note:
Streamed chunked decode in the P/D sidecar now sends `chat.completion.chunk` events that share one `id`, and sends the usage event only when `stream_options.include_usage` is set.session-state-producer keyed its state on the agent-identity value alone. As a result, two tenants that send the same session ID share one SessionState.What type of PR is this?
/kind feature
What this PR does / why we need it:session-state-producer keyed its state on the agent-identity value alone. As a result, two tenants that send the same session ID share one SessionState. With composeFairnessIDs, t1/s and t2/s get separate flows but one turn-priority depth.
This PR changes the key to SessionKey{TenantID, SessionID}:
InferenceRequest.TenantID holds the raw x-llm-d-inference-fairness-id header. The Director sets it before RequestHeader and does not change it later. FairnessID is not usable for this, because the Director rewrites it after RequestHeader.RequestHeader, PreRequest, and ResponseBody.TenantID: "". Single-tenant behavior does not change.Which issue(s) this PR fixes:
Refs #4021
Related to #4232
Release note _(write NONE if no user-facing change)_:
`session-state-producer` keeps separate session state for each tenant fairness ID. Tenants that use the same session ID no longer share a `turn-priority` depth.Session state in session-state-producer was keyed on agent-identity alone, causing different tenants sharing a session ID to collide on turn depth and token totals. This change adds an immutable TenantID field on InferenceRequest populated from the raw fairness-ID header before RequestHeader plugins run, and keys SessionStateRegistry on SessionKey{TenantID, SessionID}. Single-tenant requests without a fairness-ID header resolve to TenantID "" and behave identically, while agent-lineage and thunder-agent remain unchanged.
TenantID string on InferenceRequest (WithAttributeScope shallow-copies *r, preserving it across all plugin extension points).TenantID from FlowFairnessIDKey before RequestHeader, and director.go#L308 reads TenantID when composing FairnessID.SessionKey{TenantID, SessionID}, used by SessionStateRegistry in registry.go#L61-L184 and built via sessionKey(request) in producer.go#L198-L207 across RequestHeader, PreRequest, and ResponseBody.t1 and tenant t2 both send x-claude-code-session-id: s alongside x-llm-d-inference-fairness-id: t1 and t2 with composeFairnessIDs: true.TenantID: "t1" (and later composes FairnessID: "t1/s") on the first request, and TenantID: "t2" (FairnessID: "t2/s") on the second.session-state-producer keys the two requests under SessionKey{TenantID: "t1", SessionID: "s"} and SessionKey{TenantID: "t2", SessionID: "s"}, so t1's 5 dispatched turns and token counts stay isolated from t2 when turn-priority scores their queued heads.PodMonitor only when MONITORING=true but delete it on every cleanup.Refs #2937, which makes this fix in the Nemotron and Qwen model guides. Eight more guides create the model-server PodMonitor only when MONITORING=true but delete it on every cleanup. On a cluster without the PodMonitor CRD, --ignore-not-found does not cover the unknown kind. The delete fails, and set -euo pipefail stops cleanup before the namespace goes.
Each cleanup step now has the same when: as its deploy step, and guide.py render updated the READMEs. omni-serving deploys monitoring only for MODEL_SERVER=vllmomni, so its cleanup takes that condition too. I left hyperconverged-cephfs alone: it has no MONITORING variable and always applies monitoring.
$ python -m pytest scripts/tests/test_guide.py -q # base 361e1b7, pyyaml 6, pytest 9
34 passed # base
58 passed # this branch
16 failed, 42 passed # guide.yaml files from 361e1b7, tests kept: MONITORING unset and false, all eight
$ python scripts/guide.py render guides/*/ guides/models/*/ guides/fast-model-actuation/fast-model-actuation-keda/ guides/batch-serving/asynchronous-processing/multitenant/ --check
# exit 0
$ python -m pytest scripts/tests/ docker/scripts/cpu/ .github/scripts/nightly-e2e-verification/ docs/operations/validation/smoke-test/tests/ .github/scripts/e2e/async-multitenant/ -q
446 passed, 19 skipped
# pre-commit on the 17 changed files: markdownlint and yamllint report the same 31 findings at base and on this branch
# not run: a cleanup on a live cluster without the PodMonitor CRD
The patch also applies on the head of #2937, so the two can merge in either order. @liu-cong, three of these guides list you in OWNERS. Do you want the eight split by guide owner?
Guards monitoring resource deletion in eight guide.yaml cleanup sections with the same when: conditions used in deploy.monitoring (MONITORING: ["true"], plus MODEL_SERVER: [vllmomni] for omni-serving). Previously, cleanup deleted the PodMonitor kustomize component unconditionally, causing kubectl delete to fail under set -euo pipefail on clusters lacking the PodMonitor CRD before namespace deletion ran. Generated README.md cleanup sections and deploy.monitoring logic stay aligned via guide.py render, while hyperconverged-cephfs (which always applies monitoring) is unchanged.
when: {MONITORING: ["true"]} (and MODEL_SERVER: [vllmomni] in guides/omni-serving/guide.yaml:241) to the kubectl delete ... monitoring* step in each guide's cleanup.rest list (scripts/guide.py _step_included at scripts/guide.py:1509 drops unmatched steps in emit and annotates # only when ...: in README.md).test_monitoring_cleanup_matches_deployment (scripts/tests/test_guide.py:440) emits deploy.monitoring and cleanup for MONITORING in {None, "false", "true"} across flow-control and all eight updated guides, asserting monitoring/monitoring-pd/${MONITORING_COMPONENT} appears iff MONITORING == "true" while helm uninstall always remains.guides/omni-serving/guide.yaml (MODEL_SERVER defaults to vllmomni, MONITORING defaults to "false").guide.py emit guides/omni-serving cleanup with default MONITORING="false" skips guides/omni-serving/guide.yaml:241 in _step_included, emitting helm uninstall without kubectl delete ... monitoring.--var MONITORING=true includes the kubectl delete ... monitoring --ignore-not-found=true step in both the emitted script and the # only when MONITORING=true and MODEL_SERVER=vllmomni: block in guides/omni-serving/README.md:578./test-nightly multimodal-serving-aggregation-gke-acc-gpu-vllm-x/test-nightly multimodal-serving-aggregation-gke-acc-tpu-vllm-x/test-nightly multimodal-serving-e-disaggregation-gke-acc-gpu-vllm-x/test-nightly optimized-baseline-*/test-nightly pd-disaggregation-*/test-nightly precise-prefix-cache-routing-*/test-nightly predicted-latency-routing-*/test-nightly tiered-prefix-cache-*closes #2988
adds --metrics-port=9095 and an sc-metrics port to every routing-proxy in the guides, same port and name the amd wide-ep overlay already uses. the decode PodMonitor (and the glm-5-2, deepseek-v4 and wide-ep monitoring overlays) now scrape it too, so llm_d_disagg_sidecar_* finally shows up in prometheus. decode pods without a sidecar don't have the port so they're just skipped.
the pinned sidecar is v1.0.0 and --metrics-port has been there since v0.10.0, so no image change is needed. on GKE, managed prometheus won't pick up this port by itself, that needs a GMP PodMonitoring and can be a follow-up.
Enables the routing sidecar's Prometheus /metrics endpoint on port 9095 (--metrics-port=9095 and named containerPort sc-metrics) across all prefill/decode guide overlays and recipe bases, and wires decode PodMonitors and raw Prometheus scrape configs to collect llm_d_disagg_sidecar_* metrics. Also adds a yq-based CI dry-run gate and unit test script to prevent future guide overlays from omitting sidecar metrics, while leaving prefill/encode model server scraping and GKE Managed Prometheus PodMonitoring unchanged.
--metrics-port=9095 and named port sc-metrics (9095/TCP) to decode-podmonitor.yaml counterparts in single-host P/D bases (vllm, sglang, e-pd), model guides (deepseek-v4, glm-5-2, kimi-k3-1, nemotron-3-ultra), p2p-kv-cache-sharing, multimodal-serving, pd-disaggregation, and wide-ep; patch overlays (nemotron-3-ultra, e-p-d, cks-mooncake, mthreads, amd-ci-1p1d-tp8) inherit sc-metrics from their bases.- port: sc-metrics to decode-podmonitor.yaml and the deepseek-v4, glm-5-2, and wide-ep monitoring overlays, plus a routing-sidecar job in each guide's prometheus-scrape-configs.yaml filtering on __meta_kubernetes_pod_container_port_name: sc-metrics.check-routing-sidecar-metrics.sh and test-check-routing-sidecar-metrics.sh, wired into ci-kustomize-dry-run.yaml and run against every rendered guide manifest at lines 266-273.ci-kustomize-dry-run.yaml first runs test-check-routing-sidecar-metrics.sh after installing mikefarah/yq v4+, verifying 8 pass/fail manifest cases.guides/pd-disaggregation/modelserver/gpu/vllm/cks-mooncake), kustomize build merges the base sc-metrics port (9095) with the overlay's --metrics-port=9095 arg into /tmp/rendered.yaml.check-routing-sidecar-metrics.sh /tmp/rendered.yaml inspects every routing-proxy or disagg-sidecar container and passes only when both --metrics-port and port sc-metrics are present./test-nightly multimodal-serving-e-disaggregation-gke-acc-gpu-vllm-x/test-nightly pd-disaggregation-amd-ci-acc-rocm-vllm-moriio/test-nightly pd-disaggregation-cks-acc-gpu-vllm-x/test-nightly pd-disaggregation-gke-acc-gpu-sglang-x/test-nightly pd-disaggregation-gke-acc-gpu-vllm-x/test-nightly pd-disaggregation-ibm-acc-gpu-vllm-x/test-nightly wide-ep-*When monitoring is enabled, alternative Prometheus/GMP values steps can both be emitted, while model-monitor deployment and cleanup still request Prometheus Operator resources on a GMP-only cluster. Add an explicit MONITORING_BACKEND selector and gate those executable steps by the selected backend, preserving OSS monitoring on GKE.
Applies to multimodal-serving, omni-serving, Nemotron-3-Ultra, GLM-5.2, Qwen3.5-397B, P2P KV-cache sharing and Hyperconverged CephFS. Ceph's documented optional monitoring now has a real MONITORING toggle; both apply and cleanup honor it. The existing authenticated EPP GMP chart values are reused and README commands remain generated.
Related to #2849 and #2989. #2989 supplies values alternatives and documentation; this PR addresses executable selection and resource gating, with tests. The broader issue remains open.
Validation:
Collection limits: per-rank GLM, TPU and vLLM-Omni model metrics still require verified GMP PodMonitoring coverage; SGLang diffusion/Rust paths may expose no model metrics. P2P's change is optional EPP GMP selection for an existing compatible deployment, not a validated GKE deployment overlay. Existing MONITORING=false OSS cleanup issues outside the new Ceph toggle remain tracked separately in #2972.
Adds an explicit MONITORING_BACKEND selector (prometheus vs gmp) across 7 well-lit guides and gates executable router values and model-server PodMonitor deployment/cleanup steps. This prevents applying non-existent Prometheus Operator resources on GKE Managed Prometheus clusters while preserving full OSS Prometheus and OpenShift observability.
MONITORING_BACKEND: {default: prometheus, values: [prometheus, gmp]} to env in guide.yaml across 7 guides.deploy.monitoring_values into standard (OSS) and gke (monitoring-gke.values.yaml with skip_in: [ci]).PodMonitor deployment and cleanup with MONITORING_BACKEND: [prometheus], preventing missing-CRD errors on GMP.scripts/tests/test_gke_monitoring.py and scripts/tests/test_gke_model_guide_monitoring.py covering all backend, accelerator, provider, and cleanup permutations.MONITORING=true and MONITORING_BACKEND=gmp.-f .../router/features/monitoring-gke.values.yaml (configuring authenticated EPP PodMonitoring).kubectl apply of Prometheus Operator PodMonitor CRDs is skipped, avoiding no matches for kind 'PodMonitor' errors on GMP.kubectl delete commands, ensuring clean zero-error teardown.Fixes two critical blockers preventing bidirectional KV cache transfer from being production-ready:
timeout errors in streaming decode responses.
line-buffers SSE chunks for complete event extraction, buffers full body only for non-streaming JSON. Data passes through unchanged (read-only); preserves http.Flusher interface for
real-time streaming.
session hijacking.
What Changed
New Files
Modified Files
Testing
All 148 proxy tests pass, including 7 new bidirectional KV integration tests:
Deployment Impact
Single-tenant (one client per cluster): โ Safe to enable immediately
Multi-tenant (SaaS, shared clusters): โ ๏ธ DO NOT enable until EPP security fix deployed
Flags
--enable-bidirectional-kv-xfer=true # Enable feature (default: false)
--bidirectional-session-header=x-session-token # Header name for session token
--bidirectional-cache-size=4096 # Max sessions in LRU cache
--bidirectional-cache-ttl=480s # Cache TTL (8 minutes, matches vLLM default)
--bidirectional-recompute-threshold=64 # Min remote tokens to trigger DโP pull (0 = always pull)
What type of PR is this?
What this PR does / why we need it:
Which issue(s) this PR fixes:
Fixes #
Release note _(write NONE if no user-facing change)_:
NONEAdds bidirectional KV cache transfer to the P/D sidecar for NIXLv2 disaggregated serving, enabling follow-up prefill requests to reuse GPU KV blocks retained by the decode engine from the previous turn instead of recomputing prompt tokens. The sidecar captures decode responses (streaming SSE or non-streaming JSON) via httpsnoop without buffering, indexes the decode-held kv_transfer_params by a SHA-256 digest of request scope and message history in an expirable LRU cache, and replays them on the next turn when routed to the same decode pod via EPP session affinity. Standard non-disaggregated routing, non-NIXL connectors, and requests with reasoning or prompt truncation remain unchanged.
pkg/sidecar/proxy/bidirectional_kv_capture.go): newDecodeCapture wraps http.ResponseWriter via httpsnoop.Wrap, parsing SSE data: frames line-by-line while streaming chunks to the client immediately with http.Flusher preserved. Non-streaming responses are buffered up to 16MB. Responses with reasoning content, prompt truncation, multiple choices, or decode errors are marked unusable and never cached.pkg/sidecar/proxy/bidirectional_kv.go): Replay is guarded by both pod routing and content history. A request must carry an EPP x-session-token naming the local pod (<pod>-rank-<n>). Cache keys are SHA-256 digests combining prompt-shaping parameters (model, tools, cache_salt, etc.) and the exact canonical message history including the assistant reply. Prefill recomputes normally if history differs or tools change.atomic.Bool.CompareAndSwap) to prevent multiple requests from referencing decode blocks freed after the first read, expiring after --bidirectional-cache-ttl (default 450s, bounded below vLLM's 480s decoder_kv_blocks_ttl). Prefill retries drop replayed parameters to fall back cleanly to fresh prefill.pkg/sidecar/proxy/connector_nixlv2.go): Replayed NIXLv2 decode parameters (remote_engine_id, remote_block_ids, remote_host, remote_port) compose alongside the OffloadingConnector P2P pull source (remote_kv_source), allowing vLLM's MultiConnector to select the highest-priority source.POST /v1/chat/completions). The prefill leg runs cold with do_remote_prefill: false. As the decode engine streams SSE chunks (data: {"choices": [{"delta": {"content": "Hi"}}]}...), newDecodeCapture observes the tokens and the trailing kv_transfer_params. Upon successful response delivery, reuse.store() records the NIXL block parameters in kvReuseCache keyed by sha256(scope + "\n" + user_msg + "\n" + assistant_msg). EPP stamps x-session-token: base64("default/decode-0-rank-0").x-session-token and history [user, assistant, new_user]. sessionTargetsThisPod validates the token matches POD_NAME=decode-0. lookupKeys() computes candidate prefix hashes (longest history first) and finds the cached Turn 1 entry. take() claims the entry via atomic CAS and removes it from the LRU.handleNIXLV2 injects remote_engine_id: decode-engine, remote_block_ids: [[1, 2, 3]], and remote_host/port into prefillRequest.kv_transfer_params. The prefill engine reads the GPU blocks held by decode-0 via NIXLv2 RDMA/TCP instead of computing them from scratch.session-identity also publishes the same opaque tag as the plain-string session-tag attribute.What type of PR is this?
/kind feature
What this PR does / why we need it:
Adds two opt-in Alpha plugins with separate pipeline responsibilities:
session-identity is a RequestHeaderProcessor. It consumes the raw agent-identity, derives a deployment-scoped HMAC identity, and publishes typed SessionIdentity before flow-control admission.session-manager is a DataProducer. It consumes SessionIdentity after admission, mints a unique per-request stamp, and publishes attrsession.SessionCacheRequest for #2716โs session-prefix-cache-producer.session-identity also publishes the same opaque tag as the plain-string session-tag attribute. Typed consumers such as fairness policies and session-manager should use SessionIdentity; the string projection supports existing generic consumers such as session affinityโs SessionIDConfig.
This PR explicitly models RequestHeader processors as a pre-flow-control layer in the data graph. This permits a fairness policy to declare SessionIdentity as a dependency without triggering an invalid plugin-layer ordering error.
The SessionCacheRequest contract in attribute/session/data_types.go is copied exactly from #2716 at dfc1815c, allowing either PR to merge first without a contract conflict. Until #2716 merges, main has no plugin consuming this request.
KV-event subscription, residency indexing, continuation inference, routing policy, and observability are intentionally excluded (for now). #2716 owns KV-event subscription and residency indexing.
Related: #3221.
Validation:
go build ./...go vet ./...golangci-lint run --config=./.golangci.ymlgofmt -l .session-identity, session-manager, the data graph, request-control interfaces, runner, Director, and session affinityattribute/session/data_types.goWhich issue(s) this PR fixes:
Related to #1979, #2794, and #3221.
Release note:
Add opt-in Alpha plugins for pre-flow scoped session identity and post-flow session cache requests.What type of PR is this?
/kind bug
What this PR does / why we need it:
Honor engine retrieval-unit boundaries in precise prefix KV matching. When an engine reports a multi-canonical block (for example one 64-token block at canonical size 16), Index.Add stamps RetrievalSpan on the mapped request keys, and MatchBlockKeys only credits BlocksByTier / MatchedBlocks / WeightedScore once the full span matches. This applies to every tier, including GPU, when the engine block is larger than the canonical block size. Span-1 blocks keep the previous scoring path.
Which issue(s) this PR fixes:
Fixes #2889
Release note _(write NONE if no user-facing change)_:
Precise prefix matching now scores an engine retrieval unit only when the full span is present. This applies to every tier, including GPU, when the engine block is larger than the canonical block size.
PodEntry.RetrievalSpan from the engineโrequest key mapping on Index.Add (in-memory, Redis, cost-aware).go test ./pkg/kvcache/ ./pkg/kvcache/kvblock/ ./pkg/kvevents/TestMatchBlockKeysRetrievalSpanCPUOnly (expected CPU hits 0,0,0,4)TestMatchBlockKeysRetrievalSpanGPURetainedWhenCPUPartialTestCPUChunkSingleHashRetrievalBoundary (pool write path stamps RetrievalSpan=4)Fixes #2889 by stamping RetrievalSpan on indexed pod entries during Index.Add and updating MatchBlockKeys so multi-canonical retrieval units only credit MatchedBlocks, WeightedScore, and BlocksByTier once the full span matches. Requests whose keys are all span-1 stay on the existing endKeyIndependent fast path, while the first multi-span entry switches accumulation to creditKey. Pool.handleDeviceTierUpdate expands engine keys via Index.GetRequestKeys so tokenless offload events also preserve retrieval spans across 1:many mappings.
PodEntry.RetrievalSpan is ignored by SameIdentity and populated from requestKeyRetrievalSpans on 1:many Index.Add calls across InMemoryIndex, CostAwareMemoryIndex, and RedisIndex (stored in Redis hash field values while keeping identity JSON in the hash field key).unitTrack tracks per-tier retrieval-unit progress independently of slot.tiers (which stays contiguous-only for BlocksByTier), while deferredKey holds uncredited weights tagged with covering unit ordinals until a covering unit finishes (creditUnit) or all covers abort (discardUnit).Pool.handleDeviceTierUpdate expands each engine key via Index.GetRequestKeys and re-adds with both engine and request keys.[10, 20, 30, 40] (canonical size 16); Index.Add stamps RetrievalSpan: 4 on each key.MatchBlockKeys for [10, 20] sets sawMulti = true at key 10, defers weights for 10 and 20 in uncredited covered by the CPU unitTrack, and returns MatchedBlocks: 0, WeightedScore: 0.MatchBlockKeys for [10, 20, 30, 40] reaches pending == 4 == unitSpan at key 40, flushes the 3 deferred keys via creditUnit, credits key 40, and returns MatchedBlocks: 4, ConfirmedBlocks: 4, BlocksByTier: {"cpu": 4}.What type of PR is this?
/kind feature
What this PR does / why we need it:
token-load-scorer treats every token the same, so a pod working on 3000 image tokens + 3000 text tokens looks as loaded as a pod with 6000 text tokens. image tokens cost more since the vision encoder runs first, so pods with multimodal traffic look less busy than they are. kaushikmitr's benchmarks in llm-d#2081 showed the same thing.
the tokenized request already has what's needed. TokenCount() includes the placeholder tokens and each MultiModalFeature has its Length, so i added a NonTextTokens count next to Tokens in the in-flight load. the producer adds and releases it the same way as the total, and the prefix cache discount uses the feature Offset so a cached image isn't counted again.
the scorer gets a nonTextTokenWeight to count those tokens heavier. default is 1.0 so nothing changes until someone sets it. Tokens is still the total, so the other plugins reading InFlightLoad aren't affected.
added tests for the offset math, add/release, p/d roles, cross-replica and the scorer weight. existing tests pass unchanged, race clean.
Which issue(s) this PR fixes:
Fixes #2220
token-load-scorer has a new `nonTextTokenWeight` option to count image, audio and video tokens as heavier than text. default 1.0 keeps current behavior.data_types.go:61, producer.go; not yet resolved.PrometheusRule for the precise prefix-cache pipeline embedded in the EPP: the KV-block index, the KV-events stream that feeds it, and token-producer tokenization.Adds a default PrometheusRule for the precise prefix-cache pipeline embedded in the EPP: the KV-block index, the KV-events stream that feeds it, and token-producer tokenization. The file sits next to epp-alerting-rules.yaml, and docs/operations/observability/alerting.md gets a new section for it.
Closes llm-d/llm-d-kv-cache#664 (moved here from llm-d/llm-d-kv-cache#676 and llm-d/llm-d-router#2330, following llm-d/llm-d#1983). Part of llm-d/llm-d#1983.
All alerts are severity: warning and are evaluated per EPP replica, using the namespace/pod labels a ServiceMonitor or PodMonitor adds. Each replica keeps its own index and KV-events subscribers, so one broken replica alerts even while the others are healthy.
kv-cache.index
KVCacheIndexMetricsDisabled: the EPP is routing with the precise producer but counting no index lookups, meaning enableMetrics is off.KVCachePrefixHitRateLow: predicted prefix hit rate is below 10% for 30m, with a traffic floor.KVCacheIndexHighLookupLatency: P99 index lookup latency is above 50ms.kv-cache.events
KVCacheEventsNotReceived: the EPP is routing but receiving no KV events, including when the stream never connected.KVCacheEventsStalled: one model pod's events have stopped while the same EPP still receives events from other pods.KVCacheEventsSubscriberReconnecting / KVCacheEventsZMQErrors: a pod's event stream keeps failing, per pod and per ZMQ operation (including snapshot).KVCacheEventsPoolBacklog: more than 1000 KV-event messages have been queued for 15m.KVCacheTokenizationSlow: more than 5% of token-producer calls take over 100ms.llm_d_epp_kv_cache_*. The kvcache_* names from the issue are no longer emitted.enableMetrics only decides whether the six index_* metrics count, so absent() can't detect it being off. Traffic checks therefore use llm_d_epp_prefix_prompt_tokens_count, which the producer always records.speculativeIndexing (the precise guide's default), the EPP adds each routed prompt to the index itself, through the same counted path as real events, and those entries expire after a 2s TTL. So:lookup_hits_total / lookup_requests_total divides matched blocks by lookup calls, so it isn't a 0โ1 ratio. The hit-rate alert uses prefix_predicted_cached_tokens / prefix_prompt_tokens instead.plugin_duration_seconds tops out at a 100ms bucket, so the tokenization alert uses the share of calls over 100ms rather than P99.router-metrics.md, which said every KV-cache metric depends on enableMetrics.enableMetrics.promtool check rules and promtool test rules with seven test groups:yamllint and markdownlint (no new findings); scripts/guide.py render --check for the precise guide.helpers/preflight/preflight.py, a read-only check you run before deploying a guide (Part of #2429).Update 25.10: rebased onto the wide-ep layout from #2706 (overlays under modelserver/gpu/vllm/, dgx-cloud-gb200 gone, LWS v0.11.1).
Part of #2429.
Adds helpers/preflight/preflight.py, a read-only check you run before deploying a guide. It renders the model-server overlay with kubectl kustomize, works out what the pods will request, reads the cluster with kubectl get, and prints PASS / WARN / FAIL per prerequisite with a link to the doc that explains the fix. It never changes the cluster.
python3 helpers/preflight/preflight.py guides/wide-ep \
--overlay modelserver/gpu/vllm/gke
What it checks for wide-ep on NVIDIA GPU (modelserver/gpu/vllm/{gke,coreweave,base}):
rdma/ib on CoreWeave;recipes/router/base.values.yaml).Of the four failures in the issue, three are caught before deploy: missing RDMA setup, the R580 driver, and the router not fitting. Decode OOM depends on runtime settings and isn't checked.
How requirements are found. Most of them are derived from the rendered manifests, so they follow the guide when it changes. guides/wide-ep/preflight.yaml holds only what can't be derived (LWS minimum, driver rule, router size, CRDs the Helm chart creates, doc links), under requirements.cluster.
Changes from what I described on 13.09:
scripts/guide.py, and PyYAML is already its dependency.preflight.yaml instead of a requirements: block in guide.yaml: scripts/guide.py rejects unknown top-level keys. Its keys sit under requirements.cluster, the container @raravind007 proposes in #2636 next to requirements.modelServer, so moving them into guide.yaml is a copy once that key is allowed. Should this PR allow it, or wait for #2636?Network objects check: the GKE overlay uses DRANET now. Claim templates aren't checked either, because the overlay creates gke-rdma-template itself. The script checks the DeviceClasses and ResourceSlices instead.guides/env.sh, which pins nothing (latest).Question for @BenjaminBraunDev: the GKE README says R580 crashes DeepEP high-throughput kernels. That was written before prefill and decode moved to deepep_v2 (#2339, #2602). Does it still reproduce? Until then the driver check is a WARN, not a FAIL.
Not covered: free capacity (running pods aren't subtracted), RDMA on overlays whose manifests don't request an RDMA resource, pod-to-pod RDMA connectivity (the in-pod preflight in llm-d-pd-utils covers runtime checks). AMD overlays run, but the RDMA, driver and router-node checks only know NVIDIA resources; XPU (no DisaggregatedSet) exits with code 2.
Testing: 111 pytest tests over the committed renders of the three overlays and fake kubectl output, wired into ci-guides-check; a staleness test fails in CI when a render fixture no longer matches the manifests. About 1,650 of the ~3,600 added lines are those committed renders. Before the rebase onto #2706, ran the gke overlay against a local k3s cluster without GPUs: exit 1 with the expected FAILs, no crashes. The cluster-reading code hasn't changed since.
/test-nightly wide-ep-amd-ci-acc-rocm-vllm-moriio/test-nightly wide-ep-cks-acc-gpu-vllm-x/test-nightly wide-ep-gke-acc-gpu-vllm-xmean-residual-life (MRL) scorer and its paired sojourn-time-observer to the multicluster EPP hub (Fixes #3150).What type of PR is this?
/kind feature
What this PR does / why we need it:
Adds a two-term mean-residual-life (MRL) scorer and its paired sojourn-time-observer to the multicluster EPP hub.
Existing Distribution-axis scorers (multicluster-queue-scorer, active-request-scorer, latency-observation-scorer-hub) rank candidate endpoints without reasoning about how far along each in-flight request is toward completion and, therefore, without accounting for how much total residual work remains on each endpoint. Under tail-heavy decode times, a long-running request is more likely to be in the tail of the decode-time distribution and run even longer. Routing that doesn't account for this inflates p99 sojourn time.
This PR proposes an experimental scorer and its paired observer that aim to fix this issue under heavy-tailed service time distributions (typical for reasoning models) and bursty arrival of the requests.
Evidence for the scorer performance is provided in the tracking issue.
Which issue(s) this PR fixes:
Fixes #3150
Release note _(write NONE if no user-facing change)_:
Need to be surfaced in the documentation as an experimental scorerfailOpen: false, flow control can release a request that no endpoint can fit. For example, a 320-token request reaches endpoints loaded at 384/640 and 640/640 tokens and gets a 503 (Fixes #3154).What type of PR is this?
/kind bug
What this PR does / why we need it:
With failOpen: false, flow control can release a request that no endpoint can fit. For example, a 320-token request reaches endpoints loaded at 384/640 and 640/640 tokens and gets a 503.
Check projected cost before release, so the request waits in its scheduling band until the required profiles have capacity. Cost preparation can repeat while queued without rerunning ordinary producer hooks or counting the request twice.
Preparation failures can retry during a later queue refresh after the previous call finishes. The admitted snapshot keeps its own failure record so a final producer retry cannot change the checked cost. At dispatch, a request-local handoff prevents new preparation calls and identifies any still running; other producers continue normally. The same ownership is shared by cold, warm and fallback snapshots.
The built-in profile filters determine required and optional P/D stages. When no profile filter is provided, dispatch requires available decode capacity whenever decode candidates exist, or prefill capacity for a prefill-only candidate set.
The gate covers built-in monolithic/P/D routing with canonical role selection. Custom profile handlers retain their existing path. It checks capacity without reserving it; band order and dispatch accounting from #2920 are preserved.
Optional admission-producer hooks separate cost preparation from ordinary side effects. Pending prefix lookups use an undiscounted bound. Ordinary producers still see all candidates, including KV donors. Prepared prefix snapshots preserve prediction caching and text/multimodal metrics.
The regression for the interaction with #3847 copies a queued admission snapshot and checks the next request's prefix matches. The serving endpoint matches all six expected blocks; the prefill endpoint matches only the prompt. Without the block size in the snapshot copy, the serving endpoint matches only two blocks. The regression passed in 50 consecutive runs with the fix.
On Windows/amd64 with Go 1.27.4, 1,067 top-level tests passed across 15 packages and nine live-service tests were skipped. Three tests failed on both this branch and unmodified 8f372a85: the DAG execution-order test and two handler metrics tests. Scoped go vet passed and the E2E test binary compiled. The race detector, full presubmit and KIND/HTTP suite were not run locally for this rebase.
Which issue(s) this PR fixes:
Fixes #3154
Release note _(write NONE if no user-facing change)_:
Flow control with failOpen: false in tokens or hybrid mode checks projected request cost before release for supported monolithic and P/D routes, including required prefill capacity.Prevents flow control with failOpen: false in tokens or hybrid mode from releasing queued requests that exceed every eligible endpoint's remaining capacity. Introduces side-effect-free queued preparation (AdmissionDataProducer and AdmissionCostProducer) and stage-aware dispatch filtering (Scheduler.FilterForAdmission), while keeping ordinary Produce/PreRequest accounting, custom profile handlers, and configurations with request-handling or scheduling-time tokenizer inputs unchanged.
queued_preparation.go)**: Runs tokenization and AdmissionDataProducer/AdmissionCostProducer plugins on isolated request/endpoint copies while queued (skipping via tokenInputProducedAtScheduling if another scheduling producer supplies a tokenizer input), tracking per-producer goroutine liveness in preparationOwnership and sealing preparation at dispatch.processor.go)**: Processor.requestFits evaluates cold (WithoutPrefix) and warm PreparedRequest snapshots against live endpoint metrics via readyRequest and composite.FilterForDispatch without blocking ranked-band progress.admission.go, disagg/admission.go)**: Scheduler.FilterForAdmission and disagg.Handler.FilterForAdmission check required decode/prefill stages and pass per-profile candidates to ScheduleWithAdmission, while approximateprefix, preciseprefixcache, inflightload, and tokenizer implement AdmissionDataProducer without mutating shared PluginState.failOpen: false).FlowController.EnqueueAndWaitPrepared enqueues the request and Processor.startPreparation computes cold and prefix-discounted token costs in queuedPreparation.Processor.requestFits sees neither endpoint can fit 320 tokens, leaves the item queued, and re-evaluates live InFlightLoad on each dispatch tick until an incumbent finishes and capacity opens.NixlPushConnector) to the sidecar./kind feature
Adds support for vLLM's NIXL push mode (NixlPushConnector) to the sidecar.
This PR:
--nixl-push-mode flag (needs --kv-connector=nixlv2)transfer_id so vLLM can pair them (vllm-project/vllm#59758), with a new one for each prefill retry--nixl-push-prefill-timeout, metrics, span attributes and docsAll with push parallel through the sidecar.
I use the numbers from vllm-project/router#187 as reference.
NIXL push mode was measurably worse. We merged a change on NIXL through which push mode is on par with pull.
<img width="2359" height="1787" alt="push-vs-pull" src="https://github.com/user-attachments/assets/e04e858a-a2b8-4af3-a7db-8d20121051fb" />
Median TTFT (ms)
| c | pull | push |
|---|---|---|
| 1 | 85 | 78 |
| 2 | 84 | 78 |
| 4 | 112 | 112 |
| 8 | 122 | 120 |
| 16 | 125 | 123 |
| 32 | 130 | 135 |
| 64 | 194 | 203 |
| 128 | 580 | 585 |
| 256 | 1947 | 1979 |
Part of llm-d/llm-d#2720
The P/D sidecar supports vLLM's NIXL push mode (`NixlPushConnector`) with the new `--nixl-push-mode` and `--nixl-push-prefill-timeout` flags.llm_d_epp_datalayer_poll_errors_total and logs at DEBUG, and the endpoint keeps its last metrics (Part of #3326).What type of PR is this?
/kind feature
What this PR does / why we need it:
A failed poll of a polling data source increments llm_d_epp_datalayer_poll_errors_total and logs at DEBUG, and the endpoint keeps its last metrics. No plugin can tell an endpoint whose polls keep failing from one whose polls succeed. For file-discovered endpoints, which have no readiness signal, this means a dead endpoint looks idle and healthy.
This PR makes the datalayer collector record, for each endpoint and each polling source, a PollStatus endpoint attribute: the number of consecutive failed polls, and when the first of them completed.
due() so the collector can tell a skipped tick from a poll that ran.Stop is not recorded. It is also no longer counted in llm_d_epp_datalayer_poll_errors_total.AttributeMap implementation may keep the pointer it is given.PollStatusDataKey(<source name>) for each polling source in dataLayer.sources, so a consumer that names a source the runtime does not poll fails at startup.There is no user-facing behavior change. The first consumer is endpoint-health-filter, proposed in #3328.
This change was developed with AI assistance (Claude).
Which issue(s) this PR fixes:
Part of #3326
Release note _(write NONE if no user-facing change)_:
NONE
Test plan:
dataLayer.sources, and rejects one whose source is missing from it, including a dispatcher that is only instantiated as a pluginStop is neither recorded nor counted as a poll error๐ค Generated with Claude Code
runner.go:892 (CI all green, 1 open thread awaiting author response to elevran) awaiting @tadler10's response.The vertexai parser claims only three gRPC service methods (PredictionService/{RawPredict,StreamRawPredict,ChatCompletions}). A Vertex AI dedicated endpoint forwards requests over HTTP instead, e.g. /v1/projects/P/locations/L/endpoints/E:predict, which matches none of them, so every such request is rejected with "no parser registered matching path suffix" before any parsing runs.
Claim the REST forms as well:
| API | REST path suffix |
|---|---|
| predict | :predict |
| rawPredict | :rawPredict |
| streamRawPredict | :streamRawPredict |
| chatCompletions | /chat/completions |
| invoke | /invoke/<container path> |
Each REST suffix needs its own claim -- ":streamRawPredict" is not matched by a ":rawPredict" claim, since its trailing characters are "mRawPredict". The path is read without its query string, so e.g. ?alt=sse does not defeat matching.
Vertex invoke appends the container's own path after /invoke/, so it has no fixed suffix. The registry gains a documented "/" segment-wildcard claim form; "invoke/" matches any path containing an /invoke/ segment. No existing claim ends in "/*", so this is backwards compatible.
A REST request carries the payload as raw JSON rather than a gRPC-framed Vertex proto. When it is OpenAI-compatible it is delegated to the OpenAI parser, choosing the route from the payload's shape (messages/prompt/input). Parsing is best effort: a dedicated endpoint may front any container -- a TensorFlow model served {"instances": [...]} is not OpenAI-shaped -- so a payload the OpenAI parser cannot read is forwarded unchanged and still scheduled, rather than rejecting traffic the direct path serves today.
A REST response is the model server's JSON or SSE as is, so ParseResponse now hands any non-gRPC response (by content-type, or by body when the header is absent) straight to the OpenAI parser instead of failing to unframe it.
Finally, the parser advertises AppProtocolHTTP alongside AppProtocolH2C. With h2c alone, EPP refuses to serve against a pool whose backends speak HTTP/1.1.
The existing gRPC methods are unchanged.
Verified on a GKE Inference Gateway in front of a Vertex AI dedicated endpoint: predict, rawPredict, streamRawPredict, chat completions and invoke return the same status and bytes through the gateway as when sent directly to the model server.
What type of PR is this?
What this PR does / why we need it:
Which issue(s) this PR fixes:
Fixes #
Release note _(write NONE if no user-facing change)_:
NONEparsers.go:120, vertexai.go:125 awaiting @tianjiaoliu-google's response.BlockStored event without tokens (OffloadingConnector without self_describing_kv_events), handleDeviceTierUpdate resolved each engine key with GetRequestKey, which returns only the last request key mapped to it (Fixes #3490).What type of PR is this?
/kind bug
What this PR does / why we need it:
For a CPU BlockStored event without tokens (OffloadingConnector without self_describing_kv_events), handleDeviceTierUpdate resolved each engine key with GetRequestKey, which returns only the last request key mapped to it. When the engine block is bigger than blockSizeTokens (for example 128 vs 64), only the last canonical key of each engine block got the CPU entry, and after GPU eviction the prefix match stopped at the first key.
This adds GetRequestKeys to kvblock.Index (in-memory, cost-aware and Redis backends, plus the traced and instrumented wrappers) and uses it in handleDeviceTierUpdate. GetRequestKey stays as it is for parent-hash chaining, where the last key is the right one.
I went with a read method rather than resolving inside the index, and I'm happy to switch if you prefer that. It adds a method to the exported Index interface, so an out-of-tree implementation would need it too.
Test plan:
blockSizeTokens: 64 marks all four canonical keys, and the prefix still matches on CPU after GPU eviction (fails on main).GetRequestKeys, and an error for an unknown engine key.Which issue(s) this PR fixes:
Fixes #3490
Release note _(write NONE if no user-facing change)_:
Precise prefix routing: with CPU offloading whose events carry no tokens and an engine block larger than blockSizeTokens, every canonical key of an offloaded block is marked as held on CPU, so a CPU-cached prefix keeps its routing credit after the GPU copy is evicted.index.go:146, pool.go:528 awaiting @EugeneVon's response.emitSSEChunk converts each chunk's non-streaming response into one SSE event, and the delta it built held the message's content and role only (Fixes #3564).What type of PR is this?
/kind bug
What this PR does / why we need it:
In streaming chunked decode, emitSSEChunk converts each chunk's non-streaming response into one SSE event, and the delta it built held the message's content and role only. A reasoning model's reasoning and the choice's logprobs were dropped from every event, so a client that renders reasoning deltas or asked for logprobs: true got neither. Non-streaming requests were not affected.
The delta is now built from the message, copying reasoning and reasoning_content when present, and the choice's logprobs pass through. This is the shape vLLM's own stream carries for the same chunk (DeltaMessage, ChatCompletionResponseStreamChoice at v0.31.0).
The same conversion also dropped tool_calls; #3595 bypasses chunked decode when a request may call a tool, so that case no longer reaches this code and this PR does not carry them.
Which issue(s) this PR fixes:
Fixes #3564
Test plan:
pkg/sidecar/proxy: a streamed chunk from a reasoning model carries its reasoning and its logprobs in the event (fails on main)go test -race with -ginkgo.focus on them; go build ./...; go vet; gofmt; golangci-lint v2.14.0. The full pkg/sidecar/proxy suite exceeds the ten-minute test timeout on my machine, so it was not run whole.Release note:
The sidecar's streamed chunked decode carries a chunk's reasoning and logprobs into its SSE event.In streaming chunked decode, emitSSEChunk previously synthesized SSE delta events containing only content and role, dropping reasoning and logprobs returned by the backend decoder. This PR updates emitSSEChunk and introduces deltaFromChoice in pkg/sidecar/proxy/decode.go to forward reasoning and reasoning_content inside delta and copy choice-level logprobs, matching vLLM streaming wire conventions. Non-streaming requests and unchunked streams remain unchanged.
BlockStored before the store event for its parent. The router currently drops the child when the parent engine-to-request mapping is missing.What type of PR is this?
What this PR does / why we need it:
vLLM can publish an offloading child BlockStored before the store event for
its parent. The router currently drops the child when the parent
engine-to-request mapping is missing. The parent event does not replay the
child later, so the router's prefix-cache index can be shorter than the cache
held by the serving pod. This can reduce prefix-cache-aware routing quality and
cause additional prefill or KV transfer work.
The trigger is deterministic and does not require asynchronous transfer
completion to reorder work. In vLLM's offloading scheduler,TransferJobStatus.keys is backed by a set. prepare_store() may produce
keys in prefix order (parent, child), but completing the job passes the set
to complete_store(). The CPU offloading manager then emits the stored keys in
set iteration order, and OffloadingEventsTracker preserves that order while
expanding them into BlockStored events. Python set iteration is unrelated to
the prefix tree order, so the child can be emitted first.
The tracker metadata itself remains correct in this case: each emittedBlockStored still carries the right block hashes, tokens, block size, and
parent hash. The lost dependency is the router index lookup: the child cannot
compute its request key until the parent engine hash has been mapped.
This change keeps unresolved child store events in a bounded pending queue and
replays them after the parent mapping becomes available. Pending entries are
scoped by pod, device tier, KV-cache group, data-parallel rank, and parent
engine hash. They are removed on cache reset or block removal and are bounded
by both a queue limit and a retention period.
The implementation also exposes the pending count, enqueue count, and replay
count so operators can determine whether this path is active and whether
events are being recovered.
This remains useful even if vLLM later preserves producer-side key order:
deployments can run against existing vLLM releases, and other event producers
are not required to provide a parent-before-child guarantee.
This is separate from the existing KV-event recovery fixes:
sub-canonical stores whose parent can never produce a request key. This PR
keeps that permanent-unresolvable case skipped and only queues parents that
may arrive later.
from a vLLM snapshot when a subscriber joins late, reconnects, or misses a
stream. This PR handles the live stream while the subscriber remains
connected and does not require a snapshot or replay endpoint.
The root cause was reproduced using vLLM's real CPUOffloadingManager andOffloadingEventsTracker, not only by injecting events into the router:
prepare_store() order: parent, child
TransferJobStatus.keys: set(parent, child)
manager/tracker event order: child, parent
child.parent == parent.block: True
token_ids correct: True True
Across 1,000 real SHA256 parent/child hash chains, the two-key set emitted the
child first 498 times (49.8%), so this is a practical ordering case rather than
a contrived sequence.
The router regression test delivers P2, P0, and P1 for the chainP0 -> P1 -> P2 and verifies that all three blocks are indexed after replay.
A temporary end-to-end reproduction fed the real child-first orderchild(ParentHash=P0), parent(ParentHash=0) to the router:
index.
P0 arrived; bothrequest keys resolved to the pod.
Committed test command:
go test ./pkg/kvevents -count=1
It passed with this change. The producer-side ordering issue will be tracked
separately in vLLM; this PR provides the consumer-side compatibility needed by
existing releases.
AI assistance was used to trace the event path, build the reproduction, and
draft the validation evidence. The human submitter will review the changed
lines and run the required validation before requesting merge.
Which issue(s) this PR fixes:
Fixes #
Release note _(write NONE if no user-facing change)_:
Improve prefix-cache-aware routing when vLLM offloading events arrive out of parent-child order.Bug: the image verification step interpolated a release tag directly into its run script. A tag containing shell syntax could execute commands on a runner after the GHCR login step.
Fix: pass the tag through the step environment and expand it as quoted shell data. Use the existing registry environment variable the same way.
Test: parsed the workflow YAML and checked the run block with bash -n.
Test: simulated a tag with shell metacharacters; it remained literal data.
Test: git diff --check passed.
Bug: the manual verification workflow looked for an SGLang image under the wrong name and omitted the RDMA tools image. It also interpolated its tag input into shell code after authenticating to GHCR.
Fix: check the four names produced by the release workflow, pass the tag as environment data, and reject values outside Docker's tag syntax.
Test: parsed the workflow YAML and checked the run block with bash -n. Test: simulated Docker inspection of all four images and rejected an
input containing shell metacharacters.
Test: git diff --check passed.
kv-sglang connector takes its bootstrap port only from SGLANG_BOOTSTRAP_PORT, read once per process on the first prefill request.What type of PR is this?
/kind feature
What this PR does / why we need it:
The coordinator's kv-sglang connector takes its bootstrap port only from SGLANG_BOOTSTRAP_PORT, read once per process on the first prefill request. The port can't be set in coordinator.yaml next to kv_connector, and a bad value only shows up as a log line after traffic starts.
This adds kv_connector_params, a map of settings for the KV connector, on the pipeline or on a step:
pipeline:
kv_connector: kv-sglang
kv_connector_params:
bootstrap_port: 9100
kv.Build(name, params) passes the map to the connector. kv-sglang accepts bootstrap_port and keeps it on the connector value instead of a package-level sync.Once. kv-nixl and kv-shared-storage accept no parameters.kv_connector_params.SGLANG_BOOTSTRAP_PORT still works as before (invalid value falls back to 8998 and is logged). It is now read when the pipeline is built, so the log appears at startup.kv_connector is unset or the same as the pipeline's. A step's own params replace the pipeline map as a whole.async-broker strips kv_connector_params along with the other injected keys.I kept the env var as a fallback so existing deployments don't break. Happy to drop it if the config key should be the only source.
Verified: a new table test in pkg/coordinator/pipeline/builder loads a YAML config, builds the pipeline and reads bootstrap_port from the prefill request. On main 16 of 19 cases fail (configured port arrives as 8998, invalid configs build); all pass with this change. go vet and go test -race ./pkg/coordinator/... ./cmd/coordinator/... pass (1011 tests). make lint and golangci-lint could not run here (no Docker, no binary).
Which issue(s) this PR fixes:
None
Release note _(write NONE if no user-facing change)_:
Coordinator: the kv-sglang bootstrap port can be set with `kv_connector_params.bootstrap_port` in the coordinator config, on the pipeline or on a step. SGLANG_BOOTSTRAP_PORT is still used when the key is absent. Invalid connector parameters fail pipeline construction at startup.Adds structured kv_connector_params configuration to the coordinator pipeline and step definitions, allowing the SGLang KV bootstrap port to be configured directly in coordinator.yaml (at pipeline or step scope) instead of relying solely on the process-wide SGLANG_BOOTSTRAP_PORT environment variable. SGLANG_BOOTSTRAP_PORT remains as a fallback when bootstrap_port is absent from kv_connector_params, and invalid connector parameters fail pipeline construction at startup while non-SGLang KV connectors reject non-empty parameter maps.
pkg/coordinator/config/config.go:88-90): Adds KVConnectorParams map[string]any (kv_connector_params) to PipelineConfig.pkg/coordinator/pipeline/builder/builder.go:77-99): mergePipelineDefaults injects pipeline.kv_connector_params into a step's params when the step sets no kv_connector_params of its own and its kv_connector is unset or matches pipeline.kv_connector. Step-level kv_connector_params replaces the pipeline map as a whole.pkg/coordinator/steps/params.go:32,71-81, pkg/coordinator/steps/asyncbroker/config.go:317): buildKVConnector extracts ParamKVConnectorParams via paramMap and passes it to kv.Build; parseAsyncBrokerConfig strips ParamKVConnectorParams before DisallowUnknownFields() JSON decoding.pkg/coordinator/connectors/kv/kv.go:68-89, pkg/coordinator/connectors/kv/sglang.go:61-106): kv.Build(name, params) rejects non-empty params for kv-nixl, kv-shared-storage, and kv-offloading, and calls newSGLangKV(params) for kv-sglang. sglangKV stores bootstrapPort immutably on the connector value (removing package-level sync.Once) and falls back to SGLANG_BOOTSTRAP_PORT (default 8998) when bootstrap_port is absent.pipeline.kv_connector: kv-sglang with pipeline.kv_connector_params: {bootstrap_port: 9100} (and optionally overrides kv_connector_params: {bootstrap_port: 9200} on prefill).builder.Build merges kv_connector_params into each step's params via mergePipelineDefaults and calls NewPrefillStep / NewDecodeStep, which invoke kv.Build("kv-sglang", kvParams).newSGLangKV validates keys and port range (1-65535), storing bootstrapPort on sglangKV.sglangKV.PreparePrefillKVParams emits bootstrap_port: 9200 (or 9100) and a random bootstrap_room, while PrepareDecodeKVParams forwards reqCtx.KVTransferParams verbatim.POST /generate with the coordinator pipeline and preserve its path and request body when preparing prefill.What type of PR is this?
/kind feature
What this PR does / why we need it:
Register native SGLang POST /generate with the coordinator pipeline and preserve its path and request body when preparing prefill. This keeps text input and SGLang bootstrap fields separate from vLLMโs token-only /inference/v1/generate format.
This layer covers request preparation and validation. Streaming prefill and native decode execution follow in #3776 and #3777.
Which issue(s) this PR fixes:
Ref https://github.com/llm-d/llm-d-router/pull/3511
Release note _(write NONE if no user-facing change)_:
The coordinator recognizes native SGLang /generate requests and prepares prefill requests using their native format.sglang.go:75, server.go; not yet resolved.What type of PR is this?
/kind feature
What this PR does / why we need it:
The default strict band selection policy serves priority bands from highest to lowest, so a band can starve for as long as any higher band has work. This adds cross-band-fairness-policy, a BandSelectionPolicy that bounds that starvation by giving every band a share of dispatch opportunities once the pool is saturated.
Below activationThreshold the policy writes nothing and dispatch stays strict: while capacity is available there is nothing to arbitrate. At or above it, weighted fair queuing engages. Each band carries a virtual time, bands are ranked by ascending virtual time, and a dispatch advances the serving band's virtual time by 1 / weight, so shares converge on the configured weights.
Weights come from one of two distributions:
linear (default): weights decrease by ordinal position, ignoring priority values.explicit: operator-supplied anchors, with unlisted priorities interpolated by priority value and clamped outside the anchor range. Interpolating over value rather than rank keeps the mapping a total function from priority to weight, so shares stay stable as priority bands are provisioned and garbage-collected.A band that is new, gated, or idle holds no claim and enters at the system virtual time, taking its turn without a burst of catch-up dispatches. Idleness is not observable from the Rank inputs, so it is inferred from the outcome callback: a band ranked ahead of the band that dispatched was offered the slot and passed, and is levelled with the band that was served.
Virtual times are retained but frozen while the policy is inactive, so saturation oscillating around the threshold resumes the round in progress rather than restarting it.
Only the interleaved schedule is accepted; the priority-first schedule and the proportional distribution are not implemented.
Which issue(s) this PR fixes:
Fixes #3520
Release note :
Add the `cross-band-fairness-policy` flow control plugin, a BandSelectionPolicy that shares dispatch opportunities across priority bands in proportion to configured weights once saturation reaches a configured threshold, bounding the starvation of lower-priority traffic. Opt in with `flowControl.bandSelectionPolicyPluginRef`; dispatch remains strict by default.Adds the cross-band-fairness-policy plugin implementing flowcontrol.BandSelectionPolicy and registers it at StabilityAlpha in cmd/epp/runner/runner.go:826. Below activationThreshold, Rank leaves the pre-filled strict priority order untouched; at or above threshold (with multiple active bands), it schedules bands by ascending virtual time using either ordinal linear weights (N - i) or explicit value-interpolated anchor weights. Default strict dispatch (strict-band-selection-policy) and the processor dispatch loop remain unchanged.
pkg/epp/framework/plugins/flowcontrol/bandselection/crossbandfairness/config.go:88-171: validates required activationThreshold in [0.0, 1.0), defaults schedule ("interleaved") and distribution ("linear"), and enforces positive ratios only under "explicit".pkg/epp/framework/plugins/flowcontrol/bandselection/crossbandfairness/cross_band_fairness.go:163-277: Rank computes per-band weights, reconciles p.bands and rebases virtual times in syncBands, sorts order by eligibility and ascending virtualTime, and records the offered ranking in p.ranked; RecordDispatch levels passed-over eligible bands to the served band's virtual time before advancing the served band by 1 / weight.pkg/epp/flowcontrol/controller/internal/processor_test.go:1405-1449: drives Processor.dispatchCycle for 60 cycles at Saturation = 0.9 with activationThreshold = 0.8 across priorities 100/50/10, asserting a 30:20:10 split.activationThreshold: 0.8 and active bands [100, 50, 10] under linear distribution (weights 3, 2, 1).virtualTime = 0.0, so priority 100 breaks the tie, dispatches, and advances to 0.333.Rank orders [50 (0.0), 10 (0.0), 100 (0.333)], serving 50 (-> 0.5), then 10 (-> 1.0), converging on a 3:2:1 share over 60 cycles in processor_test.go:1446-1448.Motivation: the embedded prefill calibration script treated any stream
that produced a chunk as a successful sample, even if EOF arrived before
a terminal finish_reason or data: [DONE]. Such a truncated run still
printed PEAK_PREFILL_THROUGHPUT, which calibrate.sh tells the user to
apply. The router is not modified automatically, so this affects the
validity of the calibration result only.
Approach: track whether a non-null finish_reason or [DONE] was seen, and
raise an explicit "stream ended before a finish_reason or [DONE]" error
otherwise. First-chunk TTFT is still used for streams that complete, and
the existing error-envelope and no-chunk handling is unchanged.
Validation: python3 -m pytest scripts/tests/test_prefill_calibration.py
passes (6 tests). The new premature-eof case fails without the change and
passes with it; a finish_reason-without-[DONE] case is also covered. Run
against a local HTTP fixture only; no real vLLM server or cluster was used.
Report: https://github.com/llm-d/llm-d/issues/3024
Signed-off-by: Pujitha Paladugu <10557236+pujitha24@users.noreply.github.com>
Assisted-by: claude-sonnet-5-5 (via Claude Code)
Fixes #3024
Prevents truncated prefill calibration streams from recording false-positive throughput measurements. In guides/recipes/router/calibration/calibration-peak-throughput.yaml, send_one now tracks whether a completion signal (data: [DONE] or a truthy finish_reason in any choice) was observed, raising RuntimeError if the stream ends on premature EOF. First-chunk TTFT measurement, trailing error envelope parsing, and HTTP error handling remain unchanged.
completed = False per request in send_one (guides/recipes/router/calibration/calibration-peak-throughput.yaml:80).completed = True on payload == b"[DONE]" (breaking immediately) or when any entry in event.get("choices") contains a truthy finish_reason (guides/recipes/router/calibration/calibration-peak-throughput.yaml:88,95-99).finish_reason is set.first_chunk_ttft is None (empty stream) or not completed (stream closed prematurely without finish marker) (guides/recipes/router/calibration/calibration-peak-throughput.yaml:110-115).scripts/tests/test_prefill_calibration.py covering premature EOF, finish_reason without [DONE], and [DONE] with token.send_one issues a streaming /v1/completions request for 8192 random token IDs.finish_reason: None), setting first_chunk_ttft = 0.082s.finish_reason or data: [DONE].send_one returned 0.082s, calculating an invalid peak throughput of 99,902 tok/s. With this fix, completed remains False, triggering RuntimeError("completions stream ended before a finish_reason or [DONE] was received"), which aborts the calibration Job before emitting PEAK_PREFILL_THROUGHPUT=./test-nightly predicted-latency-routing-*session-state-producer publishes per-session counters, but not which endpoint a session is on or how many context tokens it holds there. Plugins that need this keep their own copy (thunder-agent, see #4505) (Part of #3796).What type of PR is this?
/kind feature
What this PR does / why we need it:
session-state-producer publishes per-session counters, but not which endpoint a session is on or how many context tokens it holds there. Plugins that need this keep their own copy (thunder-agent, see #4505). This PR adds both, so consumers share one source.
SessionState gains SessionID, Endpoint, ContextTokens, InFlightTokens, and ContextSize() (plus EstimatePromptTokens).PreRequest binds the session to the primary picked endpoint and charges a prompt token estimate once per RequestID. Every EndOfStream response releases the estimate, aborted streams included. Naturally completed responses set ContextTokens from reported usage (falling back to the prompt estimate when larger).EndpointSessions attribute (EndpointSessionsDataKey, read with PeekEndpointSessions) with its bound sessions and total context tokens.session-state-producer is registered as the default producer for EndpointSessionsDataKey.Test plan:
-race; dependency ordering and attribute scope.Which issue(s) this PR fixes:
Part of #3796
Release note _(write NONE if no user-facing change)_:
`session-state-producer` tracks per-session context token footprint (`ContextTokens`, `InFlightTokens`) and endpoint bindings (`Endpoint`, `EndpointSessionsDataKey`).What type of PR is this?
/kind bug
What this PR does / why we need it:
Step 3 of #4105. With per-pod subscriptions (kvEventsConfig.discoverPods), Pool.processRawMessage files every message under the endpoint the EPP dialed, whatever pod the topic names, so a message whose topic names another pod is filed under a pod that did not claim it.
This PR drops such a message and counts it in llm_d_epp_kv_cache_events_topic_pod_mismatches_total; the topic and the dialed endpoint are logged at debug level. The global socket mode (zmqEndpoint), where the topic is the only source of the pod, is unchanged.
A message is dropped only when its topic names an IP address, with or without a port, other than the dialed host; a topic that names no pod (kv@<model-name>, which #4250 accepts) or names the pod by name keeps the dialed endpoint. Ports are ignored because an engine's data-parallel ranks publish one topic (kv@$(POD_IP):$(POD_PORT)@<model> in the guides) while the EPP dials each rank on its own port, which TestProcessRawMessage_UsesSubscriberSourceEndpoint and TestZMQSubscribers_SameTopicUsesServingEndpointIdentity rely on.
Tests: one table over matching and mismatching IPv4 and IPv6 topics (with and without ports, bracketed and differently written), data-parallel ranks, model-only and pod-name topics, an endpoint dialed by name, and the bound socket; the five mismatch cases fail on main. go test -race ./pkg/kvevents/... ./pkg/kvcache/... and golangci-lint pass (1.27.4, Darwin arm64).
Which issue(s) this PR fixes:
Part of #4105
Release note _(write NONE if no user-facing change)_:
With per-pod KV-event subscriptions, a message whose topic names an IP address other than the dialed host is dropped and counted in `llm_d_epp_kv_cache_events_topic_pod_mismatches_total`.Per-pod KV-event subscriptions previously filed every received batch under msg.SourceEndpoint regardless of the pod address encoded in the ZMQ topic. This change validates the adapter-decoded podID against msg.SourceEndpoint in Pool.processRawMessage, dropping mismatches with a new llm_d_epp_kv_cache_events_topic_pod_mismatches_total counter, debug log, and span error status while leaving global-socket mode (SourceEndpoint == ""), non-IP pod names, model-only topics, and multi-rank port differences unaffected.
Pool.processRawMessage): After Pool.decode runs EngineAdapter.ParseMessage (shared by VLLMAdapter and SGLangAdapter), pkg/kvevents/pool.go#L512-L523 checks topicNamesSource(podID, msg.SourceEndpoint) before mutating index, dedup, group catalog, cache format, or external consumer state.topicPod, extracts the IP from SourceEndpoint using netip.ParseAddr + Unmap(), and tests both topicPod and endpointHost(topicPod) (handling bracketed IPv6 literals with or without ports as well as unbracketed address:port) so DP-rank port differences and unbracketed IPv6 addresses match while mismatched pod IPs are dropped.TopicPodMismatches in pkg/kvcache/metrics/collector.go#L170-L175 (included in Collectors() at #L224) and documents it in docs/metrics.md#L1300 and pkg/kvevents/README.md#L21-L25.10.0.0.1:8000 receives kv@10.0.0.2:8000@Qwen3.Pool.decode parses podID = "10.0.0.2:8000"; topicNamesSource("10.0.0.2:8000", "10.0.0.1:8000") parses 10.0.0.2 and 10.0.0.1, sees a mismatch, increments TopicPodMismatches, marks events_process with error status, logs at DEBUG, and returns before processEventBatch.SourceEndpoint = "fd00::1:8003") receiving kv@fd00::1:8000@Qwen3 or kv@[fd00::1]@Qwen3, topicNamesSource matches fd00::1 == fd00::1 and indexes the batch under fd00::1:8003.pool.go:598, pool.go:558; not yet resolved.conditional-decode step sends the decode request with Prefer: if-available (the probe). It handles a 412 Precondition Failed answer to the probe as a cache miss and any 2xx answer as a served response (Part of #4282).What type of PR is this?
/kind bug
What this PR does / why we need it:
The conditional-decode step sends the decode request with Prefer: if-available (the
probe). It handles a 412 Precondition Failed answer to the probe as a cache miss and
any 2xx answer as a served response. The linked issue changes the router's cache-miss
answer to 204 No Content, so that the router does not count the miss as an error. A
coordinator that accepts only 412 returns that 204 to the client as an empty response.
This PR makes the step handle 204 and 412 as a cache miss. It is the first of two PRs for
the issue. The router continues to answer 412 until the second PR, so this PR does not
change behaviour with a router on main. This PR must merge before the router PR.
conditional-decode: 204 and 412 continue the pipeline, write nothing to the client,and count as conditional_decode_probes_total{result="deferred"}. The cache-miss log
line carries the status.
conditional_decode_probes_total and the comments that named 412 nowdescribe a cache miss.
communication.md and the deferred result inmetrics.coord.md.
Defaults checked:
Status of the answer to the Prefer: if-available request | How the conditional-decode step handles it | Changed |
|---|---|---|
| 204 | Cache miss, deferred | Yes, was served |
| 412 | Cache miss, deferred | No |
| Other 2xx or 3xx | served | No |
| Other 4xx or 5xx | error | No |
Test plan:
deferred.stream_options are kept.Which issue(s) this PR fixes:
Part of #4282
Release note _(write NONE if no user-facing change)_:
The coordinator `conditional-decode` step handles a `204 No Content` answer to its `Prefer: if-available` request as a cache miss, in addition to `412 Precondition Failed`.ttftSource: prefillSteps to prefix-cache-affinity-filter. The load gate estimates TTFT from the requests pending on an endpoint and a profiled step time (Fixes #4297).What type of PR is this?
/kind feature
What this PR does / why we need it:
Adds ttftSource: prefillSteps to prefix-cache-affinity-filter. The load gate estimates TTFT from the requests pending on an endpoint and a profiled step time.
Stacked on #3421, so the diff carries its commits until it merges.
A chunked-prefill engine computes in steps of up to --max-num-batched-tokens. A short request still costs a step, and each request in flight delays the next one whatever its length.
inFlightTokens / peakPrefillThroughput only counts tokens, so a cached endpoint with a queue of short requests reads as nearly idle and the gate keeps sending to it (#3422).
own = max(ceil(tokens / tokensPerStep), 1)
own = ceil(tokens * min(requests + 1, requestsPerStep) / tokensPerStep) if own > 1
TTFT_ms = readMicrosecondsPerToken * (cached + tokens) / 1000 + restore
+ requests * requestMs + own * stepMs + handoffMs
In words: read the prompt, restore the cached prefix if part of it is outside GPU memory, wait requestMs per pending request, compute the new tokens in whole steps, hand off.
requests - requests on the endpoint that have not returned a first token (InFlightLoad.PendingRequests)tokens - prompt tokens the endpoint has to compute (UncachedRequestTokens)cached - the rest of the promptrestore - restoreMs when part of the confirmed cached prefix is outside GPU memory, else 0. Speculative index entries count as GPU-residentExample with the GLM 5.3 profile below: a 66K-token prompt with 3K new tokens and 3 requests pending. Read 0.33 s + 3 x 0.2 s + one step 0.345 s + handoff 0.5 s = 1.77 s. Measured 1.80 s.
UncachedRequestTokens counts cached blocks unweighted by device tier, so a prefix held in CPU memory adds restoreMs and no tokens.
With ttftEstimate: full the estimate adds the queue wait from #3421, and the queued requests are charged that wait in place of requestMs.
The source is opt-in. prefillThroughput and latencyPredictor are unchanged. The README documents each parameter and how to measure it through the router.
| Parameter | Value | Measured as |
|---|---|---|
tokensPerStep | 8192 | engine flag |
requestsPerStep | 4 | engine flag |
stepMs | 345 | prompt of 2 x 8192 uncached tokens minus 1 x 8192, idle engine |
requestMs | 200 | increase of median TTFT per pending request, about 15K requests of open-loop traffic |
readMicrosecondsPerToken | 5 | long cached prompt minus short prompt with the same new tail |
restoreMs | 1000 | prefix restored from CPU memory minus the same prefix in GPU memory: 0.67 s at 4K-16K tokens, 1.0-1.1 s at 32K-262K |
handoffMs | 500 | short prompt minus stepMs under light traffic |
Estimate for the chosen endpoint against TTFT at the client, through the router, on 4 prefill engines. Both sources are computed on the same requests, with peakPrefillThroughput: 12500.
Median error:
| Load | Requests | prefillSteps | prefillThroughput, full | prefillThroughput, backlog |
|---|---|---|---|---|
| Hot spot | 2211 | 19% | 44% | 64% |
| Production-shaped | 1086 | 19% | 51% | 63% |
| Cache churn | 779 | 55% | 81% | 85% |
The loads:
Under cache churn the step estimate reads about 4 s low. A request in flight costs about 650 ms there, against 200 ms in the profile. It reads low by the same amount for restored, GPU-hit and cold requests, so the gate's comparison between endpoints is not skewed.
p90 error:
| Load | prefillSteps | prefillThroughput, full | prefillThroughput, backlog |
|---|---|---|---|
| Hot spot | 42% | 75% | 100% |
| Production-shaped | 39% | 79% | 95% |
| Cache churn | 67% | 91% | 94% |
Router-measured medians used as unit test cases. Median error 5%, worst 24%:
| Requests in flight | Prompt | Uncached | Measured ms | Estimate ms | Error |
|---|---|---|---|---|---|
| 0 | 11240 | 11240 | 1004 | 1246 | +24% |
| 0 | 14980 | 14980 | 1038 | 1265 | +22% |
| 0 | 29940 | 29940 | 2015 | 2030 | +1% |
| 0 | 59861 | 59861 | 3752 | 3559 | -5% |
| 0 | 112220 | 112220 | 6492 | 5891 | -9% |
| 0 | 38621 | 3088 | 975 | 1038 | +6% |
| 0 | 95848 | 2664 | 1382 | 1324 | -4% |
| 0 | 40160 | 2982 | 1086 | 1046 | -4% |
| 1 | 42696 | 3122 | 1403 | 1258 | -10% |
| 2 | 66145 | 3073 | 1622 | 1576 | -3% |
| 3 | 65789 | 3022 | 1799 | 1774 | -1% |
| 4 | 41837 | 2991 | 1907 | 1854 | -3% |
| 5 | 40825 | 3077 | 2067 | 2049 | -1% |
| 6 | 39529 | 2919 | 2140 | 2243 | +5% |
Can the gate replace a concurrency guard on the prefill engines? Three setups on the same seeded loads. Every request returned 200.
concurrency-detector filter (max 8 in flight) in the prefill profile, gate set to never break (maxTTFTPenaltyMs: 30000)prefillSteps with maxTTFTPenaltyMs: 500Mean TTFT:
| Load | Guard on, sticky | Guard off, sticky | Guard off, step gate |
|---|---|---|---|
| Hot spot | 1.92 s | 2.13 s | 1.82 s |
| Production-shaped | 2.26 s | 2.23 s | 2.31 s |
| Cache churn | 7.45 s | 7.29 s | 7.57 s |
p99 TTFT:
| Load | Guard on, sticky | Guard off, sticky | Guard off, step gate |
|---|---|---|---|
| Hot spot | 4.02 s | 5.11 s | 4.23 s |
| Production-shaped | 4.99 s | 4.21 s | 4.45 s |
| Cache churn | 12.62 s | 12.14 s | 12.48 s |
| Load | Setup | Runs | Mean | p90 | p99 | Session requests moved |
|---|---|---|---|---|---|---|
| Hot spot | Guard on, sticky | 3 | 1.92 s | 2.79 s | 4.02 s | 13% |
| Hot spot | Guard off, sticky | 1 | 2.13 s | 3.33 s | 5.11 s | not recorded |
| Hot spot | Guard off, step gate | 3 | 1.82 s | 2.66 s | 4.23 s | 44% |
| Production-shaped | Guard on, sticky | 1 | 2.26 s | 3.17 s | 4.99 s | 1% |
| Production-shaped | Guard off, sticky | 1 | 2.23 s | 3.09 s | 4.21 s | 0% |
| Production-shaped | Guard off, step gate | 1 | 2.31 s | 3.17 s | 4.45 s | 0% |
| Cache churn | Guard on, sticky | 1 | 7.45 s | 10.73 s | 12.62 s | 0.3% |
| Cache churn | Guard off, sticky | 1 | 7.29 s | 10.61 s | 12.14 s | 0% |
| Cache churn | Guard off, step gate | 1 | 7.57 s | 10.43 s | 12.48 s | 0% |
Hot spot runs alternated between the two setups. Mean per run: guard on 1.85, 1.89, 2.04 s. Step gate 1.94, 1.75, 1.76 s.
The step gate runs used a build without the restored-block handling and set the CPU tier weight to 1.0 in kvCacheBackendConfigs. That gives the same tokens as this PR. It also makes the prefix scorer rank CPU and GPU hits equally.
requestMs per pending request with stepMs when unset, step sharing capped at requestsPerStep, whole-prompt read, restore ahead of the first steprequestMsttftEstimate: full, queued requests are charged the queue wait in place of requestMsUncachedRequestTokens skips the gateInFlightLoad and UncachedRequestTokens, and no latency predictionpeakPrefillThroughput needed with prefillStepsmake presubmit passes except verify-review-playbook, which also fails on main (forwardtokens/plugin.go from #3706 has no routing row).
Which issue(s) this PR fixes:
Fixes #4297
Release note _(write NONE if no user-facing change)_:
prefix-cache-affinity-filter: add `ttftSource: prefillSteps`, which estimates the load gate's TTFT from a profiled prefill step time and the requests pending on each endpoint.cache-classifier RequestHeaderProcessor that labels each request as a prefix-cache hit or miss before admission and publishes CacheClass as a DynamicRequestAttribute (match ratio, matched tokens, ready) (Fixes #4350).What type of PR is this?
/kind feature
What this PR does / why we need it:
Adds an opt-in cache-classifier RequestHeaderProcessor that labels each request as a prefix-cache hit or miss before admission and publishes CacheClass as a DynamicRequestAttribute (match ratio, matched tokens, ready).
It maintains a replica-local LRU of admitted prefix hashes (Peek for classify, Add on admit), clears pending state via RequestAbandoned when the request never reaches PreRequest, and records MatchedTokens vs engine cached_tokens for accuracy.
Metrics-only: no priority rewrite, fairness split, missHold, or dispatch gate. Gives capacity / sharing / metrics a stable class signal without changing multi-tenant FC contracts (classifier-first slice of #4021 / #4161; narrower than #3660).
Which issue(s) this PR fixes:
Fixes #4350
Release note _(write NONE if no user-facing change)_:
Add opt-in cache-classifier plugin that attaches a pre-admission CacheClass attribute and metrics without changing flow-control dispatch.Adds opt-in pre-admission prefix-cache classification to approx-prefix-cache-producer (classify: true) and six llm_d_epp_cache_class_* Prometheus metrics so Flow Control consumers can inspect a live CacheClass request attribute without a duplicate prefix index. Before admission, a companion RequestHeaderProcessor asks the consumed token-producer (EstimatePrompt) for capped pseudo-tokens, computes prefix hashes at Produce's last block size, and exposes a Version()-memoized DynamicRequestAttribute backed by approximateprefix's indexer. Scheduling behavior, DataProducer phase ordering, and non-estimate token backends remain unchanged.
plugin.go:305-309, continuation.go:54-61): newDataProducer registers cacheClassHeader as <name>-cache-class via handle.AddPlugin because dataProducer consumes TokenizedPromptDataKey and cannot sit at RequestHeaderLayer (0), while recordTokenBackend resolves *tokenproducer.Plugin when the backend is estimate.classify.go:82-128, estimate_export.go:40-75, indexer.go:302-305): EstimatePrompt applies p.backend's estimate config, x-llm-d-* headers, and maxTokens truncation (produceCapped) while returning full prompt token counts (PromptTokens); DynamicRequestAttribute.Get caches CacheClass in an atomic.Pointer[classAtVersion] keyed by indexerInst.Version().class_metrics.go:92-212, classify.go:237-283): Records admission counts/ratios in RequestHeader, turned-away requests/tokens in RequestAbandoned, and paired predicted-vs-engine cached fractions in PreRequest / ResponseBody when PromptTokenDetails is present.approx-prefix-cache-producer (classify: true) consuming the default estimate token-producer; recordTokenBackend sets estimateTokens = true and stores the *tokenproducer.Plugin pointer.RequestHeader before Produce has run (lastBlockSize == 0), so CacheClass resolves with Ready: false and cache_class_requests_total{cache_class="unready"} increments; after admission, Produce uses blockSize = 64, stores lastBlockSize = 64, and PreRequest indexes Request 1 on pod-a and increments indexer.Version().RequestHeader calls EstimatePrompt capped at resolveMaxBlocks(64) * 64, hashes at 64, computes Ready: true, Hit: true, and caches the result at the current indexer.Version(), serving repeat Flow Control reads in O(1) until the index changes.What type of PR is this?
/kind feature
What this PR does / why we need it:
the epp resolves x-request-id for every request and logs it, but on spans it only lands on
a few scheduling children, so searching that id in jaeger or tempo often finds nothing.
the response carries neither id, so a user reporting a slow request has nothing to quote.
gen_ai.request.id goes on the epp root request span and on the sidecar forward_request
span, same key in both. the response returns x-request-id, and traceparent when enabled.
--enable-request-id-response-header defaults on. --enable-traceparent-response-header
defaults off, it exposes trace ids outside the cluster. only traceparent goes back,
tracestate and baggage can hold internal values.
llm_d.pd_proxy.request_id stays on the prefill spans, #4005 shipped it and consumers read it.
Which issue(s) this PR fixes:
Fixes #4357
Release note:
EPP returns the resolved x-request-id on responses, controlled by --enable-request-id-response-header (on by default), and the request span's W3C traceparent via --enable-traceparent-response-header (off by default). The EPP request span and the routing sidecar request span carry the request ID as gen_ai.request.id.
Adds gen_ai.request.id to both the EPP root request span and the routing sidecar forward_request span, and configures EPP to return the resolved x-request-id (on by default) and optionally the request span's traceparent (off by default) on both upstream-forwarded and EPP-originated ImmediateResponse replies. Existing llm_d.pd_proxy.request_id attributes on sidecar prefill spans and outbound W3C trace context propagation to upstream requests remain unchanged.
pkg/epp/handlers/server.go:709-729 captures reqCtx.resolvedRequestID at RequestHeaders ingress, sets semconv.GenAIRequestID(requestID) on the root request span, and resolves reqCtx.correlationHeaders once via correlationResponseHeaders; pkg/sidecar/proxy/dispatch.go:91-93 sets gen_ai.request.id on forward_request when x-request-id is present.pkg/epp/handlers/response.go:437-546 prepends reqCtx.correlationHeaders in generateResponseHeaders (dropping any upstream x-request-id when requestIDResponseHeader is active), attaches them to ImmediateResponse replies in pkg/epp/handlers/responder.go:68, pkg/epp/handlers/server.go:979, and pkg/epp/handlers/server.go:1138, and formats traceparent directly from trace.SpanContextFromContext(ctx) in formatTraceparent so tracestate and baggage are never serialized.pkg/epp/server/options.go:191 and pkg/epp/server/runserver.go:324-325 wire --enable-request-id-response-header (default true) and --enable-traceparent-response-header (default false) into StreamingServer.POST /v1/chat/completions without x-request-id and with traceparent: 00-<traceID>-<spanID>-01.Process generates UUID req-uuid, stores it in reqCtx.resolvedRequestID and reqCtx.Request.Headers["x-request-id"], starts the request span joined to <traceID> with gen_ai.request.id=req-uuid, and populates reqCtx.correlationHeaders.appendCorrelationHeaders attaches x-request-id: req-uuid (and traceparent if enabled) to the ImmediateResponse; otherwise disaggregatedPrefillHandler records gen_ai.request.id=req-uuid on forward_request and generateResponseHeaders emits reqCtx.correlationHeaders while suppressing any backend x-request-id./v1/audio/transcriptions and /v1/audio/translations fall into the text UNKNOWN output bucket today, so token-load scoring does not reflect the audio duration and ASR completion counts can train the text average (Fixes #4506).What type of PR is this?
/kind feature
What this PR does / why we need it:/v1/audio/transcriptions and /v1/audio/translations fall into the text UNKNOWN output bucket today, so token-load scoring does not reflect the audio duration and ASR completion counts can train the text average.
This estimates ASR output from the uploaded audio duration using the same duration resolution as the input estimator: the x-llm-d-audio-duration-seconds header, PCM WAV metadata, or byte rate. It parses prompt, hotwords, and max_completion_tokens, estimates output at four tokens per second capped at 16,384, and applies max_completion_tokens per 30-second audio chunk with vLLM's 1-second split window. ASR requests are left UNKNOWN in outlen-bucket, and their completion counts are excluded from the text UNKNOWN average.
The rate and chunk defaults are cross-model heuristics; per-pool calibration remains a follow-up.
Which issue(s) this PR fixes:
Fixes #4506.
Related: #2220 (separate text and non-text token load).
Release note:
Estimate transcription and translation output work from audio duration for token-load routing.
Test plan:
max_completion_tokensUNKNOWN averagehotwords and max_completion_tokens for both endpointsThis PR separates /v1/audio/transcriptions and /v1/audio/translations output-token estimation from the text UNKNOWN bucket by estimating output tokens from uploaded audio duration and excluding ASR requests from outlen-bucket classification and ObserveOutput. It also parses hotwords (folded into input token estimation) and max_completion_tokens (scaled across 30s audio chunks with a 1s overlap), and adds an isTranscription path-fallback guard in InFlightLoadProducer.ResponseBody matching TTS and image handling after request body release. Text chat/completions estimation and outlen-bucket classification for text requests remain unchanged.
pkg/epp/framework/plugins/requesthandling/parsers/openai/openai.go:926-933): parseTranscriptionsRequest captures multipart hotwords onto TranscriptionRequest.Hotwords (pkg/epp/framework/common/request/types.go:820) and parses max_completion_tokens into InferenceRequestBody.MaxOutputTokens.pkg/epp/framework/plugins/requesthandling/dataproducer/tokenizer/estimate.go:340-348): transcriptionsBytes appends non-blank Hotwords after Prompt before the audio placeholder tokens; pkg/epp/framework/plugins/requesthandling/dataproducer/tokenizer/mm_estimate.go:512-514 exports AudioDurationSeconds wrapping (audioEstimator{}).durationSecondsUploaded.pkg/epp/framework/plugins/requesthandling/requestheader/outlenbucket/outlenbucket.go:111-113, pkg/epp/framework/plugins/requesthandling/dataproducer/inflightload/token_estimator.go:170-172,274-304): EstimateOutlen returns Unknown when body.Transcriptions != nil; SimpleTokenEstimator.EstimateOutputFromRequest delegates to transcriptionOutputTokens (4 tokens/s, capped at 16,384, scaling max_completion_tokens by ceil(duration / 29) chunks when duration > 30s, then clamped by MaxEstimatedOutputTokens).pkg/common/request/apitype.go:37-38, pkg/epp/framework/plugins/requesthandling/dataproducer/inflightload/producer.go:691,728-735): InFlightLoadProducer.ResponseBody skips ObserveOutput when isTranscription(request) is true, checking request.Body.Transcriptions != nil pre-release and matching PathAudioTranscriptions or PathAudioTranslations suffixes after ResponsePhaseView() drops Transcriptions./v1/audio/transcriptions with prompt="prev", hotwords="llm-d", and max_completion_tokens=10.parseTranscriptionsRequest populates Transcriptions.Prompt, Transcriptions.Hotwords, Transcriptions.Audio, and MaxOutputTokens=10; transcriptionsBytes packs "prev\nllm-d" ahead of the audio placeholders.EstimateOutlen returns Unknown; SimpleTokenEstimator.EstimateOutputFromRequest resolves duration=60s, computes expected=240, chunks=ceil(60/29)=3, cap=10*3=30, and returns 30 (clamped by any operator cap).ResponsePhaseView() drops Transcriptions; when the response ends, isTranscription matches /v1/audio/transcriptions on :path so ResponseBody skips ObserveOutput.What type of PR is this?
/kind feature
What this PR does / why we need it:
Part of the KV block index representation series (#4529).
Based directly on main; #4457 and #4458 already merged.
The walk read path (WalkKeys + prefix matching) materializes PodIdentifier and DeviceTier strings for every visited entry. This changes WalkEntry to carry pod and tier ordinals only, with an OrdinalResolver interface the consumer uses to resolve ordinals to names when it needs them. Walkers that only count or filter never allocate the strings.
This is the KeyWalker contract change of the series: anything implementing KeyWalker must follow it, so it merges first among the behavioral PRs. Match results are unchanged; the resolver returns the same names the strings carried. Prefix-match behavior is covered by the parity harness, which asserts the walked and materialized read paths agree.
Which issue(s) this PR fixes:
Part of #4529.
Release note _(write NONE if no user-facing change)_:
NONE
Test plan:
Replaces string-bearing EntryRef slices on the KeyWalker read path with ordinal-only WalkEntry values and adds an OrdinalResolver capability so prefix matching resolves pod and tier names only at request boundaries. InMemoryIndex caches per-key group-deduplication validity via PodCache.groupedKnown and forwards OrdinalResolver conditionally across instrumented/traced decorators, while Lookup and materialized matching retain string-keyed behavior unchanged.
WalkEntry{PodOrdinal, TierOrdinal, Speculative}, ReservedTierOrdinal (math.MaxUint32), and OrdinalResolver (PodOrdinal, PodName, TierOrdinal, TierName). NewInstrumentedIndex and NewTracedIndex return instrumentedWalkerResolver / tracedWalkerResolver only when the wrapped KeyWalker also implements OrdinalResolver, keeping a resolverless walker on Lookup.interner behind sync.RWMutex with a reverse names slice so PodName/TierName resolve concurrently without mutating. PodCache.visitEntries folds duplicate (pod, tier, speculative) triples across HMA groups into a single WalkEntry using groupedKnown, invalidated on addAll/removeAll (in_memory.go, in_memory.go).startWalk resolves podFilter, tierScoring weights, and SpeculativeTier to ordinals once before WalkKeys, runs the accumulator purely on uint32 ordinals, and resolves winning pod and tier names back via OrdinalResolver in result().10, 20 with {PodIdentifier: "pod-a", DeviceTier: "gpu", HasGroup: true, GroupIdx: 1} and GroupIdx: 2, where pods interned "pod-a" -> 0 and tiers interned "gpu" -> 0.MatchBlockKeys verifies both keyWalker and ordinalResolver are non-nil and calls startWalk, resolving filter "pod-a" -> 0 and weight "gpu" -> (0, 1.0) once.InMemoryIndex.WalkKeys peeks each key, folds the two grouped entries into one WalkEntry{PodOrdinal: 0, TierOrdinal: 0} in scratch, and passes it to acc.key.acc.result() resolves PodName(0) -> "pod-a" and TierName(0) -> "gpu", returning {MatchedBlocks: 2, WeightedScore: 2.0}.Stops re-rendering the whole conversation on every turn of an agentic session. Opt-in, chat completions only, off by default.
The problem, measured. Agentic clients resend the full conversation each turn, and the token-producer renders the full prompt per request on the scheduling path. On a 1-hour agentic-trace replay (74,542 chat requests, mean prompt 132,843 tokens, 87.8% of prompt tokens served from the KV prefix cache, 20.5 req/s) against a 2P+1D GB200 deployment where the render Service pointed at the prefill pods themselves:
Sources: vllm time_to_first_token, request_queue_time, request_prefill_time histograms aggregated over the profiling window; in-flight split from engine running/waiting gauges.
The change. Cache rendered prompts keyed by a SHA-256 chain over the raw message JSON: node i commits to the template-affecting envelope fields (model, tools, tool_choice, response_format, chat_template_kwargs, ...) plus the first i messages. Turn N+1 repeats turn N's deepest node.
context.WithoutCancel + own timeout, semaphore-bounded) so the session's next turn full-hitsDropping the new suffix on a partial hit is exact where it matters: the suffix was never seen, so no pod's KV index can match it; prefix matching loses the suffix plus at most the last partial block, and the published IDs stay exact for the prefix they cover. The token-load scorer undercounts by the appended messages. Generation-only fields (max_tokens, temperature) don't salt the chain, so per-turn param changes don't break it; envelope key order doesn't either. Multimodal payloads never warm in the background (their render metadata is request-scoped) but still hit over text prefixes. Completions / Messages / Responses pass through unchanged.
- type: token-producer
parameters:
modelName: <model>
vllm:
url: <render endpoint>
prefixCache:
enabled: true # maxEntries 4096, maxBytes 256MiB, asyncWarm 8 x 15s
One metric: epp_token_producer_prefix_cache_events_total{event=hit_full|hit_partial|miss|store|evict|warm|warm_failure|bypass}.
Tests. Chain prefix equality across turns, salt selection and key-order independence, non-chat rejection, escaped-marker handling; partial-hit-serves-prefix + background warm + subsequent full-hit, errors not stored, LRU eviction, multimodal never warms, Completions passthrough, config parsing/defaults, NewPlugin wiring and timeout delegation; 64-goroutine fan-in under -race (which caught an entry-mutation race โ entries are now replaced, never mutated).
Known limits: a prefix matches only when prior messages are resent byte-identically (full-replay clients do this); key reordering inside a message is a correctness-preserving miss. Storing token IDs rather than block keys keeps downstream untouched at ~30x the memory; publishing block keys directly is a possible follow-up.
Added an opt-in conversation-prefix render cache to the token-producer vLLM backend (`vllm.prefixCache.enabled`). Chat requests whose conversation repeats a previously rendered prefix publish the cached prefix tokens without a render round trip, and render the full prompt in the background for the session's next turn. Off by default.
๐ค Generated with Claude Code
prefixcache.go:218 awaiting @elvircrn's response.EPP metrics port has no single source of truth (Fixes #4644).What type of PR is this?
/kind bug
What this PR does / why we need it:
In the Helm chart, the EPP metrics port has no single source of truth. Three places configure it independently:
EPP /metrics endpoint comes only from router.epp.flags.metrics-port and ignores router.metricsPort (default 9090).metrics containerPort on the EPP container is hardcoded to 9090.http-metrics port on the Kubernetes Service reads only router.metricsPort (default 9090) and ignores router.epp.flags.metrics-port.When a user sets a metrics port other than 9090 through router.metricsPort, router.epp.flags.metrics-port, or both, the rendered listening port, containerPort, and Service port diverge. As a result, metrics scraping fails.
Fix:
The fix introduces one template helper (llm-d-router.epp.metricsPort) as the single source of truth.
It resolves the port in order from router.epp.flags.metrics-port, router.metricsPort, or default 9090, skipping null or blank values and validating 1..65535.
All three chart locations (EPP --metrics-port args, the metrics containerPort, and http-metrics Service ports) consume that same value while preserving existing config compatibility.
Which issue(s) this PR fixes:
Fixes #4644
Release note _(write NONE if no user-facing change)_:
Fixed Helm chart rendering so custom EPP metrics ports apply consistently to EPP args, containerPort, and Service ports.This change centralizes EPP metrics port resolution in a single Helm template helper (llm-d-router.epp.metricsPort) so the EPP --metrics-port argument, metrics containerPort, and http-metrics Service port always match. Previously _deployment.yaml hardcoded containerPort: 9090 and ignored router.metricsPort, while _service.yaml read only router.metricsPort and ignored router.epp.flags.metrics-port. Existing default behavior when neither setting is overridden stays unchanged (9090 with no explicit --metrics-port flag).
config/charts/routerlib/templates/_helpers.tpl:196-232): llm-d-router.epp.metricsPort checks .Values.router.epp.flags.metrics-port, then .Values.router.metricsPort, then defaults to 9090, skipping null/whitespace values and validating numeric 1..65535.config/charts/routerlib/templates/_deployment.yaml:9-17,153-155,182-183): Normalizes or unsets metrics-port in $eppFlags (so blank/null flag overrides do not render --metrics-port=<nil>), emits --metrics-port={{ $metricsPort }} when non-default and absent from $eppFlags, and sets containerPort: {{ $metricsPort }}.config/charts/routerlib/templates/_service.yaml:35-37,60-62): Updates both the GKE preferred-backends Service loop and the standard Service http-metrics port to use llm-d-router.epp.metricsPort (matching ServiceMonitor port: "http-metrics" and GMP PodMonitoring port: metrics).router.metricsPort=9190 and overrides router.epp.flags.metrics-port=null in an overlay.llm-d-router.epp.metricsPort skips the null flag, resolves 9190 from router.metricsPort, and validates 1 <= 9190 <= 65535._deployment.yaml unsets metrics-port from $eppFlags, adds --metrics-port=9190 to EPP args, sets containerPort: 9190 on metrics, and _service.yaml sets port: 9190 on http-metrics.e2e-prediction-pd-profile-handler for heterogeneous inference pools (such as AMD and NVIDIA) serving the same model (Fixes #4735).What type of PR is this?
/kind feature
What this PR does / why we need it:
Adds an optional alpha e2e-prediction-pd-profile-handler for heterogeneous inference pools (such as AMD and NVIDIA) serving the same model.
On each request, the handler first runs the default whole-request profile as a baseline and fallback, then queries a predictor service for TTFT and TPOT estimates across eligible whole-request and split P/D paths (using prompt length, output budget, prefix cache hits, and endpoint load). It switches away from the baseline only when an alternative path has a strictly lower predicted E2E and adds at most 5000 ms to predicted TTFT. If the predictor times out or cannot score the baseline, the handler keeps the baseline endpoint.
Split P/D paths are opt-in and require operator-verified direction configuration along with compatible KV labels, reusing the existing serial NIXL sidecar for Prefill-to-Decode handoff. A standalone CPU predictor service handles initial calibration records and updates its model from completed SSE streams (requiring confirmation from the sidecar that Prefill KV parameters were actually handed off to Decode).
Prototype experiments on a 2.5G Soft-RoCE setup (306 total requests per arm) illustrate the tradeoff: overall E2E P50 improved by 2.62% (26.34 s to 25.65 s), with 13 of 306 requests routed to AMD Prefill + NVIDIA Decode (all from the 2048-input/2048-output cohort, where E2E P50 dropped from 69.14 s to 56.66 s while TTFT P50 rose from 0.40 s to 7.54 s). In this environment, P/D gains are limited because the two vLLM hosts are connected over a 2.5G switch using Soft-RoCE through CPU staging buffers; high-speed NICs with hardware RDMA would substantially speed up KV cache transfer and shift the routing sweet spot, which the calibration step measures and captures automatically. Note that this upstream port has been exercised with mock backends and has not yet been benchmarked on GPUs.Fixes
Which issue(s) this PR fixes:
Fixes #4735
Related to #3791: This PR addresses related hardware-aware P/D routing with E2E prediction and a TTFT guardrail, using a different optimization objective and implementation; it does not fully resolve that issue.
Test plan:
make presubmit targets passed natively on macOS with the Go and tool versions pinned by the builder.make presubmit (the builder image download timed out).Release note _(write NONE if no user-facing change)_:
Add an experimental E2E prediction profile handler that compares whole-request and prefill/decode paths in heterogeneous inference pools serving the same model.What type of PR is this?
/kind feature
What this PR does / why we need it:
This is the second of two PRs for #3546. The first, #4575, added the shared reply encoder this PR builds on.
A force-streamed reply is written only after the upstream stream ends. The client waits for the whole generation, and the coordinator holds the whole reply. This PR adds the pipeline setting force_stream_delivery:
buffered (default): unchanged.incremental: the reply is sent to the client in frames of up to 16KiB as the stream is folded.How incremental delivery saves memory:
forceStreamFrameBytes, one HTTP/2 DATA frame) has accumulated. The rest is sent when the stream ends ([DONE], or the terminal event of Messages and Responses), so a reply shorter than a frame is sent whole at the end, as buffered delivery sends it. No timer runs per request. On HTTP/1.1 each piece goes out as one chunk.Content-Length.How the two deliveries stay aligned:
sseReassembler), the same per-frame checks in scanForcedResponse (lossy frames, error frames, the per-request ceiling) and the same encoder. encodeReply is a single final drain of a replyStream, and incremental delivery drains that stream each time it sends. Each content piece is a whole decoded string, which encoding/json escapes rune by rune, or a batch of token ids joined to the next with a comma, so the drained bytes equal the buffered bytes. The golden test checks both ways for every shape.Content-Length.error_after_commit, and the step aborts the connection with http.ErrAbortHandler, as the decode pass-through does when its body copy fails, so the client sees the body cut off. The faults are an error frame, a lossy frame, a read failure, a stream that ends before a terminal marker, or a failed client write. conditional-decode records its probe result before the abort. A committed reply is never re-sent. A client that disconnects is a cancellation.Shapes under incremental:
finish_reason and stop_reason until then.Budget and memory:
fallback_unbounded, so a request with a large max_tokens is force-streamed.error_ceiling, and aborts the connection after it.error_ceiling.Shared usage entry point (follow-up from the #4575 review):
usage.Options.apply. The response writer's JSON and SSE paths call it for every usage block they read, and the forced reply calls the exported Options.Apply on its folded block, so a rule added there reaches both pass-through and forced replies.usageOptions in parity.go builds the options for both paths: parityResponseWriter passes them to usage.NewResponseWriter, and applyForcedUsage applies them to the forced block.force_stream_delivery (env COORDINATOR_PIPELINE_FORCE_STREAM_DELIVERY) is validated at config load like the sizes, also with force_stream off, and is rejected as a step parameter.
Test plan:
force_stream_total outcome and upstream calls for chat (n=1 and n=2), completions, generate and Messages, including a frame that fills a frame of content and would pass the reservation.Content-Length included.error_after_commit, sends no fallback and releases the reservation.fallback_unbounded; it reserves a smaller buffered estimate when there is one, and the buffered estimate with several choices.error_ceiling to the pass-through.Content-Length.force_stream_delivery is loaded from config, validated, and rejected as a step parameter.Options.Apply reports a usage block before rewriting it and leaves a schema without a cached-token field alone, and for chat, Responses and Messages blocks it gives the block the response writer gives the same reply.Which issue(s) this PR fixes:
Fixes #3546
Release note _(write NONE if no user-facing change)_:
The coordinator adds the pipeline setting `force_stream_delivery`. `buffered`, the default, writes a force-streamed reply after the upstream stream ends. `incremental` sends it in frames of 16KiB as the stream arrives, and the rest when the stream ends, and for a single-choice or Messages reply reserves only that frame from `force_stream_buffer_size`, whatever the request's token limit; a fault after the first frame is sent aborts the connection and is counted as `error_after_commit` in `llm_d_coordinator_force_stream_total`.Adds pipeline.force_stream_delivery (buffered default, or incremental) so force-streamed replies can flush choice 0 (or Messages text) to the client in 16KiB frames as upstream SSE chunks fold rather than buffering the entire completion in memory. Single-choice and Messages replies reserve only one 16KiB frame plus envelope overhead (~18KiB) instead of force_stream_max_request_size (256KiB) or failing as fallback_unbounded. Buffered behavior remains unchanged, multi-choice replies still hold choices 1..n-1 until [DONE], and Responses replies still emit at their terminal event.
pkg/coordinator/config/config.go, pkg/coordinator/pipeline/builder/builder.go, pkg/coordinator/steps/force_stream.go): Parses force_stream_delivery (buffered | incremental) at config load even when force_stream is off, rejects it as a step param in rejectForceStreamParams, and passes forceStreamDelivery to DecodeStep and ConditionalDecodeStep.pkg/coordinator/steps/sse_reassemble.go): Factors encoding into replyStream (encodeReply is a single drain(true)). drain(false) opens choice 0 (or Messages text) once and drains accumulated content/tokens while subtracting drained bytes from r.contentBytes so the per-request ceiling bounds only un-sent bytes. Later choices (index > 0) stay buffered until drain(true).pkg/coordinator/steps/force_stream.go, decode.go, conditional_decode.go): incrementalReply.flush commits HTTP 200 (without Content-Length, stripping streamOnlyHeaders) once pendingBytes() >= 16KiB. Faults before commit use the existing buffered fallback/error-forwarding paths. Faults after commit record force_stream_total{result="error_after_commit"} in finishCommitted (with conditional-decode recording served first) and trigger abortCommitted (panic(http.ErrAbortHandler)), which propagates through pipeline.go (step_errors_total{error_code="internal"}), handlers.go (request_error_total{error_code="internal"}), and chi Recoverer to sever the connection.pkg/common/usage/cached_tokens.go, pkg/coordinator/steps/parity.go): Moves OnUsage + SetCachedTokens into Options.Apply so pass-through parityResponseWriter and forced applyForcedUsage share one implementation.POST /v1/chat/completions (stream: false, no max_tokens) with pipeline.force_stream: true and force_stream_delivery: incremental.tryForceStream (pkg/coordinator/steps/force_stream.go:438-444) sees holdsOneFrame(sseShapeChat, 1) == true and reserves frameReservation (~18KiB) instead of 256KiB (fallback_unbounded is avoided even if max_tokens: 100000).scanForcedResponse folds SSE deltas. Below 16KiB, nothing is sent; once 16KiB of choice-0 content accumulates, incrementalReply.flush calls drain(false) and writes HTTP 200 (chunked, no Content-Length) + {"choices":[{"index":0,"logprobs":null,"message":{"content":"... and flushes.[DONE] arrives cleanly, finishCommitted runs applyForcedUsage, writes the tail + envelope (drain(true)), and increments forced; if an error frame or stream truncation occurs after commit, it increments error_after_commit and panics http.ErrAbortHandler to cut the TCP/HTTP2 stream without retrying.What type of PR is this?
/kind feature
What this PR does / why we need it:
On AMD MoRI-IO, each vLLM pod serves all of its DP ranks on one port, so the EPP can only pick a pod and vLLM's internal balancer picks the rank. Per-rank prefix-cache locality is lost. The sidecar already runs one listener per rank when --data-parallel-size > 1, but in MoRI-IO WRITE mode it still picks KV ranks with a request-ID hash and sends x-data-parallel-rank, which a single-rank vLLM server rejects for any rank other than 0.
This adds an opt-in per-rank mode, active only when --data-parallel-size > 1 and --moriio-write-mode are both set. Without that combination nothing changes.
decode_pod_index * N + (listen port - --port), where decode_pod_index is the position of --moriio-local-pod-ip in --moriio-decode-hosts (0 without hosts). A request arriving on rank 0 with the deprecated x-data-parallel-host-port header uses that header's port; an unknown value is rejected before prefill runs.x-data-parallel-rank header is sent.remote_dp_size_local is always N on every leg.--moriio-dp-size-local defaults to, and must equal, --data-parallel-size; --moriio-dp-size must be a multiple of it; multi-pod deployments must list every pod in both host flags; the local pod IP must be one of the decode hosts.The matching vLLM change is a separate PR that adds kv_connector_extra_config.dp_size_local, so per-rank MoRI-IO children bind the ports this sidecar already addresses. The llm-d guide overlay amd-ci-per-rank uses both.
Testing
Rebased onto upstream/main 8eef60c2. Run natively on ./pkg/sidecar/..., because the builder container wasn't available:
go test -race -count=1, go vet and gofmt pass.golangci-lint run --new-from-rev=upstream/main with .golangci.yml and .golangci-security.yml: 0 issues. golangci-lint fmt --diff is clean.typos, hack/copyright.sh verify, scripts/check-latest-tags.sh and scripts/check-commits.sh pass. go mod tidy leaves go.mod and go.sum unchanged.govulncheck and verify-telemetry. render_playbook.py --check fails on main for two unrouted files outside this change.TestPerRankDPRanks, TestCompleteMoRIIOPerRankPorts, and a handler-level table for serial, serial with a returned prefill rank, and parallel dispatch. The table runs the real rank listeners in the 2P2D shape (16 global ranks, 8 per pod). All existing NVIDIA and MoRI specs still pass. Mutating the rank logic makes the new tests fail.End to end (run on the sidecar before the final rebase; not repeated on this exact diff): DeepSeek-V3 wide-EP 2P2D on 4x8 MI355X, one vLLM API server per rank, InferencePool ports 8000-8007.
dp_requests 32/32 returned HTTP 200.Overlap: #3821 routes the rank by header on one port per pod and leaves MoRI-IO out, so this is orthogonal. Both edit the x-data-parallel-rank handling in connector_nixlv2.go; whichever lands second needs a rebase there. If both land, setPrefillDPRank must not set a non-zero rank on a per-rank target.
Which issue(s) this PR fixes:
Fixes #<issue number>
Release note _(write NONE if no user-facing change)_:
The P/D sidecar supports MoRI-IO WRITE mode with one vLLM API server per DP rank: with --data-parallel-size > 1 and --moriio-write-mode, MoRI-IO DP ranks are taken from the routed ports instead of a request hash, and no x-data-parallel-rank header is sent.VLLM_LOGGING_LEVELFixes #2847.
The current verification command can stop on an evicted or terminated pod before it reaches the running consumers. Empty output is also ambiguous until a post-rollout request is sent, and reverting DEBUG immediately replaces the pods that contain the transfer evidence. These runbook gaps can turn a working NIXL EC transfer into a false-negative investigation.
kubectl logs --help confirms --ignore-errors=true is supportedpre-commit hooks pass, including markdownlintpython scripts/guide.py render guides/multimodal-serving --check passesgit diff --check passesThis is a documentation-only change. I did not rerun the GPU topology locally; the issue contains the live E/PD and E/P/D reproduction evidence.
Prepared with OpenAI Codex assistance. I reviewed the final diff and am the author of record.
Closes #2934.
With vLLM speculative decoding on (for example MTP in the GLM-5.2 guide), the observability docs don't say how to tell apart:
A model-level acceptance ratio can also hide an engine whose accepted-token series is missing, because its draft tokens still count in the denominator.
model-server-metrics.md: new "vLLM Speculative Decoding Metrics" table, checked against vLLM 85e199e (linked).promql.md: new "Speculative Decoding" section (sum-of-numerator รท sum-of-denominator, per-engine coverage check, reset hint).speculative-decoding.md runbook, plus its README link and menu-config.json entry.vllm:spec_decode_scheduled_steps_total from vllm-project/vllm#54748 (not merged). It is marked optional; nothing else depends on it.model-server-metrics.md, so the file passes markdownlint (MD060). Formatting only.absent(), a missing accepted-token series, and a smaller verification budget as the counters show it (acceptance and mean acceptance length fall while the proposal length stays the same). The full fixture is not part of this PR, since the repo has no PromQL test setup; I can add it wherever you prefer. A runnable excerpt (zero denominator, partial engine coverage) is below.make verify: passes (it checks guides only, which this PR does not touch).rule_files: []
evaluation_interval: 1m
fuzzy_compare: true
tests:
# Zero denominator: the ratios have no sample (undefined, not 0). The
# activity query still returns an explicit 0, so the empty ratio here comes
# with a present, flat denominator.
- interval: 1m
input_series:
- series: 'vllm:spec_decode_num_draft_tokens_total{model_name="m",engine="0",namespace="ns",pod="a"}'
values: '300+0x10'
- series: 'vllm:spec_decode_num_accepted_tokens_total{model_name="m",engine="0",namespace="ns",pod="a"}'
values: '180+0x10'
- series: 'vllm:spec_decode_num_drafts_total{model_name="m",engine="0",namespace="ns",pod="a"}'
values: '100+0x10'
promql_expr_test:
- expr: sum by(model_name, namespace, pod, engine) (rate(vllm:spec_decode_num_accepted_tokens_total[5m])) / (sum by(model_name, namespace, pod, engine) (rate(vllm:spec_decode_num_draft_tokens_total[5m])) > 0)
eval_time: 10m
exp_samples: []
- expr: sum by(model_name, namespace, pod, engine) (rate(vllm:spec_decode_num_draft_tokens_total[5m])) / (sum by(model_name, namespace, pod, engine) (rate(vllm:spec_decode_num_drafts_total[5m])) > 0)
eval_time: 10m
exp_samples: []
- expr: sum by(model_name, namespace, pod) (rate(vllm:spec_decode_num_drafts_total[5m]))
eval_time: 10m
exp_samples:
- labels: '{model_name="m",namespace="ns",pod="a"}'
value: 0
# Partial coverage: one pod, two engines, engine 1 has no accepted
# series. Per minute: engine 0 drafts 100 tokens and accepts 20, engine 1
# drafts 100. The model-level ratio comes out as a plausible-looking
# 20/200 = 0.1 because the missing numerator counts as nothing. A
# pod-level coverage check misses it (the pod exists on both sides). The
# engine-level check finds it.
- interval: 1m
input_series:
- series: 'vllm:spec_decode_num_draft_tokens_total{model_name="m",engine="0",namespace="ns",pod="a"}'
values: '1000+100x10'
- series: 'vllm:spec_decode_num_accepted_tokens_total{model_name="m",engine="0",namespace="ns",pod="a"}'
values: '200+20x10'
- series: 'vllm:spec_decode_num_draft_tokens_total{model_name="m",engine="1",namespace="ns",pod="a"}'
values: '1000+100x10'
promql_expr_test:
- expr: sum by(model_name) (rate(vllm:spec_decode_num_accepted_tokens_total[5m])) / (sum by(model_name) (rate(vllm:spec_decode_num_draft_tokens_total[5m])) > 0)
eval_time: 10m
exp_samples:
- labels: '{model_name="m"}'
value: 0.1
# Pod-level coverage check (rejected): finds nothing.
- expr: count by(model_name, pod) (vllm:spec_decode_num_draft_tokens_total) unless count by(model_name, pod) (vllm:spec_decode_num_accepted_tokens_total)
eval_time: 10m
exp_samples: []
- expr: count by(model_name, namespace, pod, engine) (vllm:spec_decode_num_draft_tokens_total) unless count by(model_name, namespace, pod, engine) (vllm:spec_decode_num_accepted_tokens_total)
eval_time: 10m
exp_samples:
- labels: '{model_name="m",engine="1",namespace="ns",pod="a"}'
value: 1
Not done:
/metrics scrape.This PR was prepared with AI assistance (Claude Code); I reviewed every change and can answer for it.
๐ค Generated with Claude Code
closes #2849
same pattern as #2791 for the 10 guides it didn't cover: multimodal-serving, omni-serving, flow-control, coord-disaggregation, fast-model-actuation, modelexpress-p2p, hyperconverged-cephfs, glm-5-2, nemotron-3-ultra and qwen3-5-397b. each one now has the GKE option for the router (monitoring-gke.values.yaml, so the EPP gets a GMP PodMonitoring), as tabs where the guide already had a monitoring step and as a short note where it's prose.
the "no PodMonitor needed on GKE" tab for model servers is only on multimodal-serving, nemotron-3-ultra and flow-control since those run plain vLLM. glm-5-2, omni-serving and qwen3-5-397b keep their PodMonitors because of the per-rank ports, vllm-omni and TPU vLLM. p2p-kv-cache-sharing and deepseek-v4 have no GKE path so they're left out.
Add like a GPU store. This PR: No code changes.What type of PR is this?
/kind documentation
/area kvcache
What this PR does / why we need it:
#4040: with vLLM's OffloadingConnector in its default mode, a CPU BlockStored carries block hashes but no tokens, so the pool indexes it through the engine-key mapping of the chunk's GPU store. When vLLM evicts a GPU block before its offload completes, it publishes the GPU removal first, the removal drops the mapping if no other pod holds the block, and the CPU store is skipped.
vLLM's self-describing offload events (vllm-project/vllm#43468) carry the chunk's tokens and parent hash, so the pool indexes them through Add like a GPU store. This PR:
"self_describing_kv_events": true. It also states the limit: the self-describing payload sends extra_keys as null, so CPU entries for prompts with multimodal inputs or a cache_salt do not match lookups.No code changes. The legacy payload stays order-dependent, and multimodal or salted prompts still need a fix in the index or in vLLM, so the issue stays open after this PR.
Test plan:
-race, 3 runs).go test -race ./pkg/kvevents/....golangci.yml and .golangci-security.yml), gofmt, typosWhich issue(s) this PR fixes:
Refs #4040
Release note _(write NONE if no user-facing change)_:
NONEREADME.md:115, README.md:109 awaiting @pandacooming's response.What type of PR is this?
/kind feature
What this PR does / why we need it:
The standalone chart can't deploy the coordinator today. A coordinator deployment has to hand-write the coordinator manifests and a second Envoy config next to the chart. This PR adds both to the chart. Both options default to off, so default renders are unchanged.
Depends on #4813 (router.proxy.extraRoutes). This branch is stacked on it, so the diff includes its commit until #4813 merges. Only the last commit is new here.
router.coordinator.enabled deploys the coordinator (cmd/coordinator) next to the service-mode Envoy proxy:router.coordinator.config, and a headless Service, plus an optional PodDisruptionBudget.http (8081) is for clients. Every request goes to the coordinator, without EPP. extraRoutes stay on this listener, minus their ext_proc settings.gateway (gatewayPort, 8082) handles the coordinator's legs with ext_proc.x-llm-d-epp-profile header matches a profileRouters entry goes to that entry's EPP through an ExtProcPerRoute grpc_service override. Every other leg goes to the release's own EPP.gateway port, and the coordinator's gateway.address defaults to it.server.listen_addr, metrics_port and secure_serving from values.failOpen is true (a leg that skips EPP would lose its scheduling profile), or if a port collides.router.epp.discoveryService.enabled renders the <release>-epp-discovery headless Service, and turns on EPP's gRPC health service, for a release with no proxy of its own. That release (for example a decode EPP) can then be a coordinator release's profile router.The layout this enables is two releases over one pool: a prefill release with the proxy and the coordinator, and a decode release with only an EPP. It's the same topology as a production P/D deployment we run today with hand-written manifests. The README documents both options with an example.
Tests:
hack/verify-helm.sh: coordinator and coordinator-profile-router. I rendered both and ran their checks locally. I didn't run the full script.extProcPort, and gateway with an InferencePool.envoy --mode validate (v1.40.2) passes on the coordinator Envoy config in two variants: plain coordinator, and TLS coordinator with tracing and a custom extProcPort.Which issue(s) this PR fixes:
None.
Release note _(write NONE if no user-facing change)_:
Helm: the standalone chart can deploy the coordinator (`router.coordinator.*`), with an Envoy gateway listener that routes each leg to the EPP of its scheduling profile (`router.coordinator.profileRouters`), and `router.epp.discoveryService.enabled` exposes a proxy-less EPP release as a profile router.
๐ค Generated with Claude Code
Add an opt-in adaptive render concurrency limit to token-producer) is new here.What type of PR is this?
/kind feature
What this PR does / why we need it:
Implements #4063. Stacked on #3885: the first two commits belong to #3885, and only the last commit (Add an opt-in adaptive render concurrency limit to token-producer) is new here. I will rebase once #3885 merges.
The render circuit breaker in #3885 bounds the latency of a renderer that is down or hung. Under sustained overload it cycles: while the circuit is open, the render endpoint drains, the probe succeeds, and full traffic returns until the next trip. In a model of the #2025 setup (one render replica, about 10 req/s capacity, Poisson arrivals), 23% of requests at 20 req/s still wait the full 5s budget with the breaker, and 32% wait the full 30s budget on Chat. The numbers are in https://github.com/llm-d/llm-d-router/pull/3885#issuecomment-6702298245.
vllm.concurrencyLimit caps in-flight render calls per render path, so the render endpoint stays busy at its capacity and calls over the cap skip rendering immediately instead of queueing behind it.
precise-prefix-cache-producer, which matches the fallback rule in #3980.targetLatency, scales the cap down by 10% (to minLimit). A call that succeeds within the target while at least half the cap is in use raises it by 1/limit, about one per cap's worth of calls (to maxLimit). Fast failures and cancellations do not change it. The half-in-use check keeps the cap from drifting far above what the renderer has been shown to sustain while traffic is light.vllm:
concurrencyLimit:
initialLimit: 20 # default
minLimit: 1 # default
maxLimit: 1000 # default
targetLatency: 1s # default: a quarter of the render path's budget
minLimit on multimodal requests whose render alone takes longer than the target, skipping most of them on an idle renderer. Text-only deployments can set a lower targetLatency.| 20 req/s offered | Rendered | Full-budget waits | Mean render latency of rendered requests |
|---|---|---|---|
| 5s budget, target 1.25s (default) | 50% | 0% | 0.93s |
| 30s budget, target 7.5s (default) | 50% | 0% | 5.0s |
| 30s budget, target 3s | 50% | 0% | 2.0s |
token-producer calling the render endpoint. They are independent; if the Coordinator gains a limiter, the same AIMD rule could be shared.| Metric | Type | Labels |
|---|---|---|
llm_d_epp_token_producer_render_concurrency_limit | Gauge | plugin_type, plugin_name, path |
llm_d_epp_token_producer_render_skipped_total | Counter | plugin_type, plugin_name, path, reason (new label: circuit_open, concurrency_limit) |
The tokenize span records skipped_concurrency_limit for a skipped request. docs/metrics.md and the tokenizer README describe the limit.
Test plan:
targetLatency, and invalid values rejected at startup.minLimit and maxLimit.make presubmit and -race were not run locally (no container runtime or cgo toolchain on this machine); the package tests and golangci-lint v2.14.0 pass locally.
Which issue(s) this PR fixes:
Fixes #4063
Part of #2025
Release note _(write NONE if no user-facing change)_:
token-producer: add an opt-in, Alpha adaptive render concurrency limit (`vllm.concurrencyLimit`). Render calls over a limit that adapts to render latency skip rendering and route without token IDs instead of queueing at an overloaded render endpoint. `token_producer_render_skipped_total` gains a `reason` label.What type of PR is this?
/kind bug
What this PR does / why we need it:
vLLM and SGLang report a failure that happens after a streamed response has started as an SSE error event inside the HTTP 200 response. The EPP classified requests by response status only. As a result, these failures were counted as completed, endpoint-health-filter counted them as successes, and the approximate prefix cache kept the entries the failed request added.
With this change the failure is counted the way the same failure is counted without streaming:
ParsedResponse.ErrorStatus field. The OpenAI envelope's numeric code is used when it is a 4xx or 5xx status. An Anthropic error type maps to its status, and any other error event maps to 500. The frame check and status mapping move from the coordinator's force-stream step to pkg/common/request, so both use the same code.outcome="failed", and llm_d_epp_request_error_total is incremented with the same error_code as for a non-streamed failure: ModelServerError for 5xx, ModelServerClientError for 4xx. TerminationCause stays natural, as for a non-streamed error response.:status. This follows the approach used for gRPC, where the trailer status is written onto the end-of-stream headers. The client still receives the original 200 response. Plugins that classify a request by :status see the failure without changes: the approximate prefix cache removes the request's entries, and precise-prefix-cache releases its speculative entries.endpoint-health-filter counts event-stream responses at the end of the stream, as it does for gRPC. Counting the 200 headers as a success would reset the endpoint's failure run between two failures that only the stream reports.Out of scope: vLLM's /v1/responses stream sends no error event when generation fails (vllm-project/vllm#65213), and the SGLang /generate parser does not look for error events.
Which issue(s) this PR fixes:
Fixes #4897
Testing
none-prefilled is charged to the decode endpoint.make presubmit and go test -race for the affected packages.scripts/kind-dev-env.sh, DISAGG_P=true, Istio 1.29.2). The prefill is the inference sim. The decode pod runs the sidecar in front of real vLLM (CPU nightly 0.34.0rc1.dev398) with a test KV connector that fails the KV load for long prompts. EPP images are built from main a95c594d7 (base) and from this branch (fix).| Requests | Base | Fix |
|---|---|---|
3 streamed chat, 200 + data: {"error":...} | completed x3, no error count | failed/ModelServerError x3, error count +3 |
| 3 non-streamed chat, 500 | failed/ModelServerError x3 | same |
| 3 streamed short chat (decode only), success | completed x3 | completed x3 |
1 streamed /v1/completions, error event | completed | failed/ModelServerError |
1 streamed /v1/messages, event: error | completed | failed/ModelServerError |
8 streamed requests with a second decode endpoint (sim); endpoint-health-filter with responseFailureCodes: [500] and threshold 3 | 0 ejections, vLLM stays in rotation | 1 ejection after the third vLLM failure, all later requests go to the sim |
| Retry of a prompt whose streamed request failed on vLLM (2 runs) | decode-only, back to vLLM, fails again | prefill-decode, served by the other decode endpoint |
0.35.0rc1.dev141, nixl 1.5.2, Qwen3-0.6B). Prefill runs on one GPU and decode on the other, behind Envoy, the EPP and the sidecar. When the prefill engine is killed after it answers, the decode engine's KV transfer fails (nixl_num_failed_transfers_total +1, finished_reason="error"), and vLLM streams data: {"error":...code 500}.| Requests | Base | Fix |
|---|---|---|
| 3 streamed chat, failed KV transfer | completed x3, no error count, no ejection | failed/ModelServerError x3; decode endpoint ejected after the third (reason="response") |
1 streamed /v1/messages, event: error | completed | failed/ModelServerError |
| 1 non-streamed chat, 500 | failed/ModelServerError | same |
| Retry of the last failed streamed prompt | decode-only (prefix cache kept the failed request's entries) | prefill-decode with a real NIXL transfer |
| Short and long streamed chat, success | completed | completed |
| "Removed prefix index entries for failed request" log lines | 1 (non-streamed only) | 5 |
Release note _(write NONE if no user-facing change)_:
The EPP counts a streamed response that ends with the model server's error event (for example a failed KV load in vLLM) as a failed request: `llm_d_epp_request_outcome_total{outcome="failed"}` and `llm_d_epp_request_error_total` are recorded as for the same failure without streaming. `endpoint-health-filter` counts these failures toward ejection, and the approximate prefix cache no longer keeps the prefix of such a request.make verify-review-playbook fails on main, so make presubmit fails on every branch (Fixes #4890).What type of PR is this?
/kind bug
What this PR does / why we need it:
make verify-review-playbook fails on main, so make presubmit fails on every branch. Two production packages match no row in the routing table of docs/review/playbooks/review_a_pull_request.md:
pkg/epp/framework/common/duration/** (#4375) is routed to None (AGENTS.md and repo search only). It is a self-contained seconds-to-duration validation helper, like pkg/common/clamp/** in the same row.pkg/epp/framework/plugins/requesthandling/forwardtokens/** (#3706) is routed to the engine wire contract row, with parsers/** and dataproducer/**. The plugin writes kv_transfer_params.prompt_token_ids into the request sent to vLLM.docs/review/log.md gets a dated entry, as maintain_review_bundle.md requires for routing changes. The routing table is not compiled into docs/review_playbook.md, so that file is unchanged.
Test plan:
python3 hack/render_playbook.py --check passes on this branch rebased onto the current main, and fails on main with the two "unrouted production Go file" errors.Which issue(s) this PR fixes:
Fixes #4890
Release note _(write NONE if no user-facing change)_:
NONE