Skip to content

[Bug] Admit the PD decode pod before the prefill leg is sent - #3127

Merged
varungup90 merged 3 commits into
vllm-project:mainfrom
AarnavNoble:bugfix/pd-admit-before-prefill
Oct 17, 2026
Merged

varungup90 merged 3 commits into
vllm-project:mainfrom
AarnavNoble:bugfix/pd-admit-before-prefill

Conversation

@AarnavNoble

Copy link
Copy Markdown
Contributor

Pull Request Description

This implements option A from #3112: a PD request admits its decode pod against the requestsInflight cap before the prefill leg is sent, instead of after Route returns.

The bug (details in #3112)

  • enforceReplicaInflight ran the atomic admission after Route returned, and PD's Route sends the prefill leg before returning. For vLLM that wait is the whole prefill.
  • Every request that arrives during one prefill sees the same count, passes filterSaturatedReplicaInflight for the same decode pod, and runs its own prefill. All but one are then rejected with 429.
  • The rejected requests leave their prefill work and KV behind. For SGLang, the async leg also keeps the prefill pod's tracker count raised until the bootstrap timeout.

Change

  • Routing context. RoutingContext gets an optional target admitter (SetTargetAdmitter / AdmitTarget), plus ReplicaInflightChecked. Both are cleared on reset.
  • Gateway (gateway_inflight.go).
    • For a PD request whose profile sets a cap, selectTargetPod routes through routeWithEarlyAdmission. That installs the same atomic admission enforceReplicaInflight uses, now factored out as admitReplicaInflight.
    • enforceReplicaInflight skips a request that was already admitted.
    • ErrTargetReplicaInflightExceeded maps to the existing 429 (replica_inflight_exceeded).
  • PD router. Route calls ctx.AdmitTarget(decodePod) right after Select. If the pod is full, it releases what Select registered (prefill tracker and token load) and returns before any prefill.
  • Releasing a counted admission. If the admission was counted and Route then fails (the prefill failed), the request never reaches AddRequestCount, so the completion decrement won't run. The gateway releases it through a new Cache.ReleasePodRunningRequest, which is the decrement request tracking would have applied.
  • Unchanged.
    • Other strategies do no work before returning a target, so the post-routing check still covers them.
    • PD requests without a cap are untouched.

Tests

  • The reproduction from the issue (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.
    • With this change: one prefill call, and the second request gets ErrTargetReplicaInflightExceeded with its tracker and token load released.
    • Without the AdmitTarget call: two prefill calls, and the second request is not rejected.
  • Ordering: the decode pod is admitted once, before the prefill is sent.
  • Gateway tests (replica_inflight_test.go):
    • admission happens only once;
    • a full target produces the 429;
    • a failed Route releases a counted admission and leaves an uncounted one alone;
    • against miniredis, the hash field is back at 0 after a failed prefill;
    • selectTargetPod installs the admitter for PD.
  • Mutation checks. Each of these was caught by at least one test:
    • removing the release;
    • removing the "already checked" skip;
    • removing the 429 mapping;
    • not installing the admitter.
  • Checks run:
    • go test -race ./pkg/plugins/gateway/... ./pkg/cache/... ./pkg/types/... passes.
    • go test ./test/integration/gateway/... passes.
    • go vet passes, and make lint reports 0 issues.

Notes

  • Interface change. ReleasePodRunningRequest is a new MetricCache method. The test fakes get no-op implementations.
  • Prefix index. Select enqueues a prefix-index update for the prefill pod. A request rejected early leaves that update, as a prefill failure does on main today. I left it alone; moving the update after the prefill seemed out of scope.
  • Without Redis. In standalone mode admission falls back to the local count, which request tracking increments only at AddRequestCount. That keeps the current behaviour there; Redis is required in Kubernetes mode.

Related Issues

Resolves: #3112

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]>

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

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.

Comment on lines +84 to 85
func (s *Server) admitReplicaInflight(routingCtx *types.RoutingContext, pod *v1.Pod, limit int64) bool {
admitted, counted, err := s.cache.AdmitPodRunningRequest(pod.Name, pod.Namespace, limit)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

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.

Suggested change
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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment on lines +108 to +116
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
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

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
	})

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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]>
@github-actions github-actions Bot added area/gateway area/testing Issues or PRs related to testing labels Oct 16, 2026

