Repository navigation
[Bug] Admit the PD decode pod before the prefill leg is sent - #3127
Conversation
With pd routing and a profile that sets requestsInflight, the per-replica cap was checked by enforceReplicaInflight after Route returned, and PD's Route sends the prefill leg before returning. For vLLM that is the whole prefill. Every request arriving during one prefill saw the same count, passed the pre-filter for the same decode pod and ran its own prefill; all but one were then rejected with 429, leaving the prefill work and its KV behind (SGLang's async leg also kept the prefill tracker raised until its bootstrap timeout). The routing context now carries an optional target admitter. For a PD request with a cap, selectTargetPod installs the gateway's atomic admission there, and the PD router admits its decode pod right after Select, before any prefill. A full pod fails Route with ErrTargetReplicaInflightExceeded, which maps to the same 429, after releasing what Select registered. enforceReplicaInflight skips a request that was already admitted. A counted admission whose Route then fails never reaches AddRequestCount, so the gateway releases it through the new Cache.ReleasePodRunningRequest. Other strategies are unchanged: they do no work before returning a target, so the post-routing check still covers them. Signed-off-by: Aarnav Noble <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces early admission for target pods (specifically for the PD router) before the prefill leg is sent, preventing wasted prefill work and orphaned KV caches when the target decode pod is already at its in-flight limit. It adds a ReleasePodRunningRequest method to the MetricCache interface to clean up counted admissions on route failures, and updates the gateway routing logic and tests accordingly. The review feedback highlights two important improvements: adding a defensive nil check for the pod parameter in admitReplicaInflight to prevent potential nil pointer dereferences, and releasing any previously admitted pod within SetTargetAdmitter if it is called multiple times to avoid resource leaks.
| func (s *Server) admitReplicaInflight(routingCtx *types.RoutingContext, pod *v1.Pod, limit int64) bool { | ||
| admitted, counted, err := s.cache.AdmitPodRunningRequest(pod.Name, pod.Namespace, limit) |
There was a problem hiding this comment.
To prevent potential nil pointer dereference panics if a router calls AdmitTarget with a nil pod, we should add a defensive nil check for pod at the beginning of admitReplicaInflight.
| func (s *Server) admitReplicaInflight(routingCtx *types.RoutingContext, pod *v1.Pod, limit int64) bool { | |
| admitted, counted, err := s.cache.AdmitPodRunningRequest(pod.Name, pod.Namespace, limit) | |
| func (s *Server) admitReplicaInflight(routingCtx *types.RoutingContext, pod *v1.Pod, limit int64) bool { | |
| if pod == nil { | |
| return false | |
| } | |
| admitted, counted, err := s.cache.AdmitPodRunningRequest(pod.Name, pod.Namespace, limit) |
There was a problem hiding this comment.
I don't think this one is needed. The only caller is pdRouter.Route, which calls AdmitTarget with the decode pod straight after Select returns without an error. That code already dereferences decodePod (the HeaderPrefillTargetPod and SetDecodeTarget lines) and passes it to SetTargetPod, so a nil pod there would already be a bug in Select. enforceReplicaInflight also checks TargetPod() == nil before calling this helper. I've left it as is.
| var admittedPod *v1.Pod | ||
| routeCtx.SetTargetAdmitter(func(pod *v1.Pod) error { | ||
| routeCtx.ReplicaInflightChecked = true | ||
| if !s.admitReplicaInflight(routeCtx, pod, limit) { | ||
| return types.ErrTargetReplicaInflightExceeded | ||
| } | ||
| admittedPod = pod | ||
| return nil | ||
| }) |
There was a problem hiding this comment.
If AdmitTarget is called multiple times during a single routing decision (e.g., due to retries or multi-target routing), the previously admitted pod's reservation would be overwritten and leaked. To prevent this, we should release any previously admitted pod before admitting a new one.
var admittedPod *v1.Pod
routeCtx.SetTargetAdmitter(func(pod *v1.Pod) error {
routeCtx.ReplicaInflightChecked = true
if admittedPod != nil && routeCtx.ReplicaInflightAdmitted {
s.cache.ReleasePodRunningRequest(admittedPod.Name, admittedPod.Namespace)
routeCtx.ReplicaInflightAdmitted = false
}
if !s.admitReplicaInflight(routeCtx, pod, limit) {
return types.ErrTargetReplicaInflightExceeded
}
admittedPod = pod
return nil
})There was a problem hiding this comment.
Good point. PD admits once, but the admitter is installed on the routing context, so nothing stopped a router from admitting twice and leaking the first counted slot. Fixed in 4a47dce: the admitter now releases the previous counted admission before admitting the next target, and the error path uses the same release. TestRouteWithEarlyAdmission_ReadmitReleasesPrevious covers it, both when the second target is admitted and when it is full, and fails without the release.
PD admits its target once, but the admitter is installed on the routing context, and a router that admitted a second target would leave the first one's slot counted with nothing to release it. Release it before admitting the next target. Signed-off-by: Aarnav Noble <[email protected]>
varungup90
left a comment
There was a problem hiding this comment.
Review: admit the PD decode pod before the prefill leg is sent
Verdict: approve with nits (my recommendation only; I have not submitted a formal approval). The design is sound and the central test reproduces the reported race. The two nits are test gaps I found by mutation; neither is a defect I could demonstrate in the code.
What I checked on 4a47dce
- The bug and the fix. Before,
enforceReplicaInflightadmitted the target afterRoutereturned, but PD'sRoutesends the prefill before returning, so every request arriving during one prefill saw the same count, passed the pre-filter for the same decode pod, ran its own prefill, and was then rejected. Admitting the decode pod insideRoute, right afterSelectand beforedoPrefillRequest, closes it. EverythingSelectregistered (prefill tracker, token load) is released on rejection, and the pending-decode removal is adeferregistered before the admit call. - No double decrement. The completion decrement runs in
donePodStats, which is gated onCanDoneStats(the stats flag must be in the "added" state, whichAddRequestCount/addPodStatssets). A request whoseRoutefailed never gets there, so the release inrouteWithEarlyAdmissionis the only decrement for it. After a successfulRoutethe request continues toAddRequestCountas before, and the code betweenselectTargetPodandAddRequestCounthas no other failure exit, so the window for a leaked counted slot is just a failingRoute, which is handled. - Safe defaults.
ReplicaInflightCheckedis set only when the admitter actually runs, so a router that never callsAdmitTargetstill gets the post-routing check.Releasepasses(podNamespace, podName)todecrPodRunningRequestsin the right order (the Redis test would fail on a swap, and I confirmed that). Other strategies and PD requests without a cap are untouched. - Gemini's threads. The nil-pod check is not needed, as the author says (the only caller dereferences
decodePodalready). The re-admit leak was real and is fixed in4a47dce.
What I ran (scratch worktree at the PR head, Linux, Go 1.24.7)
gofmt -l,go veton the touched packages: clean.go test -race -count=1 ./pkg/plugins/gateway/... ./pkg/types/... ./pkg/cache/: pass.- Mutation: sixteen mutants. Thirteen were caught, including: no
AdmitTargetcall, the call placed after the prefill, leaving the prefill tracker or token load registered on rejection, losingerrors.Isthrough%v, no release on a failedRoute, no release on re-admit, ignoring or never setting the "already checked" flag,selectTargetPodnot using early admission, the 429 mapping removed, and swapped arguments in the release. Three survived (inline comments):- the release ignoring whether the admission was counted (the "not counted" subtest cannot fail);
- the context reset not clearing
ReplicaInflightChecked; - the context reset not clearing the admitter.
- CI on the head: Go Unit, Race, Integration, Lint, Coverage and Verify Generated Code are green, and so are the image builds and DCO.
Installation E2E Testswas still queued and both Installation Smoke jobs were in progress when I looked.
Not run
- The integration suite (
test/integration/gateway), the e2e suites, and a real PD deployment with Redis. The "slot held during prefill" behaviour is covered by the miniredis test, not by a live run.
Nits (optional)
- Vacuous assertion (inline on
gateway_test_helpers.go:164): the "uncounted admission is left alone" check cannot fail, because the mock records no call without an expectation. - Pooled-context reset untested (inline on
router_context.go:580): a stale flag or admitter would bypass or misapply the cap for a later request. I included a throw-away test in the comment that passes now and fails if either reset is removed.
FYI (the author already documents these)
- Without Redis (standalone mode) the admission holds no slot during the prefill, so the original race remains there; the description says so.
- A request rejected early still leaves the prefix-index update that
Selectenqueued, as a failed prefill does today.
Generated by Claude Code
| // ReleasePodRunningRequest is a no-op without an expectation, like AdmitPodRunningRequest. | ||
| func (m *MockCache) ReleasePodRunningRequest(podName string, podNamespace string) { | ||
| if !m.hasExpectation("ReleasePodRunningRequest") { | ||
| return |
There was a problem hiding this comment.
Test gap: because this method returns before m.Called when no expectation is set, the call is never recorded, so mockCache.AssertNotCalled(t, "ReleasePodRunningRequest", ...) in TestRouteWithEarlyAdmission_ReleasesWhenRouteFails (the "not counted" subtest, replica_inflight_test.go:387) can never fail.
I confirmed it with a mutation: changing release() in routeWithEarlyAdmission to if admittedPod != nil { (so that it releases even when the admission was not counted, which would decrement a slot that was never taken) leaves every test green. That is the one behaviour of the release logic that the author's description says is tested ("leaves an uncounted one alone").
A small fix is to make the no-expectation path record the call without failing, for example m.Called(...) guarded by .Maybe() expectations, or a tiny counting fake for this method. Then the "not counted" subtest would fail on that mutant.
Generated by Claude Code
There was a problem hiding this comment.
Thanks, fixed in 3e054d8. The "not counted" subtest now sets an optional (.Maybe()) expectation for ReleasePodRunningRequest, so the mock records the call and AssertNotCalled can fail. With your mutant (if admittedPod != nil {) the not_counted subtest now fails. I kept the mock's default unchanged so other tests aren't affected.
| clear(r.trustedPolicyAttributes) | ||
| r.ReplicaInflightAdmitted = false | ||
| r.ReplicaInflightChecked = false | ||
| r.targetAdmitter = nil |
There was a problem hiding this comment.
Nit (test gap): these two resets are what stops one request's early-admission state from leaking into the next request that reuses the pooled RoutingContext, and nothing tests them. Removing r.ReplicaInflightChecked = false, or removing r.targetAdmitter = nil, each left all of ./pkg/plugins/gateway/..., ./pkg/types/... and ./pkg/cache/ green.
The stakes are real. A stale ReplicaInflightChecked = true makes enforceReplicaInflight skip the cap for a later request, and a stale admitter would run the previous request's closure (with its old limit) on a later PD request.
A throw-away test in pkg/types shows it: create a context, SetTargetAdmitter(...), set both flags, Delete(), then call NewRoutingContext until the pool hands back the same pointer, and assert that AdmitTarget returns nil without calling the old closure and that both flags are false. It passes on this head, and it fails with either reset removed. If you add it, skip it when sync.Pool doesn't return the same object, since pool reuse isn't guaranteed.
Generated by Claude Code
There was a problem hiding this comment.
Added in 3e054d8 as TestRoutingContextResetClearsEarlyAdmission (pkg/types/admit_target_test.go). To avoid depending on sync.Pool reuse, it calls reset() directly from inside the package: it installs an admitter, sets both flags, resets, then asserts that both flags are false and that AdmitTarget returns nil without running the old closure. It fails with either r.ReplicaInflightChecked = false or r.targetAdmitter = nil removed.
The "not counted" subtest could not fail: without an expectation the mock returns before recording the call. And nothing covered reset() clearing the early-admission state, which would let a pooled context skip the cap or run a previous request's admitter. Signed-off-by: Aarnav Noble <[email protected]>
varungup90
left a comment
There was a problem hiding this comment.
Follow-up review of 3e054d8
Verdict: approve (my recommendation only; I have not submitted a formal approval). The new commit closes both test gaps from my review, and I checked that each now fails when the behaviour it pins is removed. CI on this head is green.
What changed since 4a47dce
One commit, tests only:
replica_inflight_test.go: the "not counted" subtest ofTestRouteWithEarlyAdmission_ReleasesWhenRouteFailsnow registers a.Maybe()expectation forReleasePodRunningRequest, so the mock records the call andAssertNotCalledcan actually fail. This was the vacuous assertion I flagged.pkg/types/admit_target_test.go:TestRoutingContextResetClearsEarlyAdmissioncallsresetdirectly (so it does not depend onsync.Poolhanding back the same object), installs an admitter and both flags, resets, and asserts both flags are false, the new request admits normally, and the old admitter never runs.
What I ran (scratch worktree at the new head, Linux)
gofmt -l,go vet: clean.go test -race -count=1on./pkg/types/,./pkg/plugins/gateway/,./pkg/plugins/gateway/algorithms/pd/router/and./pkg/cache/: pass.- Mutation, the three that survived before are now caught:
- releasing even when the admission was not counted fails
TestRouteWithEarlyAdmission_ReleasesWhenRouteFails; resetnot clearingReplicaInflightChecked, andresetnot clearing the admitter, each failTestRoutingContextResetClearsEarlyAdmission. I also checked a fourth variant (resetnot clearingReplicaInflightAdmitted), and it is caught too.
- releasing even when the admission was not counted fails
- CI on the head: all the check runs are done and green (Go Unit, Race, Integration, Lint, Coverage, Verify Generated Code, Installation E2E, both Installation Smoke jobs, the image builds, DCO), with
buildskipped.
Generated by Claude Code
Code reviewVerdict: Approve — fix is correct and well tested; CI green on tip; remaining items are optional nits, not merge blockers. Scope
Correctness
Tests & local checks
CI at review timeManagePullRequest Nits (non-blocking)
Code: Approve. Merge recommendation: Approve. |
Design simplification reviewVerdict: Approve — option A from #3112 at the right layer; no extra abstraction beyond what PD needs. IntentWith What works well
Simpler alternatives considered
Non-blocking notes
Design: Approve. |
Pull Request Description
This implements option A from #3112: a PD request admits its decode pod against the
requestsInflightcap before the prefill leg is sent, instead of afterRoutereturns.The bug (details in #3112)
enforceReplicaInflightran the atomic admission afterRoutereturned, and PD'sRoutesends the prefill leg before returning. For vLLM that wait is the whole prefill.filterSaturatedReplicaInflightfor the same decode pod, and runs its own prefill. All but one are then rejected with 429.Change
RoutingContextgets an optional target admitter (SetTargetAdmitter/AdmitTarget), plusReplicaInflightChecked. Both are cleared on reset.gateway_inflight.go).selectTargetPodroutes throughrouteWithEarlyAdmission. That installs the same atomic admissionenforceReplicaInflightuses, now factored out asadmitReplicaInflight.enforceReplicaInflightskips a request that was already admitted.ErrTargetReplicaInflightExceededmaps to the existing 429 (replica_inflight_exceeded).Routecallsctx.AdmitTarget(decodePod)right afterSelect. If the pod is full, it releases whatSelectregistered (prefill tracker and token load) and returns before any prefill.Routethen fails (the prefill failed), the request never reachesAddRequestCount, so the completion decrement won't run. The gateway releases it through a newCache.ReleasePodRunningRequest, which is the decrement request tracking would have applied.Tests
pd/router/admit_target_test.go): a cap of one on the decode pod, and a second request arriving while the first request's prefill is held open.ErrTargetReplicaInflightExceededwith its tracker and token load released.AdmitTargetcall: two prefill calls, and the second request is not rejected.replica_inflight_test.go):Routereleases a counted admission and leaves an uncounted one alone;selectTargetPodinstalls the admitter for PD.go test -race ./pkg/plugins/gateway/... ./pkg/cache/... ./pkg/types/...passes.go test ./test/integration/gateway/...passes.go vetpasses, andmake lintreports 0 issues.Notes
ReleasePodRunningRequestis a newMetricCachemethod. The test fakes get no-op implementations.Selectenqueues a prefix-index update for the prefill pod. A request rejected early leaves that update, as a prefill failure does onmaintoday. I left it alone; moving the update after the prefill seemed out of scope.AddRequestCount. That keeps the current behaviour there; Redis is required in Kubernetes mode.Related Issues
Resolves: #3112