Skip to content

[Fix] Prevent zombie requests after client disconnect: abort pending requests before dropping tokenizer state - #35936

Closed
gencer-altan wants to merge 2 commits into
sgl-project:mainfrom
gencer-altan:fix/disconnect-zombie-abort-race
Closed

gencer-altan wants to merge 2 commits into
sgl-project:mainfrom
gencer-altan:fix/disconnect-zombie-abort-race

Conversation

@gencer-altan

@gencer-altan gencer-altan commented Aug 22, 2026 •

Copy link
Copy Markdown

Problem

Streaming clients that disconnect mid-generation (Esc in an agent UI, network drop, proxy timeout) leave orphaned requests decoding on the scheduler until the request reaches its configured generation limit, while TokenizerManager spams thousands of:

Received output for rid='...' but the state was deleted in TokenizerManager.

Observed on an AMD MI300X deployment (ROCm) and reproduced on main @ 5a46d65 (2026-08-21); independently reported by @bitfinop below on CUDA/H200 with a clean v0.5.17 ↔ v0.5.18 boundary. A single interrupted 4k-token request produced more than 5,000 error messages over several minutes and kept consuming GPU decode throughput as a zombie.

Version note (verified from git history): the released v0.5.17 tag (2948168546, 2026-08-07) already contains #32588's cleanup-time abort dispatch (cherry-pick 283f505f9c, 2026-08-05), so only builds of that series predating 2026-08-05 exhibit this exact failure mode. The broken combination exists on main from #34160 (2026-08-09) onward — see chain below.

Root cause

  1. Client disconnect cancels the streaming response; CancelledError/GeneratorExit is raised inside TokenizerManager.generate_request.
  2. The cleanup runs under except BaseException: and immediately deletes rid_to_state[rid] via the pop-only _discard_pending_req_states.
  3. Two seconds later, the delayed create_abort_task fires abort_request(rid) - but its guard (rid not in self.rid_to_state -> return) silently drops the dispatch because the state was already deleted in step 2.
  4. The scheduler never receives an AbortReq and keeps decoding; every streamed chunk then hits the missing-state error path.

Regression chain:

Fix

All changes are in python/sglang/srt/managers/tokenizer_manager.py:

  • generate_request() cleanup: replace the pop-only _discard_pending_req_states with _abort_and_discard_pending_req_states, which dispatches AbortReq before popping each still-pending state, using concrete tracked rids only. Disconnect cleanup does not depend on the delayed background task; afterwards the delayed create_abort_task hits the rid_to_state guard and is a no-op, so exactly one AbortReq is sent per disconnected request.
  • Failure-path hardening: the dispatch inside the cleanup is wrapped in try/except Exception with the pop in a finally - a broken scheduler socket is logged, cleanup continues for the remaining requests, tokenizer state is still removed, and the original CancelledError/GeneratorExit is never masked.
  • abort_request() is not touched: the public guard keeps exact-ID semantics. Scheduler abort matching is prefix-based (req.rid.startswith(recv_req.rid) at eight sites in scheduler.py, plus grammar/dLLM/PD-disaggregation paths), so forwarding unknown or stale public rids could cancel unrelated live work sharing a prefix - e.g. abort_request(rid="batch") matches live batch_0..batch_10 generated by GenerateReqInput._normalize_rid, and "batch_1" also matches batch_10. An earlier revision of this PR removed the guard; that was wrong (found in review) and was reverted. /abort_request with an already-orphaned rid therefore remains a documented no-op.