@varungup90 varungup90 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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, enforceReplicaInflight admitted the target after Route returned, but PD's Route sends 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 inside Route, right after Select and before doPrefillRequest, closes it. Everything Select registered (prefill tracker, token load) is released on rejection, and the pending-decode removal is a defer registered before the admit call.
  • No double decrement. The completion decrement runs in donePodStats, which is gated on CanDoneStats (the stats flag must be in the "added" state, which AddRequestCount/addPodStats sets). A request whose Route failed never gets there, so the release in routeWithEarlyAdmission is the only decrement for it. After a successful Route the request continues to AddRequestCount as before, and the code between selectTargetPod and AddRequestCount has no other failure exit, so the window for a leaked counted slot is just a failing Route, which is handled.
  • Safe defaults. ReplicaInflightChecked is set only when the admitter actually runs, so a router that never calls AdmitTarget still gets the post-routing check. Release passes (podNamespace, podName) to decrPodRunningRequests in 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 decodePod already). The re-admit leak was real and is fixed in 4a47dce.

What I ran (scratch worktree at the PR head, Linux, Go 1.24.7)

  • gofmt -l, go vet on 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 AdmitTarget call, the call placed after the prefill, leaving the prefill tracker or token load registered on rejection, losing errors.Is through %v, no release on a failed Route, no release on re-admit, ignoring or never setting the "already checked" flag, selectTargetPod not 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 Tests was 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)

  1. 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.
  2. 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 Select enqueued, 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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 varungup90 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 of TestRouteWithEarlyAdmission_ReleasesWhenRouteFails now registers a .Maybe() expectation for ReleasePodRunningRequest, so the mock records the call and AssertNotCalled can actually fail. This was the vacuous assertion I flagged.
  • pkg/types/admit_target_test.go: TestRoutingContextResetClearsEarlyAdmission calls reset directly (so it does not depend on sync.Pool handing 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=1 on ./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;
    • reset not clearing ReplicaInflightChecked, and reset not clearing the admitter, each fail TestRoutingContextResetClearsEarlyAdmission. I also checked a fourth variant (reset not clearing ReplicaInflightAdmitted), and it is caught too.
  • 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 build skipped.

Generated by Claude Code

@cursor

cursor Bot commented Oct 16, 2026

Copy link
Copy Markdown

Code review

Verdict: Approve — fix is correct and well tested; CI green on tip; remaining items are optional nits, not merge blockers.

Scope

  • Head: 3e054d894e8bf69cae44e4c8fa2ce6e93d814162
  • Resolves: [Bug] PD routing runs the prefill before the requestsInflight cap is checked #3112 (option A)
  • Core: gateway_inflight.go early admission + release, PD AdmitTarget before prefill, ReleasePodRunningRequest on MetricCache, ErrTargetReplicaInflightExceeded → same 429, pool reset clears early-admission state
  • Tests: PD race reproduction + ordering; gateway admit-once / 429 / release / re-admit / Redis restore / selectTargetPod install; pooled-context reset
  • Prior: gemini-code-assist (nil check; re-admit release — addressed by releasing inside the admitter); @varungup90 (approve after tip pinned uncounted-release + reset tests)

Correctness

  1. Race is closed. TestPDRouter_FullDecodePodRejectsBeforePrefill holds the first prefill open under a cap of one; the second request gets ErrTargetReplicaInflightExceeded with a single prefill call and released tracker/token load. Ordering test pins admit-before-prefill for the success path.
  2. No double admit. Early path sets ReplicaInflightChecked; enforceReplicaInflight returns immediately afterward. TestRouteWithEarlyAdmission_AdmitsOnce and Test_selectTargetPod_PDAdmitsTargetInsideRoute pin that.
  3. Slot lifecycle. Counted admission + failed Route → ReleasePodRunningRequest (mock + miniredis restore to 0). Uncounted admission is not released (.Maybe() expectation so AssertNotCalled can fail). Re-admit releases the previous pod whether the second admit succeeds or is full.
  4. Error surface. Wrapped ErrTargetReplicaInflightExceeded maps in buildTargetSelectionErrorResponse to the existing 429 / replica_inflight_exceeded body — same client contract as the post-routing check.
  5. Pool safety. reset clears ReplicaInflightChecked, ReplicaInflightAdmitted, and targetAdmitter; TestRoutingContextResetClearsEarlyAdmission fails if any of those stick across reuse.
  6. PD cleanup on reject. Prefill tracker + token load released; pendingDecodeTracker still cleared by the existing defer. Decode pod comes from a successful Select, so a nil-pod panic on admit is not a realistic production path.

Tests & local checks

  • Local on tip: go test -race -count=1 ./pkg/types/ ./pkg/plugins/gateway/ ./pkg/plugins/gateway/algorithms/pd/router/ ./pkg/cache/ — pass.

CI at review time

ManagePullRequest get_ci_status: SUCCESS — 24 successful, 0 failed, 0 pending, 1 skipped (Docker Build Images / build). Required checks: 0 failed / 0 pending. Includes Go Lint / Unit / Race / Integration / Coverage / Verify, Installation Smoke (Kustomize + Helm), Installation E2E, DCO, RTD, triage.

Nits (non-blocking)

  1. Optional defensive nil guard in admitReplicaInflight before pod.Name (gemini) — belt-and-suspenders; PD only admits after Select succeeds.
  2. routeWithEarlyAdmission releases on err != nil but not on panic; a defer with a named return would be slightly safer. Not a practical merge concern for this path.
  3. Follow-ups already called out in the PR/issue: try next decode candidate instead of hard 429; prefix-index update timing on early reject.

Code: Approve. Merge recommendation: Approve.

@cursor

cursor Bot commented Oct 16, 2026

Copy link
Copy Markdown

Design simplification review

Verdict: Approve — option A from #3112 at the right layer; no extra abstraction beyond what PD needs.

Intent

With pd + requestsInflight, the hard cap ran in enforceReplicaInflight after Route returned, but PD sends the prefill leg inside Route. Every request that arrived during one prefill saw the same decode count, ran its own prefill, then got 429 — wasting work and leaving KV for a decode that never comes. Admit the decode pod before prefill starts.

What works well

  1. Hook on the routing context, not a PD↔cache shortcut. SetTargetAdmitter / AdmitTarget lets the gateway keep owning Redis admission while PD calls it right after Select. Other strategies stay on the post-routing check; uncapped PD is untouched. That matches “routers that start work before returning a target” without redesigning Route.
  2. One atomic admit path. admitReplicaInflight is shared by early admission and enforceReplicaInflight; the latter skips when ReplicaInflightChecked is set. No second counters or parallel semantics.
  3. Release ownership is explicit. Counted admissions that never reach AddRequestCount are released via Cache.ReleasePodRunningRequest when Route fails; re-admit releases the previous slot before the next attempt. That is the failure mode this change introduces, and it is handled next to the admitter rather than buried in PD.
  4. Scope stays on the race. Trying the next decode candidate, moving the prefix-index update, and changing standalone (no-Redis) behaviour are correctly called out as out of scope / pre-existing.

Simpler alternatives considered

  • B (undo prefill on reject): smaller gateway change, but vLLM still pays the full prefill; does not meet the issue’s expected behaviour.
  • C (treat combo unsupported): drops the cap for the deployments that need it most.
  • Give PD a cache/limit dependency: couples the router to Redis admission details and duplicates gateway policy.
  • Move prefill out of Route: larger redesign; this PR does not need it.

Non-blocking notes

  • Early reject still leaves a prefix-index update queued by Select (same as a prefill failure on main today) — fine to leave, just worth remembering if cleanup is ever unified.
  • Standalone mode still cannot hold a Redis slot during prefill; Kubernetes mode (Redis required) is the path this fixes.

Design: Approve.

@varungup90
varungup90 merged commit 065e50f into vllm-project:main Oct 17, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/gateway area/testing Issues or PRs related to testing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] PD routing runs the prefill before the requestsInflight cap is checked

2 participants