Rebased onto latest main (d1af3c8923), where the guard is present upstream after the config-bags refactor (#35906); the remaining diff vs main is the cleanup fix, the failure-path hardening, and tests.

Repro

curl -sN localhost:30000/generate \
  -H 'Content-Type: application/json' \
  -d '{"text":"long story...","sampling_params":{"max_new_tokens":4000},"stream":true}' &
PID=$!

sleep 8 && kill -9 "$PID"   # client disconnect mid-decode

Before: thousands of state was deleted lines; #running-req stays elevated for minutes.
After: <=2 backlog lines, decode stops within ~1 s.

Verification

Test Before After
Streaming disconnect (mid-decode) Thousands of error messages; zombie until generation limit ≤2 backlog lines, stopped in ~1 s
/abort_request with bogus/stale rid (e.g. prefix like batch) dropped at the tokenizer, never dispatched unchanged (guard restored; prevents prefix fan-out)
/abort_request with orphaned rid silently dropped (no-op) unchanged (documented no-op)
Exact known rid abort dispatched dispatched
Duplicate abort after completion no second dispatch no second dispatch
Normal completion (stream/non-stream) OK OK
Dispatch failure during cleanup n/a logged; remaining requests still aborted; state removed; cancellation exception preserved

Unit coverage (CPU-only, mock-based): new test/registered/unit/managers/test_abort_lifecycle_regression.py (15 cases: unknown/stale/prefix/duplicate public rids never dispatched; disconnect cleanup dispatch-before-pop incl. per-rid batch ordering; delayed-task no-op; normal completion emits no abort; dispatch-failure tolerance incl. CancelledError preservation; _normalize_rid scheme + scheduler predicate characterization) plus the repaired registered test_tokenizer_manager_rid_cleanup.py: 33 passed. The pre-review head broke 5 of those registered tests (renamed helper, missing tokenizer_ipc_name mock) — repaired here.

GPU verification on SGLang commit 5a46d65 (main @ 2026-08-21, ROCm build), Qwen3.8-27B (BF16) on AMD MI300X (ROCm), TP=1, FP8 E4M3 KV cache.


CI States

Latest PR Test (Base): ❌ Run #32655915755
Latest PR Test (Extra): ❌ Run #32655915461
Latest PR Test (AMD ROCm 7.2): ❌ Run #32655915610

@gencer-altan

Copy link
Copy Markdown
Author

Hi! Quick status on CI: all 16 failing checks fail at the pr-gate step "Require run-ci label (optional)" - none of the actual test jobs started yet (they are all skipped), so the red checks reflect the missing run-ci label rather than any code failure. As an external contributor I cannot add the label myself (the API returns 403), so could someone with permission add run-ci and re-run the failed jobs to trigger CI?

Context while CI is pending: this change was verified on real AMD MI300X (ROCm) hardware with Qwen3.8-27B (TP=1, FP8 E4M3 KV cache) - after a client disconnect mid-decode, the orphaned request now gets an AbortReq dispatched to the scheduler and stops within ~1 s, instead of decoding until its generation limit. Thanks!

guqiong96 added a commit to guqiong96/Lsglang that referenced this pull request Aug 22, 2026
@guqiong96

Copy link
Copy Markdown

@Cayrop
Thanks for the PR that fixes this issue:

[2026-08-22 17:45:19] Received output for rid='fa58389fa9704408a710d5ad34474e45' but the state was deleted in TokenizerManager.
[2026-08-22 17:45:19] Received output for rid='fa58389fa9704408a710d5ad34474e45' but the state was deleted in TokenizerManager.

Before this fix, cancelled requests were still lingering as zombies. I have applied the PR to guqiong96/Lsglang@a7fee3c, and it runs well. Thanks again!

@chilltongx chilltongx 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.

The disconnect cleanup is directionally correct, but removing the rid_to_state guard from the public TokenizerManager.abort_request path makes the stated "unknown rids are a safe no-op" invariant false.

I verified this against the exact head a02bd281ba702d359dcb8ca9b08ecffbe78ad3dc. With tokenizer_worker_num == 1 and an empty rid_to_state, the base commit dispatches zero messages for abort_request(rid="batch"); this head dispatches one AbortReq. The scheduler then uses req.rid.startswith(recv_req.rid) at eight abort sites. Given active IDs batch_0, batch_1, and batch_10, an unknown/stale abort ID batch matches all three, and batch_1 also matches both batch_1 and batch_10. Batch IDs are generated with exactly this prefix scheme in GenerateReqInput._normalize_rid.

That changes /abort_request and the gRPC abort API from an exact-state-gated operation into a potentially broad prefix cancellation operation. The endpoint describes its argument as a request ID, not an arbitrary group prefix, so a stale or mistyped ID can now cancel unrelated live work sharing that prefix.

The zombie-request fix itself does not require this public-path change: _abort_and_discard_pending_req_states already dispatches the concrete pending rids directly before removing their tokenizer state. Please either retain the existing guard in abort_request, or make prefix/group cancellation explicit in the protocol and use exact matching for concrete request IDs. A regression test should cover both invariants: disconnect cleanup dispatches before the pop, while an unknown/stale public rid cannot cancel a live request merely because it is a prefix.

@bitfinop

Copy link
Copy Markdown

Second reproduction, this time on CUDA / H200, with a version boundary that may help narrow the regression.

Setup: DeepSeek-V4-Flash-0731, TP=2 on 2×H200, --speculative-algorithm DSPARK (--speculative-dspark-block-size 5, i.e. speculative_num_draft_tokens=6), --schedule-policy lpm, --enable-hierarchical-cache --hicache-ratio 2, --max-running-requests 64. Streaming clients sit behind a proxy that enforces a 60 s request timeout and a 30 s stream timeout, so mid-generation disconnects are routine for us.

Version boundary

  • v0.5.17 (sha256:16aba892…): a streaming request with max_tokens=3000, connection dropped after 3 s, produces 2 lines and then silence, single rid. The abort reaches the scheduler and the request dies.
  • v0.5.18 (build commit 71de97b264b0): the same class of disconnects produces bursts of 278–756 lines per minute.

Totals from an A/B/A/B benchmark (each version measured twice, three load levels per arm, ~3.5 h in total, identical flags, only the image digest changing):

v0.5.17 v0.5.18
state was deleted lines 63 9129
client-visible errors 0 0

The bursts are clustered into 2–3 minute windows (579 / 404 / 176, then 756 / 508, then 278 / 649) rather than spread as background noise — consistent with a handful of orphaned generations each emitting hundreds of lines while decoding to their limit, not with a logging-only issue.

Two things that may matter for triage:

  1. The failure is invisible to clients. Both our own load harness and sglang.benchmark.serving reported zero errors on both versions. The only symptoms are the log spam and the decode capacity silently spent on requests nobody is reading.
  2. The v0.5.17 → v0.5.18 boundary matches the analysis in this PR. The revert (Revert parallel request lifecycle tracking from #32588 #34160) landed after v0.5.17 was cut and retained the except BaseException: cleanup, so the pre-existing guard becomes a dispatch blocker only from v0.5.18 onwards. Our v0.5.17 control run above is consistent with that: same client behaviour, abort still dispatched.

We have deferred our v0.5.18 upgrade because of this. Happy to re-run the same A/B benchmark against either this PR or #35255 on the same hardware if that would help you choose between them.

@gencer-altan gencer-altan changed the title [Fix] Prevent zombie requests after client disconnect: always dispatch AbortReq [Fix] Prevent zombie requests after client disconnect: abort pending requests before dropping tokenizer state Aug 23, 2026
@gencer-altan

Copy link
Copy Markdown
Author

Confirmed — reproduced against a02bd281: with tokenizer_worker_num == 1 and an empty rid_to_state, base dispatches nothing for abort_request(rid="batch") while that head dispatched one AbortReq; with live batch_0..batch_10 (scheme straight from GenerateReqInput._normalize_rid) it cancels all 11, and "batch_1" also cancels batch_10. Prefix matching exists at 8 sites in scheduler.py plus grammar/dLLM/PD queues. You were right that the guard removal was unnecessary: B alone fixes the zombie loop.

Fixed in 5eb93a990a:

  • Restored the rid_to_state presence guard in abort_request() — /abort_request and the gRPC abort API keep exact-ID semantics.
  • Kept _abort_and_discard_pending_req_states (dispatch-before-pop). After cleanup, the delayed create_abort_task hits the restored guard and is a no-op, so exactly one AbortReq goes out per disconnected request.
  • Added test/registered/unit/managers/test_abort_lifecycle_regression.py covering both invariants you asked for: disconnect cleanup dispatches before the pop (including per-rid batch ordering and delayed-task no-op), and unknown/stale/prefix-like public rids are never dispatched. Also repaired the registered rid-cleanup tests that referenced the renamed helper — they were failing on the previous head. All 31 pass CPU-only.

Also corrected the PR body's regression chain while at it: #32588 didn't create the dispatch blocker on its own — it made the cleanup abort dispatched requests before dropping them (and was cherry-picked into v0.5.17 as 283f505f9c). The broken combination (except BaseException: + pop-only cleanup + guard) first appeared when #34160 selectively reverted #32588 (71043b9dbb, Aug 9) — after the v0.5.17 tag, before v0.5.18, consistent with the H200 boundary report above.

@bitfinop this branch keeps the zombie fix your benchmark targets — a re-run against 5eb93a990a would be welcome once CI has looked at it.

… disconnect

A streaming client disconnect raises CancelledError/GeneratorExit inside
generate_request; the handler cleanup popped rid_to_state entries without
telling the scheduler, and the delayed create_abort_task that fires 2s
later is dropped by the rid_to_state guard in abort_request(), so the
scheduler kept decoding the request until its generation limit while
TokenizerManager logged 'state was deleted' for every streamed chunk.

Replace the pop-only _discard_pending_req_states with
_abort_and_discard_pending_req_states, which dispatches AbortReq for each
concrete, still-tracked rid BEFORE popping its state. The public
abort_request() guard is left untouched, so unknown/stale rids are still
dropped at the tokenizer (scheduler abort matching is prefix-based) and
the delayed task becomes a no-op after cleanup -- exactly one AbortReq per
disconnected request.

Repair the registered rid-cleanup unit tests for the renamed helper and
add tokenizer_ipc_name to the mocked manager (cleanup now dispatches to
the scheduler), and add a 13-case regression suite covering both
lifecycle invariants: disconnect cleanup dispatches before the pop
(including per-rid batch ordering and delayed-task no-op), and
unknown/stale/prefix/duplicate public rids are never dispatched.
@gencer-altan
gencer-altan force-pushed the fix/disconnect-zombie-abort-race branch from 5eb93a9 to 7b8496b Compare August 23, 2026 17:21
@gencer-altan

Copy link
Copy Markdown
Author

Rebased onto latest main (d1af3c8923) as required by the CI gate; new head 7b8496b04a replaces 5eb93a990a. The rid_to_state guard is present upstream after the config-bags refactor (#35906), so the remaining diff is the disconnect-cleanup fix (dispatch-before-pop) plus the regression tests only.

If dispatching an AbortReq fails in _abort_and_discard_pending_req_states
(e.g. a broken scheduler socket during shutdown), the exception used to
abort the cleanup loop mid-way: remaining rid_to_state entries leaked and
the original CancelledError/GeneratorExit was masked by the dispatch
error. Wrap the dispatch in try/except Exception with the pop in a
finally block -- the failure is logged, the state is still removed, and
the loop continues with the remaining rids, matching the guarded
dispatch in earlier implementations of this cleanup.

Add regression coverage: a batch cleanup where the middle dispatch
raises still pops every rid and keeps aborting the rest, and a
generate_request-level test asserts the original CancelledError survives
a dispatch failure during cleanup.
@gencer-altan

Copy link
Copy Markdown
Author

Added one failure-path hardening change (764f0b95c6): if dispatching an AbortReq fails during disconnect cleanup, the failure is logged, cleanup continues for the remaining requests, and tokenizer state is still removed (finally), so a broken scheduler socket can no longer leak rid_to_state entries or mask the original CancelledError/GeneratorExit. Added regression coverage for dispatch failure during cleanup, including a generate_request-level test that asserts the cancellation exception is preserved.

@SAXEM1997

Copy link
Copy Markdown
Contributor

Production confirmation on 8×H20 (CUDA, SM90) with v0.5.18 + DeepSeek-V4-Flash-0731 + DSPARK

Adding another production data point matching this exact issue, on NVIDIA H20 with sglang v0.5.18, DeepSeek-V4-Flash-0731 (FP4 routed experts / marlin runner), DSPARK (speculative_num_draft_tokens=6), schedule_policy=lpm, HiCache enabled, single node 8×H20, TP=8.

Scale observed (2026-08-25, 24h window):

  • 31,063 occurrences of Received output for rid='...' but the state was deleted in TokenizerManager (ERROR level)
  • From only 28 unique request IDs — a few orphaned requests each producing thousands of spurious outputs
  • Worst case: one interrupted request produced 7,063 outputs in 88 seconds (~80 outputs/s = full-speed decode), burning an entire GPU slot for ~88s in a max_running_requests=8 deployment
  • Peak hour: 16,064 occurrences between 10:00–11:00 local time (matches agent-UI cancellation patterns)

Impact confirmed in production: orphans occupy running slots under max_running_requests=8, directly contributing to queue buildup during peak hours; plus heavy ERROR-log noise masking real errors. We also confirmed a related wrinkle: the client disconnect path with tokenizer_worker_num == 1 removes rid_to_state before the delayed create_abort_task fires, so abort_request skips dispatch — matching the described root cause. For the Anthropic-compat endpoint (/v1/messages, Claude Code clients), max_tokens is required by the protocol so the orphan's lifetime is bounded by the client-supplied value, but the wasted decode still holds a running slot until it finishes.

Happy to provide full log excerpts or run verification builds if helpful. This fix matters a lot for production agent workloads — hoping to see it land for 0.5.19.

Leoyzen added a commit to Leoyzen/sglang that referenced this pull request Aug 27, 2026
…nt disconnect (sgl-project#35936)

On client disconnect, CancelledError/GeneratorExit (both BaseException)
reaches the generate_request cleanup, which popped rid_to_state entries
immediately. The delayed create_abort_task then hit the rid_to_state guard
in abort_request and silently skipped the dispatch, so the scheduler never
learned the client was gone and kept decoding to max_tokens, flooding logs
with 'state was deleted in TokenizerManager' and burning GPU slots.

Replace the pop-only cleanup with _abort_and_discard_pending_req_states:
dispatch AbortReq for each still-pending rid BEFORE removing its state, and
keep the public abort_request rid_to_state guard so unknown/stale rids
cannot trigger broad prefix-based cancellation (scheduler abort matching is
startswith-based). A dispatch failure during cleanup is logged and cleanup
continues (finally) so a broken scheduler socket cannot leak entries.
@tengotengo

Copy link
Copy Markdown

Confirmation from a different code lineage and GPU class: applied this PR's tokenizer_manager.py change to the day-0 image lmsysorg/sglang:qwen38flashnext (commit d91c368) on an RTX PRO 6000 Blackwell (SM120), TP1, serving Qwen3.8-Flash-Next NVFP4 (--quantization modelopt_fp4 --fp4-gemm-backend flashinfer_cutlass --ple-offload-embedding, BF16 KV, no spec decode).

The diff applies file-level unchanged to that base (only the method rename in tokenizer_manager.py; anchors are identical to main).

Before: one cancelled streaming request left the scheduler decoding it to its configured max_tokens. Observed 61,976 "Received output for rid=... but the state was deleted" lines over ~2 minutes with #running-req: 1 pinned (we run --max-running-requests 1) and every new request queued behind the zombie. Only a container restart cleared it.

After: streamed ~8 s (~1,600 chunks), disconnected mid-generation → zero "state was deleted" lines and zero further decode batches; the slot freed immediately and the next request served normally.

@bitfinop

bitfinop commented Sep 6, 2026

Copy link
Copy Markdown

#35255 covers this and was merged on Sep 4. It keeps the state until the scheduler replies instead of deleting it immediately, so no state was deleted lines appear at all, and it also restores the abort lost during chunked prefill.

Numbers from the v0.5.19 release build (DeepSeek-V4-Flash, TP=2, DSpark, --chunked-prefill-size 16384): five streamed requests aborted at 3s produce 5082 such lines. With #35255 backported onto the tag, the same probe gives 0, and num_running_reqs returns to 0 within 30s.

@SAXEM1997

Copy link
Copy Markdown
Contributor

Update from our side (we reported the 8×H20 production numbers upthread, 31,063 lines / 28 rids per 24h on v0.5.18): we are now 13 days into running v0.5.19 + this PR as a single-file tokenizer_manager.py bind mount, still in production.

Result on v0.5.19 + this patch: state was deleted dropped to 55 lines / 16h across 25 unique rids — ~2 lines per rid, i.e. exactly the "≤2 backlog lines" transient the PR describes (the in-flight decode batch arriving right after cleanup), with zero zombie re-decode and no slot occupancy. So both fix strategies are now field-validated on this hardware.

On @bitfinop's note that #35255 was merged to main on Sep 4 — thanks, that's the cleaner long-term path since it also restores the abort lost during chunked prefill, which this PR doesn't cover (we run chunked-prefill-size=32768, so that race is relevant to us). One question for the maintainers that matters for everyone pinned to the v0.5.19 tag: is #35255 planned to be backported to a v0.5.19.x patch release? As of the v0.5.19 release build the regression is still fully reproducible (bitfinop's probe: 5,082 lines), so 0.5.19 users today have to choose between hand-backporting #35255 or carrying this PR — an official backport (or even just a pointer in the release notes) would settle that.

If this PR is now considered superseded by #35255 and won't be merged, a short note to that effect would also help — the production validation data in this thread (H200 / MI300X / RTX 6000 / H20) would then live under the winning PR's references. Either way, thanks @Cayrop — this fix has been carrying our production since Aug 25.

@gencer-altan

Copy link
Copy Markdown
Author

I saw that #35255 has been merged. Since it targets the same disconnect race and provides a more comprehensive fix, I'm fine with considering #35936 superseded and closing it.

It would also be useful to reference the independent production validation results from this thread in #35255.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants