From 6b1a51d80e4a6ec9d950e350301edf8df1f0bd35 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Fri, 25 Sep 2026 18:18:54 +0000 Subject: [PATCH] feat(glm53): v3 HiCache W4AFP8 image that keeps the HTTP event loop free The GLM-5.3 Flash engines answer /health, /metrics and chat requests from one uvicorn event loop, so any work done synchronously on it also stops /health, and the CVM proxy's 3 s probes miss. This adds three patches to docker/sglang-glm53-hicache-w4afp8: - sglang-pr30771.diff: upstream sgl-project/sglang PR #30771 (open), byte-identical to its diff at head 60a56aa. Chat template rendering and tokenization run in a single-worker request-preprocessor thread. - shm-off-loop.diff (new, applied after it): the dispatch-time /dev/shm copy of multimodal features, about 141 MiB per large image, runs on its own sglang-mm-shm thread. A request cancelled during the copy still has its segments unlinked once the copy finishes. - event-loop-stall-dump.diff (new, diagnostic, on by default): after 30 s without a loop tick, every thread's stack goes to stderr with the prefix [event-loop-stall]; SGLANG_EVENT_LOOP_STALL_DUMP_SECS=0 disables it. It targets the multi-minute gpu02 hangs, which have never left a stack. Evidence (gpu32 lab, 2026-09-25, same source bytes bind-mounted over v1, one request at a time, worst /health probe): - 4.7 MB text chat: 3,444 ms stock, 38 ms with PR #30771 alone. - With PR #30771 alone, each 64-image request still blocked the loop once for 3.7 to over 5 s, mostly in the shm copy (8.8-8.9 GiB per request). - All three patches, stall dump at 30 s: 30 / 163 / 551 / 1,258 ms for the text and the 64 x 9 / 48 / 169 MP requests, 0 of 3,211 probes over 3 s. The stock arm in the same half hour: 3,033 / 3,098 / 2,976 / 4,062 ms. prompt_tokens identical, no /dev/shm leak, no errors, no stall dumps. - Stall dump: 58/58 CPU checks. Live on a GPU engine at a 2 s threshold it named the shm copy on the loop thread and logged the recovery. apply-patches.py now checks and applies each patch in order, because shm-off-loop.diff edits lines that sglang-pr30771.diff adds and cannot be checked against the unpatched base. source-manifest.json gains http_server.py, serving_base.py, tokenizer_manager.py (base to final; PROVENANCE records the hash between the two patches), the new utils module and the PR's three test files. test-cpu.sh gains steps 5-7: the PR's own tests, a check of the shm move, and the stall-dump test, shipped as test_stall_dump.py. Run against its base 3eccc307 in a CPU-only container, the recipe passes sha256sum --check, apply-patches.py and test-cpu.sh steps 1-7. The publish workflow pins the new hashes and defaults to glm53-hicache-w4afp8-v3, so the v1 and v2 tags stay as they are (its tag input description, which still said v1, now says v3). No compose file changes here: r2 is pinned to v3 in a follow-up once the image is published. --- .../publish-glm53-admission-reserve.yaml | 10 +- docker/sglang-glm53-hicache-w4afp8/Dockerfile | 25 +- docker/sglang-glm53-hicache-w4afp8/PROVENANCE | 17 + docker/sglang-glm53-hicache-w4afp8/README.md | 136 ++++- docker/sglang-glm53-hicache-w4afp8/SHA256SUMS | 14 +- .../apply-patches.py | 11 +- .../event-loop-stall-dump.diff | 156 ++++++ .../sglang-pr30771.diff | 490 ++++++++++++++++++ .../shm-off-loop.diff | 69 +++ .../source-manifest.json | 28 + .../sglang-glm53-hicache-w4afp8/test-cpu.sh | 161 ++++++ .../test_stall_dump.py | 415 +++++++++++++++ 12 files changed, 1507 insertions(+), 25 deletions(-) create mode 100644 docker/sglang-glm53-hicache-w4afp8/event-loop-stall-dump.diff create mode 100644 docker/sglang-glm53-hicache-w4afp8/sglang-pr30771.diff create mode 100644 docker/sglang-glm53-hicache-w4afp8/shm-off-loop.diff create mode 100644 docker/sglang-glm53-hicache-w4afp8/test_stall_dump.py diff --git a/.github/workflows/publish-glm53-admission-reserve.yaml b/.github/workflows/publish-glm53-admission-reserve.yaml index 79523813..18349ed8 100644 --- a/.github/workflows/publish-glm53-admission-reserve.yaml +++ b/.github/workflows/publish-glm53-admission-reserve.yaml @@ -15,7 +15,7 @@ on: - w4afp8 - hicache-w4afp8 tag: - description: Docker Hub tag; empty derives the per-variant default (glm53-admission-reserve-v10, glm53-hicache-admission-reserve-v10, glm53-pool-clamp-v1, glm53-hicache-pool-clamp-v1, glm53-w4afp8-pool-clamp-v1, glm53-hicache-w4afp8-v1) + description: Docker Hub tag; empty derives the per-variant default (glm53-admission-reserve-v10, glm53-hicache-admission-reserve-v10, glm53-pool-clamp-v1, glm53-hicache-pool-clamp-v1, glm53-w4afp8-pool-clamp-v1, glm53-hicache-w4afp8-v3) required: false type: string default: '' @@ -119,12 +119,12 @@ jobs: hicache-w4afp8) echo "BUILD_CONTEXT=docker/sglang-glm53-hicache-w4afp8" >> "$GITHUB_ENV" echo "BASE_DIGEST=sha256:3eccc30709f5719c81084d1264f03ca5354b3059ec4cff62f0c5ff88c309680c" >> "$GITHUB_ENV" - echo "EXPECTED_DOCKERFILE_SHA256=d910a7a2172219292f6196f20d8232c8573de2f412d8eceea3b1202002f43ebf" >> "$GITHUB_ENV" - echo "EXPECTED_PROVENANCE_SHA256=49c6fd3ef72c0bed3991b325361cd2245ed27a3a946a92b95cd9c562ff45585e" >> "$GITHUB_ENV" - echo "EXPECTED_SHA256SUMS_SHA256=d5b4e05f35ebf3f4c84a676161cb1d22953488d91b8f1d394214710d8225fe8a" >> "$GITHUB_ENV" + echo "EXPECTED_DOCKERFILE_SHA256=f5136afd7b9107ad0ca56a1e9c1b5d76633803f34cfcb338e4223592524bbc96" >> "$GITHUB_ENV" + echo "EXPECTED_PROVENANCE_SHA256=720fd00c13ba60c6f01c1de5009772104da5a44fc8ed0429f01502fab9d17b38" >> "$GITHUB_ENV" + echo "EXPECTED_SHA256SUMS_SHA256=2f74f65b9b27a8ea8e0b479ac44b13d289d8bef9f7cab68e3b30ead0a852c2f3" >> "$GITHUB_ENV" echo "TEST_SCRIPT=/usr/share/nearai/glm53-hicache-w4afp8/test-cpu.sh" >> "$GITHUB_ENV" echo "EVIDENCE_PREFIX=glm53-hicache-w4afp8" >> "$GITHUB_ENV" - DEFAULT_TAG=glm53-hicache-w4afp8-v2 + DEFAULT_TAG=glm53-hicache-w4afp8-v3 ;; *) echo "Unknown variant: $VARIANT" >&2 diff --git a/docker/sglang-glm53-hicache-w4afp8/Dockerfile b/docker/sglang-glm53-hicache-w4afp8/Dockerfile index 25da9f2b..dc74a028 100644 --- a/docker/sglang-glm53-hicache-w4afp8/Dockerfile +++ b/docker/sglang-glm53-hicache-w4afp8/Dockerfile @@ -3,7 +3,7 @@ FROM docker.io/nearaidev/sglang@sha256:3eccc30709f5719c81084d1264f03ca5354b3059e ARG BUILD_SOURCE_REVISION LABEL org.opencontainers.image.title="GLM-5.3 Flash HiCache W4AFP8 engine" -LABEL org.opencontainers.image.description="HCC-safe HiCache engine with admission reserve v10, the W4AFP8 loader fix, the unconditional chunked-prefill pool clamp and the opt-in DSA indexer query split" +LABEL org.opencontainers.image.description="HCC-safe HiCache engine with admission reserve v10, the W4AFP8 loader fix, the unconditional chunked-prefill pool clamp, the opt-in DSA indexer query split, request preprocessing and the multimodal shared-memory copy moved off the HTTP event loop, and an event-loop stall dump" LABEL org.opencontainers.image.source="https://github.com/nearai/cvm-compose-files" LABEL org.opencontainers.image.revision="${BUILD_SOURCE_REVISION}" LABEL org.opencontainers.image.base.name="docker.io/nearaidev/sglang" @@ -21,6 +21,9 @@ LABEL nearai.sglang.hcc_managed_memory="v3-host-prefetch-opt-in" LABEL nearai.sglang.w4afp8_loader_patch="modules-to-not-convert-v1" LABEL nearai.sglang.chunked_prefill_pool_clamp="v1" LABEL nearai.sglang.dsa_indexer_qsplit="v1-opt-in" +LABEL nearai.sglang.request_preprocessing_off_loop="pr30771-60a56aa" +LABEL nearai.sglang.mm_shm_wrap_off_loop="v1" +LABEL nearai.sglang.event_loop_stall_dump="v1-on-30s" COPY Dockerfile \ PROVENANCE \ @@ -29,9 +32,13 @@ COPY Dockerfile \ apply-patches.py \ chunked-prefill-pool-clamp.diff \ dsa-indexer-qsplit.diff \ + event-loop-stall-dump.diff \ modules-to-not-convert.diff \ + sglang-pr30771.diff \ + shm-off-loop.diff \ source-manifest.json \ test-cpu.sh \ + test_stall_dump.py \ /usr/share/nearai/glm53-hicache-w4afp8/ RUN test -n "$BUILD_SOURCE_REVISION" \ && cd /usr/share/nearai/glm53-hicache-w4afp8 \ @@ -39,8 +46,14 @@ RUN test -n "$BUILD_SOURCE_REVISION" \ && python3 apply-patches.py # The loader and pool-clamp patches are required for the W4AFP8 image and are unconditional. The DSA -# indexer query split is inert unless SGLANG_DSA_INDEXER_QSPLIT=1. Everything inherited from -# the base stays opt-in: admission reserve v10 via SGLANG_CHUNKED_PREFILL_ADMISSION_RESERVE, and -# HiCache via --enable-hierarchical-cache plus SGLANG_HICACHE_*. On an HCC/PPCIe (TEE) host -# SGLANG_HICACHE_CUDA_HOST_MEMORY must stay 1; 0 selects the anonymous-mmap plus cudaHostRegister -# path, which fails with CUDA error 801. +# indexer query split is inert unless SGLANG_DSA_INDEXER_QSPLIT=1. The two event-loop patches are +# unconditional: upstream sglang PR #30771 runs chat template rendering and tokenization in a +# request-preprocessor thread, and shm-off-loop moves the dispatch-time /dev/shm copy of multimodal +# features to its own thread, so /health keeps answering during multi-MB and image-heavy requests. +# The event-loop stall dump is on by default: after 30 s without a loop tick it writes every +# thread's stack to stderr with the prefix [event-loop-stall]. SGLANG_EVENT_LOOP_STALL_DUMP_SECS=0 +# disables it; SGLANG_EVENT_LOOP_STALL_DUMP_REPEAT_SECS (default 60) spaces the repeats. +# Everything inherited from the base stays opt-in: admission reserve v10 via +# SGLANG_CHUNKED_PREFILL_ADMISSION_RESERVE, and HiCache via --enable-hierarchical-cache plus +# SGLANG_HICACHE_*. On an HCC/PPCIe (TEE) host SGLANG_HICACHE_CUDA_HOST_MEMORY must stay 1; 0 selects +# the anonymous-mmap plus cudaHostRegister path, which fails with CUDA error 801. diff --git a/docker/sglang-glm53-hicache-w4afp8/PROVENANCE b/docker/sglang-glm53-hicache-w4afp8/PROVENANCE index c76e9ec2..288e4ca3 100644 --- a/docker/sglang-glm53-hicache-w4afp8/PROVENANCE +++ b/docker/sglang-glm53-hicache-w4afp8/PROVENANCE @@ -16,6 +16,23 @@ patch_3_sha256=37ad31b95511a831038d2ab572656a59d4ba1c9c21348d9fcb0095cba665aad1 patch_3_origin=new in this recipe; lab form validated on gpu31/gpu32 2026-09-24 patch_3_scope=IndexerKPool._get_topk_ragged_kpool_plan only; inert unless SGLANG_DSA_INDEXER_QSPLIT=1 (min rows SGLANG_DSA_INDEXER_QSPLIT_MIN_ROWS, default 1024) patch_3_evidence=stored long-tier traffic paired TTFT 0.81-0.85x (both island orders), c16384 burst min free 9.5 GB vs 0.65 GB, GSM8K/MMLU/passkey/teacher-forced agreement at the noise floor; gpu31:/data/inference-optimizer-20260913/results/roofline-20260923/fix3 +patch_file_4=docker/sglang-glm53-hicache-w4afp8/sglang-pr30771.diff +patch_4_sha256=a102977de7bb02776cee1053ff04979b740526fe99c59d2c63e2f3962df3c95d +patch_4_origin=upstream sgl-project/sglang PR #30771 "fix(frontend): offload blocking request preprocessing" (open, unmerged); byte-identical to the PR diff at head 60a56aa361832a49b771762ecdd1694c9639171b; applies to fc91d24 with line offsets only +patch_4_scope=OpenAIServingBase.handle_request and TokenizerManager._tokenize_texts: request conversion (chat template render + tokenize) and the regular-tokenizer path run in a single-worker request-preprocessor thread instead of on the uvicorn event loop; adds the PR's three CPU tests under test/registered/unit; unconditional, no env var +patch_4_evidence=gpu32 2026-09-25, same source bytes bind-mounted over the fde25985 image: worst /health probe during a 4.7 MB text chat (653,502 prompt tokens) 3,444 ms stock vs 38 ms patched (p95 1.9 ms); prompt_tokens identical on 11 correctness/image cases and 4 large shapes; the PR's tests pass 5/5 patched and fail 3 (2 skipped) on the stock files; gpu32:/data/glm53-dyntok-20260925 +patch_file_5=docker/sglang-glm53-hicache-w4afp8/shm-off-loop.diff +patch_5_sha256=4bd4cc65d68deacd1b56b95e32a2242853d20bd3cfa4188e8c1a20777cc79a94 +patch_5_origin=new in this recipe (gpu32 lab 2026-09-25) +patch_5_scope=TokenizerManager._send_one_request only: for requests with multimodal inputs, wrap_shm_features (posix_fallocate + copy_ into /dev/shm) runs on its own single-thread executor (sglang-mm-shm) instead of the event loop; a request cancelled during the copy has its segments discarded once the copy finishes; unconditional, no env var +patch_5_stacking=applied after patch 4, whose request-preprocessor setup it extends; tokenizer_manager.py cc4d633d8c609300e095a16ef7fe460e2c3c0e0ad52fcc76e9134d0aee4dff51 (base) -> d32617ee41a0e2e55e8ca6924e45afec4645551b1b87f0171b17818980b78867 (after patch 4) -> 1037bbac2e0183882e3f3c16d6be9492e047ff4b4ce4724f0baba9a3cd46cc4f (after patch 5, the manifest after-hash) +patch_5_evidence=gpu32 2026-09-25. Phase 3a: with patch 4 alone each 64-image request still blocked the event loop once at dispatch, for 3.7 s to over 5.0 s (3.0-4.0 s on the stock arm), in ShmPointerMMData.__init__ (posix_fallocate + copy_ of ~141 MiB per image, 8.8-8.9 GiB per request). Phase 3b, patches 4-6 bind-mounted over the fde25985 image (stall dump at 30 s): worst /health probe 30 / 163 / 551 / 1,258 ms for the 4.7 MB text and the 64 x 9 / 48 / 169 MP requests, 0 of 3,211 probes over 3 s, vs 3,033 / 3,098 / 2,976 / 4,062 ms on the stock arm; the copy runs on sglang-mm-shm_0 while the loop idles; prompt_tokens identical, no /dev/shm leak, no Traceback. The remainder is the GIL-held process_mm_data_async return, untouched here. CPU-only with real ShmPointerMMData (16 x 141 MiB, 32 CPUs): stock inline copy blocks the loop 897 ms, patched longest gap 8.1 ms, a request cancelled mid-copy leaves 0 segments (a plain run_in_executor leaks 16 of 16); test-cpu.sh step 6 checks the executor thread, loop progress during the copy and the discard on cancellation +patch_file_6=docker/sglang-glm53-hicache-w4afp8/event-loop-stall-dump.diff +patch_6_sha256=367dbcdec432586ae4c8ab984c08caafb2f148d62cebf257d12e89c4c32f72ab +patch_6_origin=new in this recipe (gpu32 lab 2026-09-25) +patch_6_scope=new module python/sglang/srt/utils/event_loop_stall_dump.py plus a lifespan hook in entrypoints/http_server.py; diagnostic only, request handling unchanged; on by default: first dump after 30 s without a loop tick (SGLANG_EVENT_LOOP_STALL_DUMP_SECS, 0 disables), repeats every 60 s (SGLANG_EVENT_LOOP_STALL_DUMP_REPEAT_SECS) +patch_6_evidence=CPU-only throwaway containers of the fde25985 image on gpu32: git apply reproduces these after-hashes, import check 6/6, test_stall_dump.py 58/58 (shipped here, test-cpu.sh step 7). Live on GPU engines (gpu32 2026-09-25): at a 2 s threshold, armed at startup, no dump through startup, warmup and 2.5 min idle, and one 64-image request gave 2 dumps naming ShmPointerMMData.__init__ dst.copy_ on the event-loop thread (loop CPU 2.0 s of 2.8 s), then recovered after 5.3 s, about 16 KB per dump; at the 30 s default with patches 4-5, armed and 0 dumps across the text and three 64-image requests. Not yet exercised by the multi-minute hang, which the lab has not reproduced; gpu32:/data/glm53-dyntok-20260925 +composition_event_loop=patches 4-6 touch entrypoints/http_server.py, entrypoints/openai/serving_base.py, managers/tokenizer_manager.py, a new utils module and three new test files; none of those is touched by the HiCache patches or patches 1-3. Checked in the real base image 3eccc307 (2026-09-25): serving_base.py=3d0613b92abae51e8566a11ae80a2369a46422b49bd63c4cd6aa593d8a4bdbc2, tokenizer_manager.py=cc4d633d8c609300e095a16ef7fe460e2c3c0e0ad52fcc76e9134d0aee4dff51, http_server.py=553e5d1108dfded05e1693f7a26efd733e297b9ef7b238905e09e52a5e848652 (all equal to fc91d24), the four new paths absent composition=docker/sglang-glm53-w4afp8 rebased onto the HCC-safe HiCache image instead of the plain admission-reserve image, so a w4afp8 checkpoint and hierarchical caching can run in one engine composition_safety=all three patch targets are byte-identical in both bases, verified against the real base image rather than assumed: w4afp8.py=21e9c527c9b83e350cdc35ce2bc62891cda1550934b2a5d302f0f807f752f125, schedule_policy.py=02def839ec597d2b141f9d97aace6dc376c047cf670e115e851c86cb875362f0, scheduler.py=6ffd1584f6bcbbd3384f1ec45e3313a7b4b010fd3f900b8f19345d4b02f5d0ba composition_disjointness=the HiCache patches touch mem_cache/*, disaggregation/* and schedule_batch.py; neither added patch touches any of those files, so source-manifest.json is reused unchanged from docker/sglang-glm53-w4afp8 diff --git a/docker/sglang-glm53-hicache-w4afp8/README.md b/docker/sglang-glm53-hicache-w4afp8/README.md index 2da9c0f8..d17fdd8b 100644 --- a/docker/sglang-glm53-hicache-w4afp8/README.md +++ b/docker/sglang-glm53-hicache-w4afp8/README.md @@ -10,13 +10,17 @@ CUDA error 801. ## What it layers Base `sha256:3eccc307…` (HiCache + admission reserve v10) plus two correctness patches, both -byte-identical copies of the reviewed originals, and one opt-in performance patch: +byte-identical copies of the reviewed originals, one opt-in performance patch, two patches that move +blocking work off the HTTP event loop, and one diagnostic: | patch | origin | scope | | --- | --- | --- | | `chunked-prefill-pool-clamp.diff` | `docker/sglang-glm53-pool-clamp` | `PrefillAdder.add_chunked_req` only | | `modules-to-not-convert.diff` | `docker/sglang-glm53-w4afp8` | `W4AFp8Config.from_config` only | | `dsa-indexer-qsplit.diff` | new here (opt-in, `SGLANG_DSA_INDEXER_QSPLIT=1`) | `IndexerKPool._get_topk_ragged_kpool_plan` only | +| `sglang-pr30771.diff` | upstream sglang PR #30771 (open), byte-identical to its diff at head `60a56aa` | `OpenAIServingBase.handle_request`, `TokenizerManager._tokenize_texts`, plus the PR's three CPU tests | +| `shm-off-loop.diff` | new here, applied after `sglang-pr30771.diff` | `TokenizerManager._send_one_request`, requests with multimodal inputs only | +| `event-loop-stall-dump.diff` | new here (diagnostic, on by default at 30 s) | new `utils/event_loop_stall_dump.py` plus a hook in the HTTP server lifespan | ## DSA indexer query split (opt-in) @@ -39,11 +43,112 @@ Evidence (gpu31/gpu32, 2026-09-24, lab form of this patch; every A/B in both isl teacher-forced top-1 agreement on 116K / 359K real text 97.75% / 96.73% vs a base-vs-base noise floor of 97.41% / 96.97%. +## Blocking work moved off the HTTP event loop + +The `sglang serve` main process (the tokenizer manager) answers `/health`, `/metrics` and +`/v1/chat/completions` from one uvicorn event loop, so any synchronous work on that loop also stops +`/health`. The CVM proxy marks a replica unhealthy after three consecutive missed probes (3 s timeout +each). On the gpu02 long tier this showed up as replicas flapping under image-heavy traffic. + +- `sglang-pr30771.diff` runs request conversion (chat template rendering and `tokenizer.encode` in + `_convert_to_internal_request`) and the regular-tokenizer path of `_tokenize_texts` in a + single-worker request-preprocessor thread. Requests are still preprocessed one at a time, now in + that thread. +- `shm-off-loop.diff` moves the dispatch-time copy of multimodal features into `/dev/shm` + (`wrap_shm_features`: `posix_fallocate` plus `copy_`, about 141 MiB per large image) to its own + single-thread executor, `sglang-mm-shm`. A multi-GiB copy then neither blocks the loop nor waits + behind other requests' preprocessing. If the request is cancelled during the copy, its segments are + discarded once the copy finishes. It extends the executor setup PR #30771 adds, so it is applied + after it. + +Evidence (gpu32, 2026-09-25, CC off): the same source bytes bind-mounted over the v1 image +`fde25985…` on an arm that also ran `--enable-dynamic-batch-tokenizer`, one request at a time, +`/health` probed every 200 ms. Worst `/health` probe per request, in two sessions, each patched run +next to a stock arm in the same half hour: + +| request | stock | PR #30771 alone | PR #30771 + shm-off-loop (+ stall dump at 30 s) | +| --- | --- | --- | --- | +| 4.7 MB text chat (653,502 prompt tokens) | 3,444 / 3,033 ms | 38 ms | 30 ms | +| 64 images of 9 MP | 3,047 / 3,098 ms | 3,665 ms | 163 ms | +| 64 images of 48 MP | 3,046 / 2,976 ms | 3,903 ms | 551 ms | +| 64 images of 169 MP | 4,021 / 4,062 ms | ≥ 5,007 ms (probe timeout) | 1,258 ms | + +- PR #30771 removes the text stall. With it applied, py-spy puts each remaining image stall in + `ShmPointerMMData.__init__` on the event loop: 64 segments of ~141 MiB, 8.8-8.9 GiB per request. + That copy is what `shm-off-loop.diff` moves. +- With both patches no probe went over 3 s: 0 of 3,211, against one over 3 s on three of the four + requests on the stock arm. py-spy taken during the copies shows the loop thread idle while + `sglang-mm-shm_0` runs `ShmPointerMMData.__init__`. +- The image stalls with PR #30771 alone ran 0.6-1.0 s longer than on the stock arm. That code is not + touched by the patch, and two unpatched arms had differed by up to 0.3 s in either direction the + same day, so the difference is not attributed to it. +- `prompt_tokens` stayed identical on 11 correctness and small-image cases and on the four large + requests. The PR's own tests pass 5/5 on the patched files; on the stock files 3 fail and 2 are + skipped. +- A 15-minute flood of screenshot conversations through the pinned proxy (450 requests, GPUs about + 90 % busy) caused no unhealthy transitions on either the patched or the stock arm. +- The shm move was tested CPU-only in the v1 image with real `ShmPointerMMData` segments + (16 × 141 MiB per request, 32 CPUs). The stock inline copy blocked the loop for 897 ms; with the + patch the longest loop gap was 8.1 ms, the copy ran on `sglang-mm-shm_0`, and the features arrived + byte-identical. A request cancelled mid-copy left 0 segments behind, while a plain + `run_in_executor` without the cleanup leaked all 16. +- `test-cpu.sh` step 6 checks the same mechanism without touching `/dev/shm`, which the publish + workflow's test container keeps at Docker's 64 MB default: the copy runs on `sglang-mm-shm` while + the loop keeps running, and a cancelled copy is discarded. It fails if the copy is put back on the + loop or the discard is dropped. +- What remains with both patches (163 ms, 551 ms and 1,258 ms above) comes just before the copy: C + code holding the GIL on the loop where `process_mm_data_async` returns, the same line on patched + and stock engines. It grows with the source image size, from 9 MP to 169 MP (13000x13000). Neither + patch touches it. +- `prompt_tokens` were identical across all runs, every request returned HTTP 200, `/dev/shm` was + back to the same used bytes and segment names 13 s after every request, and the engine log had no + `Traceback`, no `Already borrowed` and, at the default 30 s, no stall dump. End-to-end time matched + the stock arm on three requests. The 9 MP request took 256 s against 81 s, all of it before + dispatch in image processing, during host memory pressure; the patches do not run before dispatch. +- Not covered: the minutes-long hang seen on gpu02 has not been reproduced in the lab, so neither + patch is known to fix it. The stall dump below is there to capture it. +- Also not covered on GPU: the production engines do not set `--enable-dynamic-batch-tokenizer`, + which on the lab arm ran the second tokenization pass in its own thread. In production that pass + goes through PR #30771's `_tokenize_texts` change instead, which only the PR's unit test covers. + +## Event-loop stall dump (on by default) + +`event-loop-stall-dump.diff` adds `python/sglang/srt/utils/event_loop_stall_dump.py` and arms it +from the HTTP server's lifespan, before the warmup thread starts. A task on the loop records a +heartbeat every second and a daemon thread (`event-loop-stall-watch`) checks it. + +- After `SGLANG_EVENT_LOOP_STALL_DUMP_SECS` (default 30) without a tick, it writes a header and every + thread's Python stack to stderr, one line per write, each line prefixed `[event-loop-stall]`. The + header has the pid, the stall age and how much CPU the loop thread used since its last tick. +- It repeats every `SGLANG_EVENT_LOOP_STALL_DUMP_REPEAT_SECS` (default 60) while the stall lasts, and + logs `event loop recovered after N s` when the loop ticks again. +- If the loop thread holds the GIL in one long C call, the Python watcher cannot run. faulthandler + then dumps every thread without the GIL 3 s later, as an unprefixed `Timeout (0:00:33)!` block. +- `0` disables it. An invalid value logs one `event-loop stall dump not armed` warning and the server + starts normally. At startup it logs + `event-loop stall dump armed: stall=30s repeat=60s (pid N, loop thread 0x…)`. +- Request handling is unchanged. The cost is one timer re-arm per second on the loop (median 198 µs + in the image on gpu32) and one watcher wakeup per second. Stalls shorter than the threshold are not + dumped. +- Validated CPU-only: `test_stall_dump.py` (58 checks, shipped here) runs as step 7 of `test-cpu.sh`. +- Validated live on a GPU engine (gpu32, threshold lowered to 2 s): armed at startup, silent through + startup, warmup and 2.5 minutes idle. One 64-image request produced two dumps, both naming + `ShmPointerMMData.__init__` (`dst.copy_`) on the event-loop thread with the loop thread using 2.0 s + of CPU in the first 2.8 s, then `event loop recovered after 5.3s`. Each dump was about 16 KB for 11 + threads. + +To read it, filter the engine log on `[event-loop-stall]`. Loop-thread CPU near 0 means the loop is +waiting (a lock, I/O, the GIL); CPU close to the stall age means it is computing. + ## Why the composition is safe The HiCache patches touch `mem_cache/*`, `disaggregation/*` and `schedule_batch.py`. None of the added patches touches any of those files, so the patch sets are disjoint. `source-manifest.json` -is the one from `docker/sglang-glm53-w4afp8` plus the `dsa_indexer_kpool.py` entry. +is the one from `docker/sglang-glm53-w4afp8` plus the `dsa_indexer_kpool.py` entry and the +event-loop entries: `http_server.py`, `serving_base.py`, `tokenizer_manager.py`, the new stall-dump +module and the three new test files (`"before": null` asserts that a file is new). +`tokenizer_manager.py` is the only file two patches touch (PR #30771, then shm-off-loop). Its +manifest entry spans both, and `PROVENANCE` records the hash between them. That disjointness was verified against the real base image, not assumed — all three patch targets hash identically in `3eccc307…` and in `e9d29a1c…`: @@ -54,13 +159,26 @@ hash identically in `3eccc307…` and in `e9d29a1c…`: 6ffd1584f6bcbbd3384f1ec45e3313a7b4b010fd3f900b8f19345d4b02f5d0ba managers/scheduler.py ``` -`apply-patches.py` re-checks every before-hash at build time, runs `git apply --check` first, -re-checks every after-hash, and `ast.parse`s each patched file, so a base drift fails the build -rather than producing a silently different image. +The event-loop targets were checked the same way in `3eccc307…` (2026-09-25). They are +byte-identical to fc91d24, and the four new paths do not exist there: + +``` +3d0613b92abae51e8566a11ae80a2369a46422b49bd63c4cd6aa593d8a4bdbc2 entrypoints/openai/serving_base.py +cc4d633d8c609300e095a16ef7fe460e2c3c0e0ad52fcc76e9134d0aee4dff51 managers/tokenizer_manager.py +553e5d1108dfded05e1693f7a26efd733e297b9ef7b238905e09e52a5e848652 entrypoints/http_server.py +``` + +`apply-patches.py` re-checks every before-hash at build time, then checks each patch with +`git apply --check` against the tree the previous patches left and applies it, in `PATCHES` order, +because `shm-off-loop.diff` edits lines that `sglang-pr30771.diff` adds. It then re-checks every +after-hash and `ast.parse`s each patched file, so a base drift fails the build rather than +producing a silently different image. ## Runtime -Nothing added here is switched on by default. Inherited opt-ins: +Added here: the DSA indexer query split is opt-in (`SGLANG_DSA_INDEXER_QSPLIT=1`), the two +event-loop patches have no switch, and the stall dump is on at 30 s +(`SGLANG_EVENT_LOOP_STALL_DUMP_SECS=0` turns it off). Inherited opt-ins: - admission reserve — `SGLANG_CHUNKED_PREFILL_ADMISSION_RESERVE` (never set `SGLANG_ADMISSION_RESERVE_MIN_WAIT_S`: the wall-clock gate desynchronises TP ranks and @@ -88,3 +206,9 @@ Two interactions to measure rather than assume: tier would have served, so the hit-rate lift may be small. 2. **Host RAM budget.** `SGLANG_HICACHE_RAM_BUDGET` defaults to `80%` and was sized against the fp8 device pool. It is not obviously right for a 2.43× larger one. + +**v3** (the event-loop patches and the stall dump) was run as a recipe against its base in a +CPU-only container: `apply-patches.py`, then `test-cpu.sh` steps 1-7. On GPU the lab bind-mounted +the same source bytes over the v1 image, all three patches together with the stall dump at its 30 s +default. No v3 build has run on GPU, so the published image first does so as the long-context r2 +canary. diff --git a/docker/sglang-glm53-hicache-w4afp8/SHA256SUMS b/docker/sglang-glm53-hicache-w4afp8/SHA256SUMS index ef01f72f..ffe2d5c0 100644 --- a/docker/sglang-glm53-hicache-w4afp8/SHA256SUMS +++ b/docker/sglang-glm53-hicache-w4afp8/SHA256SUMS @@ -1,8 +1,12 @@ -49c6fd3ef72c0bed3991b325361cd2245ed27a3a946a92b95cd9c562ff45585e PROVENANCE -a53f708e6d5e3ca08b4d0c7d8b427b551346d1a1fca702e6325a08e3b6078e7c README.md +720fd00c13ba60c6f01c1de5009772104da5a44fc8ed0429f01502fab9d17b38 PROVENANCE +39cd462e48cd826952051f9cd1568aa65ff9821d1c2266dcc3b9fa65c7a2f4ab README.md 29764baa3e464d2272ea85f2e254392c2a61a3fc61a51f8d33b5910ce0cd8d00 modules-to-not-convert.diff ba911be688556df0c0b2c9a26cde4c9f38b410a5ba51020d7754fa2e8cd010c3 chunked-prefill-pool-clamp.diff 37ad31b95511a831038d2ab572656a59d4ba1c9c21348d9fcb0095cba665aad1 dsa-indexer-qsplit.diff -2ec18422607acea743a9a6f3d03d7b544e7caa5c3f8f7b987703bd22eb71ec65 source-manifest.json -9f5eaf2742802024b40f001abc0cc8744a067b57ab6c1149c82fb3d0dd59fcbc apply-patches.py -64765443dc75c50b602f167a25d0c4c834e0d2a807b33b2ef8c95639d4a7ea69 test-cpu.sh +a102977de7bb02776cee1053ff04979b740526fe99c59d2c63e2f3962df3c95d sglang-pr30771.diff +4bd4cc65d68deacd1b56b95e32a2242853d20bd3cfa4188e8c1a20777cc79a94 shm-off-loop.diff +367dbcdec432586ae4c8ab984c08caafb2f148d62cebf257d12e89c4c32f72ab event-loop-stall-dump.diff +38e1f69012f6371660b46f3ab7c9c225eb28ef818d13f78c32cabe78d6aaa1b7 source-manifest.json +d28d5ddecf31d5051ffa3ae6b4f7907244e79bc23d98462212378aba01f005bf apply-patches.py +1603019a8905f8a8ca1e08cc4df62c12ea6a01ae8041305dea8842b42c3d72c8 test-cpu.sh +59cf2daae55e46b4f597f004ca647e235bcea41de4d6485dc386c98b5e088abb test_stall_dump.py diff --git a/docker/sglang-glm53-hicache-w4afp8/apply-patches.py b/docker/sglang-glm53-hicache-w4afp8/apply-patches.py index e22d0d07..14ed5d63 100644 --- a/docker/sglang-glm53-hicache-w4afp8/apply-patches.py +++ b/docker/sglang-glm53-hicache-w4afp8/apply-patches.py @@ -1,4 +1,5 @@ -"""Apply the reviewed W4AFP8 loader, pool-clamp and DSA indexer query-split patches to exact production source bytes.""" +"""Apply the reviewed W4AFP8 loader, pool-clamp, DSA indexer query-split, event-loop offload and +event-loop stall-dump patches to exact production source bytes.""" import ast import hashlib @@ -13,6 +14,10 @@ "modules-to-not-convert.diff": "29764baa3e464d2272ea85f2e254392c2a61a3fc61a51f8d33b5910ce0cd8d00", "chunked-prefill-pool-clamp.diff": "ba911be688556df0c0b2c9a26cde4c9f38b410a5ba51020d7754fa2e8cd010c3", "dsa-indexer-qsplit.diff": "37ad31b95511a831038d2ab572656a59d4ba1c9c21348d9fcb0095cba665aad1", + "sglang-pr30771.diff": "a102977de7bb02776cee1053ff04979b740526fe99c59d2c63e2f3962df3c95d", + # Stacked on sglang-pr30771.diff: it edits lines that diff adds, so the order here matters. + "shm-off-loop.diff": "4bd4cc65d68deacd1b56b95e32a2242853d20bd3cfa4188e8c1a20777cc79a94", + "event-loop-stall-dump.diff": "367dbcdec432586ae4c8ab984c08caafb2f148d62cebf257d12e89c4c32f72ab", } MANIFEST: Final = json.loads((CONTEXT / "source-manifest.json").read_text()) @@ -34,14 +39,14 @@ def digest(path: Path) -> str | None: if digest(ROOT / name) != entry["before"]: raise PatchApplicationError(f"Unrecognized base source: {name}") +# Check each patch against the tree the previous patches left, then apply it. A stacked patch +# (shm-off-loop.diff on sglang-pr30771.diff) cannot be checked against the unpatched base. for patch_name in PATCHES: subprocess.run( ["git", "apply", "--check", str(CONTEXT / patch_name)], cwd=ROOT, check=True, ) - -for patch_name in PATCHES: subprocess.run(["git", "apply", str(CONTEXT / patch_name)], cwd=ROOT, check=True) for name, entry in MANIFEST.items(): diff --git a/docker/sglang-glm53-hicache-w4afp8/event-loop-stall-dump.diff b/docker/sglang-glm53-hicache-w4afp8/event-loop-stall-dump.diff new file mode 100644 index 00000000..61c0eb18 --- /dev/null +++ b/docker/sglang-glm53-hicache-w4afp8/event-loop-stall-dump.diff @@ -0,0 +1,156 @@ +diff --git a/python/sglang/srt/entrypoints/http_server.py b/python/sglang/srt/entrypoints/http_server.py +index 18c865a..113bd17 100644 +--- a/python/sglang/srt/entrypoints/http_server.py ++++ b/python/sglang/srt/entrypoints/http_server.py +@@ -176,6 +176,7 @@ from sglang.srt.utils import ( + set_uvicorn_logging_configs, + ) + from sglang.srt.utils.auth import AuthLevel, app_has_admin_force_endpoints, auth_level ++from sglang.srt.utils.event_loop_stall_dump import install as install_stall_dump + from sglang.srt.utils.json_response import ( + SGLangORJSONResponse, + dumps_json, +@@ -389,6 +390,11 @@ async def lifespan(fast_api_app: FastAPI): + ) + logger.info("Warmup ended") + ++ # Diagnostic for the production hang where this process stopped answering /health for ++ # 14-155 min with no log line and no stack: if this event loop stops ticking, dump every ++ # thread's stack to stderr (SGLANG_EVENT_LOOP_STALL_DUMP_SECS, default 30, 0 disables). ++ install_stall_dump(asyncio.get_running_loop()) ++ + # Start the native gRPC server and warmup inside the try so a failure in + # either still runs the finally cleanup below. Native gRPC is enabled via + # --grpc-port / SGLANG_GRPC_PORT; only the single-tokenizer process is +diff --git a/python/sglang/srt/utils/event_loop_stall_dump.py b/python/sglang/srt/utils/event_loop_stall_dump.py +new file mode 100644 +index 0000000..6f7bcd0 +--- /dev/null ++++ b/python/sglang/srt/utils/event_loop_stall_dump.py +@@ -0,0 +1,126 @@ ++"""Dump every thread's stack when this process's asyncio event loop stops ticking. ++ ++Why: in production the `sglang serve` main process (tokenizer manager; its uvicorn loop serves ++/health, /metrics and /v1/chat/completions) stopped answering for 14-155 min and then recovered, ++with zero log lines and no way to attach py-spy. This makes the process say where it is stuck. ++A daemon thread watches a heartbeat that a task on the loop refreshes every second. After ++SGLANG_EVENT_LOOP_STALL_DUMP_SECS (default 30, 0 disables) without a tick it writes a header and ++every thread's stack to stderr, again every SGLANG_EVENT_LOOP_STALL_DUMP_REPEAT_SECS (default ++60), and one line on recovery. A single long C call that keeps the GIL (regex, JSON or pydantic ++on a multi-MB body) would starve that thread, so every tick also re-arms faulthandler's C ++watchdog, which dumps all stacks without the GIL ("Timeout (0:00:33)!") if the thread misses one. ++""" ++ ++import asyncio ++import faulthandler ++import logging ++import os ++import sys ++import threading ++import time ++import traceback ++ ++logger = logging.getLogger(__name__) ++_MARGIN = 3.0 # the GIL-free C dump only fires when the Python watcher is this late ++_detector = None ++ ++ ++def install(loop, stall_seconds=None, repeat_seconds=None, log_prefix="[event-loop-stall]"): ++ """Arm the detector for `loop`; call once, from the loop's own thread. Never raises.""" ++ global _detector ++ try: ++ if stall_seconds is None: ++ stall_seconds = float(os.environ.get("SGLANG_EVENT_LOOP_STALL_DUMP_SECS", 30)) ++ if repeat_seconds is None: ++ repeat_seconds = float(os.environ.get("SGLANG_EVENT_LOOP_STALL_DUMP_REPEAT_SECS", 60)) ++ if stall_seconds > 0 and _detector is None: ++ _detector = _Detector(loop, stall_seconds, max(repeat_seconds, 1.0), log_prefix) ++ logger.info( ++ f"event-loop stall dump armed: stall={stall_seconds:g}s" ++ f" repeat={_detector.repeat:g}s (pid {os.getpid()}," ++ f" loop thread 0x{_detector.ident:016x})" ++ ) ++ except Exception: ++ logger.warning("event-loop stall dump not armed", exc_info=True) ++ return _detector ++ ++ ++class _Detector: ++ def __init__(self, loop, stall, repeat, prefix): ++ self.loop, self.stall, self.repeat, self.prefix = loop, stall, repeat, prefix ++ self.ident = threading.get_ident() ++ self.cpu_clock = time.pthread_getcpuclockid(self.ident) # the loop thread's CPU time ++ self.beat, self.beat_cpu = time.monotonic(), time.clock_gettime(self.cpu_clock) ++ self.stopped = threading.Event() ++ self.task = loop.create_task(self._heartbeat()) ++ threading.Thread(target=self._watch, name="event-loop-stall-watch", daemon=True).start() ++ # A fork()-ed child that exits through normal interpreter shutdown hangs forever if it ++ # inherits an armed faulthandler timer, so disarm it around every fork() of this process. ++ os.register_at_fork( ++ before=faulthandler.cancel_dump_traceback_later, ++ after_in_parent=lambda: self.stopped.is_set() or self._arm_backstop(self.stall), ++ ) ++ ++ def _arm_backstop(self, seconds): ++ try: ++ faulthandler.dump_traceback_later(seconds + _MARGIN, file=2) ++ except Exception: ++ pass ++ ++ async def _heartbeat(self): ++ try: ++ while True: ++ self.beat, self.beat_cpu = time.monotonic(), time.clock_gettime(self.cpu_clock) ++ self._arm_backstop(self.stall) ++ await asyncio.sleep(1.0) ++ finally: ++ self.stopped.set() ++ faulthandler.cancel_dump_traceback_later() ++ ++ def _watch(self): ++ stalled_at, last_dump, dumps = None, 0.0, 0 # stalled_at: last beat before the stall ++ while not self.stopped.wait(1.0) and not self.loop.is_closed(): ++ try: ++ beat, now, pid = self.beat, time.monotonic(), os.getpid() ++ if stalled_at is not None and beat != stalled_at: ++ self._write([f"pid={pid} event loop recovered after {beat - stalled_at:.1f}s"]) ++ stalled_at = None ++ due = stalled_at is None or now - last_dump >= self.repeat ++ if now - beat > self.stall and due: ++ if stalled_at is None: # a new stall episode ++ stalled_at, dumps = beat, 0 ++ dumps, last_dump = dumps + 1, now ++ self._arm_backstop(self.repeat) # C dump only if we miss the next one ++ self._dump(pid, now - beat, dumps) ++ except Exception: ++ pass ++ ++ def _dump(self, pid, age, n): ++ frames = sys._current_frames() ++ try: ++ cpu = time.clock_gettime(self.cpu_clock) - self.beat_cpu ++ names = {t.ident: t.name for t in threading.enumerate()} ++ lines = [f"pid={pid} event loop stalled for {age:.1f}s (threshold {self.stall:g}s)," ++ f" dump {n}, {len(frames)} threads, loop thread used {cpu:.1f}s CPU since its" ++ f" last tick, {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}"] ++ for ident in sorted(frames, key=lambda i: i != self.ident): # loop thread first ++ role = " (event loop)" if ident == self.ident else "" ++ lines.append(f"--- thread 0x{ident:016x} {names.get(ident, '?')}{role}," ++ " most recent call last:") ++ for entry in traceback.format_stack(frames[ident], limit=200): ++ lines.extend(entry.rstrip("\n").split("\n")) ++ self._write(lines + [f"pid={pid} end of dump {n}"]) ++ except Exception: ++ self._write([f"pid={pid} stack formatting failed, raw faulthandler dump follows"]) ++ faulthandler.dump_traceback(file=2, all_threads=True) ++ ++ def _write(self, lines): ++ # One write per line: pipe writes up to 4 KiB are atomic, so lines of the other processes ++ # sharing this stderr never land inside ours, and every line carries the grep-able prefix. ++ for line in lines: ++ data = f"{self.prefix} {line}".encode("utf-8", "replace")[:4000] + b"\n" ++ try: ++ while data: ++ data = data[os.write(2, data):] ++ except OSError: ++ return diff --git a/docker/sglang-glm53-hicache-w4afp8/sglang-pr30771.diff b/docker/sglang-glm53-hicache-w4afp8/sglang-pr30771.diff new file mode 100644 index 00000000..5c1cf313 --- /dev/null +++ b/docker/sglang-glm53-hicache-w4afp8/sglang-pr30771.diff @@ -0,0 +1,490 @@ +diff --git a/python/sglang/srt/entrypoints/openai/serving_base.py b/python/sglang/srt/entrypoints/openai/serving_base.py +index 46a5d256b419..6145d607aee0 100644 +--- a/python/sglang/srt/entrypoints/openai/serving_base.py ++++ b/python/sglang/srt/entrypoints/openai/serving_base.py +@@ -88,9 +88,12 @@ async def handle_request( + if request_logger.log_requests and request_logger.log_requests_level >= 2: + request_logger.log_openai_received_request(request, request=raw_request) + +- # Convert to internal format +- adapted_request, processed_request = self._convert_to_internal_request( +- request, raw_request ++ # Chat template rendering and tokenization can block the event loop. ++ ( ++ adapted_request, ++ processed_request, ++ ) = await self.tokenizer_manager.run_in_request_preprocessor( ++ self._convert_to_internal_request, request, raw_request + ) + + if isinstance(adapted_request, (GenerateReqInput, EmbeddingReqInput)): +diff --git a/python/sglang/srt/managers/tokenizer_manager.py b/python/sglang/srt/managers/tokenizer_manager.py +index ea77294d2f88..bf91d6278dc2 100644 +--- a/python/sglang/srt/managers/tokenizer_manager.py ++++ b/python/sglang/srt/managers/tokenizer_manager.py +@@ -29,10 +29,12 @@ + import time + from array import array + from collections import deque ++from concurrent.futures import ThreadPoolExecutor + from contextlib import nullcontext ++from contextvars import copy_context + from datetime import datetime + from enum import Enum +-from functools import lru_cache ++from functools import lru_cache, partial + from http import HTTPStatus + from typing import Any, Awaitable, Dict, Iterable, List, Optional, Tuple, Union + +@@ -440,6 +442,9 @@ def __init__( + # Initialize tokenizer and multimodalprocessor + self.init_tokenizer_and_processor() + ++ # Initialize blocking request preprocessor ++ self.init_request_preprocessor() ++ + # Init inter-process communication + self.init_ipc_channels(port_args) + +@@ -555,6 +560,15 @@ def _validate_cuda_vmm_feature_transport_support(self) -> None: + f"{model_class.__name__}" + ) + ++ def init_request_preprocessor(self): ++ self._request_preprocessor_executor = ThreadPoolExecutor(max_workers=1) ++ ++ async def run_in_request_preprocessor(self, func, *args, **kwargs): ++ func_call = partial(copy_context().run, func, *args, **kwargs) ++ return await asyncio.get_running_loop().run_in_executor( ++ self._request_preprocessor_executor, func_call ++ ) ++ + def init_ipc_channels(self, port_args: PortArgs): + context = zmq.asyncio.Context(2) + self.recv_from_detokenizer = get_zmq_socket( +@@ -935,16 +949,22 @@ async def _tokenize_texts( + else: + logger.debug(f"Using regular tokenizer for {len(tokenizer_input)} inputs") + +- if not is_cross_encoder and (not getattr(self.tokenizer, "is_fast", False)): +- input_ids = [self.tokenizer.encode(t) for t in tokenizer_input] +- token_type_ids = None +- else: ++ def tokenize_sync(): ++ if not is_cross_encoder and ( ++ not getattr(self.tokenizer, "is_fast", False) ++ ): ++ return [self.tokenizer.encode(t) for t in tokenizer_input], None ++ + encoded = self.tokenizer(tokenizer_input, **tokenizer_kwargs) +- input_ids = encoded["input_ids"] +- token_type_ids = ( +- encoded.get("token_type_ids") if is_cross_encoder else None ++ return ( ++ encoded["input_ids"], ++ encoded.get("token_type_ids") if is_cross_encoder else None, + ) + ++ input_ids, token_type_ids = await self.run_in_request_preprocessor( ++ tokenize_sync ++ ) ++ + # vLLM's OpenAI embeddings endpoint includes special tokens for + # encoder models. EmbeddingGemma's restored Gemma tokenizer adds BOS + # but, by its checkpoint default, omits EOS. Add EOS explicitly here +diff --git a/test/registered/unit/entrypoints/openai/test_serving_base_event_loop.py b/test/registered/unit/entrypoints/openai/test_serving_base_event_loop.py +new file mode 100644 +index 000000000000..dfab863d359b +--- /dev/null ++++ b/test/registered/unit/entrypoints/openai/test_serving_base_event_loop.py +@@ -0,0 +1,100 @@ ++"""Event-loop responsiveness tests for OpenAI request preprocessing.""" ++ ++import asyncio ++import threading ++import unittest ++from types import SimpleNamespace ++ ++from sglang.test.test_utils import CustomTestCase, maybe_stub_sgl_kernel ++ ++maybe_stub_sgl_kernel() ++ ++from sglang.srt.entrypoints.openai.serving_base import OpenAIServingBase # noqa: E402 ++from sglang.srt.managers.tokenizer_manager import TokenizerManager # noqa: E402 ++from sglang.test.ci.ci_register import register_cpu_ci # noqa: E402 ++ ++register_cpu_ci(est_time=3, suite="base-a-test-cpu") ++ ++ ++class _BlockingServing(OpenAIServingBase): ++ def __init__(self, conversion_started, release_conversion): ++ tokenizer_manager = TokenizerManager.__new__(TokenizerManager) ++ if hasattr(tokenizer_manager, "init_request_preprocessor"): ++ tokenizer_manager.init_request_preprocessor() ++ tokenizer_manager.request_logger = SimpleNamespace( ++ log_requests=False, log_requests_level=0 ++ ) ++ tokenizer_manager.server_args = SimpleNamespace( ++ tokenizer_metrics_allowed_custom_labels=None, ++ ) ++ super().__init__(tokenizer_manager) ++ self.conversion_started = conversion_started ++ self.release_conversion = release_conversion ++ ++ def _request_id_prefix(self): ++ return "test-" ++ ++ def _convert_to_internal_request(self, request, raw_request=None): ++ self.conversion_started.set() ++ if not self.release_conversion.wait(timeout=5): ++ raise TimeoutError("test did not release request conversion") ++ return object(), request ++ ++ async def _handle_non_streaming_request( ++ self, adapted_request, request, raw_request ++ ): ++ return "ok" ++ ++ ++class TestServingBaseEventLoop(CustomTestCase): ++ def test_request_conversion_does_not_block_event_loop(self): ++ conversion_started = threading.Event() ++ loop_progressed = threading.Event() ++ release_conversion = threading.Event() ++ loop_was_starved = threading.Event() ++ conversion_did_not_start = threading.Event() ++ serving = _BlockingServing(conversion_started, release_conversion) ++ ++ def release_after_loop_progress(): ++ if not conversion_started.wait(timeout=2): ++ conversion_did_not_start.set() ++ release_conversion.set() ++ return ++ if not loop_progressed.wait(timeout=1): ++ loop_was_starved.set() ++ release_conversion.set() ++ ++ watchdog = threading.Thread(target=release_after_loop_progress) ++ watchdog.start() ++ ++ async def run_request_and_probe_loop(): ++ request = SimpleNamespace(stream=False) ++ request_task = asyncio.create_task( ++ serving.handle_request(request, object()) ++ ) ++ await asyncio.sleep(0) ++ loop_progressed.set() ++ return await request_task ++ ++ try: ++ result = asyncio.run(run_request_and_probe_loop()) ++ finally: ++ release_conversion.set() ++ watchdog.join(timeout=2) ++ executor = getattr( ++ serving.tokenizer_manager, "_request_preprocessor_executor", None ++ ) ++ if executor is not None: ++ executor.shutdown(wait=True) ++ ++ self.assertEqual(result, "ok") ++ self.assertFalse(conversion_did_not_start.is_set()) ++ self.assertFalse(watchdog.is_alive()) ++ self.assertFalse( ++ loop_was_starved.is_set(), ++ "synchronous request conversion blocked the API event loop", ++ ) ++ ++ ++if __name__ == "__main__": ++ unittest.main() +diff --git a/test/registered/unit/entrypoints/test_http_server_liveness.py b/test/registered/unit/entrypoints/test_http_server_liveness.py +new file mode 100644 +index 000000000000..109c2c7d339d +--- /dev/null ++++ b/test/registered/unit/entrypoints/test_http_server_liveness.py +@@ -0,0 +1,125 @@ ++"""ASGI integration coverage for HTTP liveness during request preprocessing.""" ++ ++import asyncio ++import threading ++import unittest ++from types import SimpleNamespace ++ ++import httpx ++ ++from sglang.test.test_utils import CustomTestCase, maybe_stub_sgl_kernel ++ ++maybe_stub_sgl_kernel() ++ ++from sglang.srt.entrypoints.http_server import app # noqa: E402 ++from sglang.srt.entrypoints.openai.serving_base import OpenAIServingBase # noqa: E402 ++from sglang.srt.managers.tokenizer_manager import TokenizerManager # noqa: E402 ++from sglang.test.ci.ci_register import register_cpu_ci # noqa: E402 ++ ++register_cpu_ci(est_time=5, suite="base-a-test-cpu") ++ ++ ++class _BlockingChatServing(OpenAIServingBase): ++ def __init__(self, conversion_started, release_conversion): ++ tokenizer_manager = TokenizerManager.__new__(TokenizerManager) ++ if hasattr(tokenizer_manager, "init_request_preprocessor"): ++ tokenizer_manager.init_request_preprocessor() ++ tokenizer_manager.request_logger = SimpleNamespace( ++ log_requests=False, log_requests_level=0 ++ ) ++ tokenizer_manager.server_args = SimpleNamespace( ++ tokenizer_metrics_allowed_custom_labels=None, ++ ) ++ super().__init__(tokenizer_manager) ++ self.conversion_started = conversion_started ++ self.release_conversion = release_conversion ++ ++ def _request_id_prefix(self): ++ return "test-" ++ ++ def _convert_to_internal_request(self, request, raw_request=None): ++ self.conversion_started.set() ++ if not self.release_conversion.wait(timeout=5): ++ raise TimeoutError("test did not release request conversion") ++ return object(), request ++ ++ async def _handle_non_streaming_request( ++ self, adapted_request, request, raw_request ++ ): ++ return {"status": "ok"} ++ ++ ++class TestHTTPServerLiveness(CustomTestCase): ++ def test_ping_responds_while_chat_preprocessing_is_blocked(self): ++ conversion_started = threading.Event() ++ ping_completed = threading.Event() ++ release_conversion = threading.Event() ++ ping_was_starved = threading.Event() ++ conversion_did_not_start = threading.Event() ++ serving = _BlockingChatServing(conversion_started, release_conversion) ++ ++ def release_after_ping(): ++ if not conversion_started.wait(timeout=2): ++ conversion_did_not_start.set() ++ release_conversion.set() ++ return ++ if not ping_completed.wait(timeout=1): ++ ping_was_starved.set() ++ release_conversion.set() ++ ++ watchdog = threading.Thread(target=release_after_ping) ++ watchdog.start() ++ ++ had_previous_serving = hasattr(app.state, "openai_serving_chat") ++ previous_serving = getattr(app.state, "openai_serving_chat", None) ++ app.state.openai_serving_chat = serving ++ ++ async def call_chat_and_ping(): ++ transport = httpx.ASGITransport(app=app) ++ async with httpx.AsyncClient( ++ transport=transport, base_url="http://test" ++ ) as client: ++ chat_task = asyncio.create_task( ++ client.post( ++ "/v1/chat/completions", ++ json={ ++ "model": "test-model", ++ "messages": [{"role": "user", "content": "hello"}], ++ }, ++ ) ++ ) ++ # Queue liveness before chat conversion gets its first event-loop turn. ++ ping_task = asyncio.create_task(client.get("/ping")) ++ ping_response = await ping_task ++ ping_completed.set() ++ chat_response = await chat_task ++ return ping_response, chat_response ++ ++ try: ++ ping_response, chat_response = asyncio.run(call_chat_and_ping()) ++ finally: ++ release_conversion.set() ++ watchdog.join(timeout=2) ++ executor = getattr( ++ serving.tokenizer_manager, "_request_preprocessor_executor", None ++ ) ++ if executor is not None: ++ executor.shutdown(wait=True) ++ if had_previous_serving: ++ app.state.openai_serving_chat = previous_serving ++ else: ++ delattr(app.state, "openai_serving_chat") ++ ++ self.assertEqual(ping_response.status_code, 200) ++ self.assertEqual(chat_response.status_code, 200) ++ self.assertEqual(chat_response.json(), {"status": "ok"}) ++ self.assertFalse(conversion_did_not_start.is_set()) ++ self.assertFalse(watchdog.is_alive()) ++ self.assertFalse( ++ ping_was_starved.is_set(), ++ "/ping was starved by synchronous chat request preprocessing", ++ ) ++ ++ ++if __name__ == "__main__": ++ unittest.main() +diff --git a/test/registered/unit/managers/test_tokenizer_manager_event_loop.py b/test/registered/unit/managers/test_tokenizer_manager_event_loop.py +new file mode 100644 +index 000000000000..ceeb8dd64763 +--- /dev/null ++++ b/test/registered/unit/managers/test_tokenizer_manager_event_loop.py +@@ -0,0 +1,153 @@ ++"""Event-loop responsiveness tests for TokenizerManager tokenization.""" ++ ++import asyncio ++import threading ++import types ++import unittest ++from contextvars import ContextVar ++ ++from sglang.test.test_utils import CustomTestCase, maybe_stub_sgl_kernel ++ ++maybe_stub_sgl_kernel() ++ ++from sglang.srt.managers.tokenizer_manager import TokenizerManager # noqa: E402 ++from sglang.test.ci.ci_register import register_cpu_ci # noqa: E402 ++ ++register_cpu_ci(est_time=3, suite="base-a-test-cpu") ++ ++ ++class _BlockingFastTokenizer: ++ is_fast = True ++ ++ def __init__(self, tokenization_started, release_tokenization): ++ self.tokenization_started = tokenization_started ++ self.release_tokenization = release_tokenization ++ ++ def __call__(self, texts, **kwargs): ++ self.tokenization_started.set() ++ if not self.release_tokenization.wait(timeout=5): ++ raise TimeoutError("test did not release tokenization") ++ return {"input_ids": [[1] for _ in texts]} ++ ++ ++class TestTokenizerManagerEventLoop(CustomTestCase): ++ def test_regular_tokenizer_does_not_block_event_loop(self): ++ tokenization_started = threading.Event() ++ loop_progressed = threading.Event() ++ release_tokenization = threading.Event() ++ loop_was_starved = threading.Event() ++ tokenization_did_not_start = threading.Event() ++ ++ manager = TokenizerManager.__new__(TokenizerManager) ++ manager.tokenizer = _BlockingFastTokenizer( ++ tokenization_started, release_tokenization ++ ) ++ manager.async_dynamic_batch_tokenizer = None ++ # `_tokenize_texts` consults model_config for the EmbeddingGemma EOS ++ # fix-up; this test builds a bare manager, so stub the flag it reads. ++ manager.model_config = types.SimpleNamespace(is_embedding_gemma=False) ++ if hasattr(manager, "init_request_preprocessor"): ++ manager.init_request_preprocessor() ++ ++ def release_after_loop_progress(): ++ if not tokenization_started.wait(timeout=2): ++ tokenization_did_not_start.set() ++ release_tokenization.set() ++ return ++ if not loop_progressed.wait(timeout=1): ++ loop_was_starved.set() ++ release_tokenization.set() ++ ++ watchdog = threading.Thread(target=release_after_loop_progress) ++ watchdog.start() ++ ++ async def tokenize_and_probe_loop(): ++ tokenize_task = asyncio.create_task(manager._tokenize_texts("hello")) ++ await asyncio.sleep(0) ++ loop_progressed.set() ++ return await tokenize_task ++ ++ try: ++ input_ids, token_type_ids = asyncio.run(tokenize_and_probe_loop()) ++ finally: ++ release_tokenization.set() ++ watchdog.join(timeout=2) ++ executor = getattr(manager, "_request_preprocessor_executor", None) ++ if executor is not None: ++ executor.shutdown(wait=True) ++ ++ self.assertEqual(input_ids, [1]) ++ self.assertIsNone(token_type_ids) ++ self.assertFalse(tokenization_did_not_start.is_set()) ++ self.assertFalse(watchdog.is_alive()) ++ self.assertFalse( ++ loop_was_starved.is_set(), ++ "synchronous tokenization blocked the API event loop", ++ ) ++ ++ @unittest.skipUnless( ++ hasattr(TokenizerManager, "init_request_preprocessor"), ++ "requires the request preprocessor executor", ++ ) ++ def test_request_preprocessing_is_serialized(self): ++ first_started = threading.Event() ++ release_first = threading.Event() ++ second_started = threading.Event() ++ manager = TokenizerManager.__new__(TokenizerManager) ++ manager.init_request_preprocessor() ++ ++ def first_call(): ++ first_started.set() ++ if not release_first.wait(timeout=5): ++ raise TimeoutError("test did not release first preprocessing call") ++ ++ def second_call(): ++ second_started.set() ++ ++ async def run_concurrent_calls(): ++ first_task = asyncio.create_task( ++ manager.run_in_request_preprocessor(first_call) ++ ) ++ started = await asyncio.to_thread(first_started.wait, 1) ++ self.assertTrue(started) ++ ++ second_task = asyncio.create_task( ++ manager.run_in_request_preprocessor(second_call) ++ ) ++ await asyncio.sleep(0.05) ++ self.assertFalse(second_started.is_set()) ++ ++ release_first.set() ++ await asyncio.gather(first_task, second_task) ++ ++ try: ++ asyncio.run(run_concurrent_calls()) ++ finally: ++ release_first.set() ++ manager._request_preprocessor_executor.shutdown(wait=True) ++ ++ self.assertTrue(second_started.is_set()) ++ ++ @unittest.skipUnless( ++ hasattr(TokenizerManager, "init_request_preprocessor"), ++ "requires the request preprocessor executor", ++ ) ++ def test_request_preprocessing_preserves_context(self): ++ request_context = ContextVar("request_context") ++ manager = TokenizerManager.__new__(TokenizerManager) ++ manager.init_request_preprocessor() ++ ++ async def read_context_from_preprocessor(): ++ request_context.set("request-value") ++ return await manager.run_in_request_preprocessor(request_context.get) ++ ++ try: ++ result = asyncio.run(read_context_from_preprocessor()) ++ finally: ++ manager._request_preprocessor_executor.shutdown(wait=True) ++ ++ self.assertEqual(result, "request-value") ++ ++ ++if __name__ == "__main__": ++ unittest.main() diff --git a/docker/sglang-glm53-hicache-w4afp8/shm-off-loop.diff b/docker/sglang-glm53-hicache-w4afp8/shm-off-loop.diff new file mode 100644 index 00000000..886199a3 --- /dev/null +++ b/docker/sglang-glm53-hicache-w4afp8/shm-off-loop.diff @@ -0,0 +1,69 @@ +Move the dispatch-time /dev/shm copy of multimodal features off the tokenizer manager's event loop. + +Applies to SGLang fc91d24 on top of upstream PR #30771 (sglang-pr30771.diff, which adds +TokenizerManager.init_request_preprocessor/run_in_request_preprocessor). Why: on the GLM-5.3 Flash +long tier, TokenizerManager._send_one_request -> mm_utils.wrap_shm_features -> ShmPointerMMData.__init__ +(posix_fallocate + copy_ of ~141 MiB per large image, 8.8-8.9 GiB per 64-image request) ran on the uvicorn +event loop and blocked /health for 3-5 s per image-heavy request (gpu32 lab phase 3a). The copy now runs in +its own single-thread executor ("sglang-mm-shm"), not the PR's preprocessor thread, so a multi-GiB copy +neither blocks the loop nor queues other requests' template rendering/tokenization behind it. If the +request is cancelled during the copy, its segments are unlinked once the copy finishes. +_send_batch_request has no wrap_shm_features call at fc91d24, so nothing changes there. + +diff --git a/python/sglang/srt/managers/tokenizer_manager.py b/python/sglang/srt/managers/tokenizer_manager.py +index 374f35d..a42c7ff 100644 +--- a/python/sglang/srt/managers/tokenizer_manager.py ++++ b/python/sglang/srt/managers/tokenizer_manager.py +@@ -95,7 +95,7 @@ from sglang.srt.managers.io_struct import ( + unwrap_from_pickle, + ) + from sglang.srt.managers.load_snapshot import create_load_snapshot_reader +-from sglang.srt.managers.mm_utils import wrap_shm_features ++from sglang.srt.managers.mm_utils import discard_shm_features, wrap_shm_features + from sglang.srt.managers.multimodal_processor import get_mm_processor, import_processors + from sglang.srt.managers.schedule_batch import ( + MultimodalDataItem, +@@ -560,6 +560,11 @@ class TokenizerManager(TokenizerControlMixin, TokenizerManagerScoreMixin): + + def init_request_preprocessor(self): + self._request_preprocessor_executor = ThreadPoolExecutor(max_workers=1) ++ # Own thread for the dispatch-time /dev/shm copy of multimodal features, so a ++ # multi-GiB copy does not queue behind (or delay) other requests' preprocessing. ++ self._shm_wrap_executor = ThreadPoolExecutor( ++ max_workers=1, thread_name_prefix="sglang-mm-shm" ++ ) + + async def run_in_request_preprocessor(self, func, *args, **kwargs): + func_call = partial(copy_context().run, func, *args, **kwargs) +@@ -567,6 +572,21 @@ class TokenizerManager(TokenizerControlMixin, TokenizerManagerScoreMixin): + self._request_preprocessor_executor, func_call + ) + ++ async def _wrap_shm_features_off_loop(self, tokenized_obj): ++ # wrap_shm_features creates one /dev/shm segment per feature tensor ++ # (posix_fallocate + copy_, both release the GIL). On the event loop this took ++ # 3-5 s for 64-image requests (~141 MiB per image) and stalled /health. ++ fut = asyncio.get_running_loop().run_in_executor( ++ self._shm_wrap_executor, wrap_shm_features, tokenized_obj ++ ) ++ try: ++ return await asyncio.shield(fut) ++ except asyncio.CancelledError: ++ # The copy cannot be interrupted and the request will not be dispatched: ++ # unlink its segments once it finishes (same FIFO thread), then re-raise. ++ self._shm_wrap_executor.submit(discard_shm_features, tokenized_obj) ++ raise ++ + def init_ipc_channels(self, port_args: PortArgs): + context = zmq.asyncio.Context(2) + self.recv_from_detokenizer = get_zmq_socket( +@@ -1593,7 +1613,8 @@ class TokenizerManager(TokenizerControlMixin, TokenizerManagerScoreMixin): + ) + ) + tokenized_obj.time_stats.set_api_server_dispatch_time() +- tokenized_obj = wrap_shm_features(tokenized_obj) ++ if tokenized_obj.mm_inputs: # without mm inputs the wrap is a no-op ++ tokenized_obj = await self._wrap_shm_features_off_loop(tokenized_obj) + time_stats = tokenized_obj.time_stats + tokenized_obj.wrap_pickle_fields() + self._dispatch_to_scheduler(tokenized_obj) diff --git a/docker/sglang-glm53-hicache-w4afp8/source-manifest.json b/docker/sglang-glm53-hicache-w4afp8/source-manifest.json index 1770419b..54a6f14c 100644 --- a/docker/sglang-glm53-hicache-w4afp8/source-manifest.json +++ b/docker/sglang-glm53-hicache-w4afp8/source-manifest.json @@ -1,4 +1,12 @@ { + "python/sglang/srt/entrypoints/http_server.py": { + "after": "0ea6fa2a3f9d7255957f2228748a0c6c83d06226c91e127e87af5b76871bded7", + "before": "553e5d1108dfded05e1693f7a26efd733e297b9ef7b238905e09e52a5e848652" + }, + "python/sglang/srt/entrypoints/openai/serving_base.py": { + "after": "e24b9de6fb2eeec1d3f75758e5287249d9b04780ba40b59ebdedabc0c51ad641", + "before": "3d0613b92abae51e8566a11ae80a2369a46422b49bd63c4cd6aa593d8a4bdbc2" + }, "python/sglang/srt/layers/attention/dsa/dsa_indexer_kpool.py": { "after": "6120351d2bc8447a4f670f007e3eb37ab79608266600f1b32f42bb08d64ae5c9", "before": "784b16cdd9c229dbda95c7b8d5685f9ef8f71dc5e2450de557814f1373bef42a" @@ -14,5 +22,25 @@ "python/sglang/srt/managers/scheduler.py": { "after": "6ffd1584f6bcbbd3384f1ec45e3313a7b4b010fd3f900b8f19345d4b02f5d0ba", "before": "6ffd1584f6bcbbd3384f1ec45e3313a7b4b010fd3f900b8f19345d4b02f5d0ba" + }, + "python/sglang/srt/managers/tokenizer_manager.py": { + "after": "1037bbac2e0183882e3f3c16d6be9492e047ff4b4ce4724f0baba9a3cd46cc4f", + "before": "cc4d633d8c609300e095a16ef7fe460e2c3c0e0ad52fcc76e9134d0aee4dff51" + }, + "python/sglang/srt/utils/event_loop_stall_dump.py": { + "after": "061b0aac60382eb21709dd3b5322c0b85a58121a8f3b405d09489d38506b2ecf", + "before": null + }, + "test/registered/unit/entrypoints/openai/test_serving_base_event_loop.py": { + "after": "109bbbd5a58dc65f99018c755ac7a62314d05395871f97877ed3f7a421a7435e", + "before": null + }, + "test/registered/unit/entrypoints/test_http_server_liveness.py": { + "after": "55d17fc5ae91cfb5304149470387ae437f975c3005865c62fe0417b0a14fd252", + "before": null + }, + "test/registered/unit/managers/test_tokenizer_manager_event_loop.py": { + "after": "05230e294a5b798128cf7009ab27bb5ca906eed617f40cbc8666e00b2c9ff083", + "before": null } } diff --git a/docker/sglang-glm53-hicache-w4afp8/test-cpu.sh b/docker/sglang-glm53-hicache-w4afp8/test-cpu.sh index 8794a01f..2129cd4c 100755 --- a/docker/sglang-glm53-hicache-w4afp8/test-cpu.sh +++ b/docker/sglang-glm53-hicache-w4afp8/test-cpu.sh @@ -1,5 +1,7 @@ #!/usr/bin/env bash set -euo pipefail +# Resolved before the cd: step 7 runs a test file shipped next to this script. +RECIPE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" cd /sgl-workspace/sglang # This pinned upstream test utility indexes the first visible-device digit. # Use an unavailable ordinal, with the CPU container's runtime set to runc. @@ -157,4 +159,163 @@ assert kpool._qsplit_group(2047) is None print("step 4 OK: the DSA indexer query split is opt-in and respects its minimum row count") EOF +# 5. Request preprocessing runs off the event loop (upstream sglang PR #30771): chat template +# rendering and tokenization in _convert_to_internal_request, and the regular-tokenizer path of +# _tokenize_texts, run in the tokenizer manager's single request-preprocessor thread, so the uvicorn +# loop keeps answering /health during multi-MB requests. The pytest files are the PR's own tests, +# applied under test/registered/unit; on the stock files three of them fail and two are skipped. +python3 - <<'EOF' +import inspect + +from sglang.test.test_utils import maybe_stub_sgl_kernel + +maybe_stub_sgl_kernel() + +from sglang.srt.entrypoints.openai.serving_base import OpenAIServingBase # noqa: E402 +from sglang.srt.managers.tokenizer_manager import TokenizerManager # noqa: E402 + +assert "run_in_request_preprocessor" in inspect.getsource(OpenAIServingBase.handle_request) +assert "run_in_request_preprocessor" in inspect.getsource(TokenizerManager._tokenize_texts) +assert "self.init_request_preprocessor()" in inspect.getsource(TokenizerManager.__init__) +EOF +python3 -m pytest -q -p no:cacheprovider \ + test/registered/unit/entrypoints/openai/test_serving_base_event_loop.py \ + test/registered/unit/entrypoints/test_http_server_liveness.py \ + test/registered/unit/managers/test_tokenizer_manager_event_loop.py +echo "step 5 OK: chat template rendering and tokenization run off the event loop (PR #30771 tests)" + +# 6. The dispatch-time /dev/shm copy of multimodal features (wrap_shm_features: posix_fallocate + +# copy_, ~141 MiB per large image) runs on its own sglang-mm-shm thread while the event loop keeps +# running, and a request cancelled during the copy still has its segments discarded afterwards. +python3 - <<'EOF' +import asyncio +import inspect +import threading +import time +from types import SimpleNamespace + +from sglang.test.test_utils import maybe_stub_sgl_kernel + +maybe_stub_sgl_kernel() + +import sglang.srt.managers.tokenizer_manager as tm # noqa: E402 + +send = inspect.getsource(tm.TokenizerManager._send_one_request) +assert "await self._wrap_shm_features_off_loop(tokenized_obj)" in send, send +assert "= wrap_shm_features(" not in send, send + +manager = tm.TokenizerManager.__new__(tm.TokenizerManager) +manager.init_request_preprocessor() +calls, release = [], threading.Event() + + +def blocking_wrap(obj): + calls.append(("wrap", threading.current_thread().name)) + if not release.wait(10): + raise TimeoutError("test did not release the copy") + return obj + + +def recording_discard(obj): + calls.append(("discard", threading.current_thread().name)) + + +# _wrap_shm_features_off_loop resolves both names in the module at call time. +tm.wrap_shm_features, tm.discard_shm_features = blocking_wrap, recording_discard + + +async def wait_for(condition): + for _ in range(500): + if condition(): + return + await asyncio.sleep(0.01) + raise AssertionError(f"timed out waiting; calls={calls}") + + +async def copy_while_loop_ticks(): + obj = SimpleNamespace(mm_inputs=object()) + task = asyncio.create_task(manager._wrap_shm_features_off_loop(obj)) + await wait_for(lambda: calls) + ticks, end = 0, time.monotonic() + 0.5 + while time.monotonic() < end: + await asyncio.sleep(0.01) + ticks += 1 + release.set() + assert await task is obj + return ticks + + +ticks = asyncio.run(copy_while_loop_ticks()) +assert ticks >= 20, f"the event loop ran only {ticks} times in 0.5 s while the copy was blocked" +assert [c[0] for c in calls] == ["wrap"] and calls[0][1].startswith("sglang-mm-shm"), calls + +calls.clear() +release.clear() + + +async def cancel_during_copy(): + task = asyncio.create_task(manager._wrap_shm_features_off_loop(SimpleNamespace(mm_inputs=object()))) + await wait_for(lambda: calls) + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + else: + raise AssertionError("cancellation did not reach the caller") + release.set() + await wait_for(lambda: len(calls) == 2) + + +asyncio.run(cancel_during_copy()) +manager._shm_wrap_executor.shutdown(wait=True) +manager._request_preprocessor_executor.shutdown(wait=True) +assert [c[0] for c in calls] == ["wrap", "discard"], calls +assert all(name.startswith("sglang-mm-shm") for _, name in calls), calls +print("step 6 OK: the multimodal shm copy runs off the event loop and a cancelled copy is discarded") +EOF + +# 7. The event-loop stall dump is armed from the HTTP server lifespan, before the warmup thread and +# before the lifespan yields, and importing it arms nothing. test_stall_dump.py then runs each +# scenario in its own child process: a loop blocked in time.sleep (uvloop and asyncio), a CPU spin, +# a C call that keeps the GIL (faulthandler's dump), fork() and a fork-context process pool, +# uvicorn + FastAPI with /health polled during a blocked request, the detector disabled with 0, and +# an invalid value. In the image it is on by default at 30 s; SGLANG_EVENT_LOOP_STALL_DUMP_SECS=0 +# disables it. +python3 - <<'EOF' +import inspect + +import sglang.srt.entrypoints.http_server as hs +import sglang.srt.utils.event_loop_stall_dump as stall + +assert list(inspect.signature(stall.install).parameters) == [ + "loop", + "stall_seconds", + "repeat_seconds", + "log_prefix", +] +assert hs.install_stall_dump is stall.install +lifespan = inspect.getsource(hs.lifespan) +hook, warmup, handoff = ( + lifespan.index(marker) + for marker in ( + "install_stall_dump(asyncio.get_running_loop())", + "warmup_thread = threading.Thread(", + "yield", + ) +) +assert hook < warmup < handoff, (hook, warmup, handoff) +assert stall._detector is None, "importing the module must not arm the detector" +EOF +stall_report="$(mktemp)" +if ! python3 -W ignore::DeprecationWarning "$RECIPE_DIR/test_stall_dump.py" \ + --module "$PWD/python/sglang/srt/utils/event_loop_stall_dump.py" \ + --out "$stall_report" > /dev/null; then + cat "$stall_report" + echo "step 7 FAILED: event-loop stall dump functional test" >&2 + exit 1 +fi +sed -n '/^SUMMARY/,$p' "$stall_report" +echo "step 7 OK: the event-loop stall dump reports blocked-loop stacks and recoveries, and stays off at 0" + echo "GLM-5.3 W4AFP8 combined-image CPU checks passed" diff --git a/docker/sglang-glm53-hicache-w4afp8/test_stall_dump.py b/docker/sglang-glm53-hicache-w4afp8/test_stall_dump.py new file mode 100644 index 00000000..1d6a131f --- /dev/null +++ b/docker/sglang-glm53-hicache-w4afp8/test_stall_dump.py @@ -0,0 +1,415 @@ +#!/usr/bin/env python3 +"""Functional test of event_loop_stall_dump (CPU only; stdlib plus the engine image's uvloop, +uvicorn and fastapi). Every scenario runs in its own child process, because faulthandler's +watchdog and the detector are both per process; the parent captures the child's stderr and +asserts on it. + + uvloop-sleep uvloop (the production loop); a coroutine blocks the loop with time.sleep(7) + asyncio-sleep the same on the stdlib asyncio loop + uvloop-spin a coroutine spins in pure Python for 7 s (CPU-bound; the GIL still switches) + uvloop-gil a coroutine sits 7 s in a C call that keeps the GIL (libc sleep through + ctypes.PyDLL), which starves every Python thread: only faulthandler's C + watchdog can dump, and the Python dump comes late + uvicorn uvicorn + FastAPI on uvloop like `sglang serve`; install() is called with no + arguments from the FastAPI lifespan (as the http_server.py hook does) and reads + the env vars; an async POST /v1/chat/completions blocks the loop with + time.sleep(7) while the parent polls GET /health every 200 ms + asyncio-fork fork() + a child exiting through interpreter shutdown, a fork-context + ProcessPoolExecutor (the multimodal CPU pool pattern), then a GIL-held block + with no await in between: the child must not hang on the inherited + faulthandler timer, and the at-fork re-arm must still produce the C dump + disabled SGLANG_EVENT_LOOP_STALL_DUMP_SECS=0: no watcher thread, no dump + bad-env SGLANG_EVENT_LOOP_STALL_DUMP_SECS=abc: one warning, nothing raised, no dump + +Usage: python3 test_stall_dump.py --module PATH/event_loop_stall_dump.py [--out FILE] +""" + +import argparse +import asyncio +import importlib.util +import logging +import os +import re +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time +import urllib.request + +BLOCK_S, AFTER_S = 7, 3 +PREFIX = "[event-loop-stall]" +T0 = time.monotonic() + + +def mark(msg): + os.write(2, f"[test +{time.monotonic() - T0:6.2f}s] {msg}\n".encode()) + + +def load(path): + spec = importlib.util.spec_from_file_location("event_loop_stall_dump", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +# ----------------------------------------------------------------------------- children +async def block_releasing_gil(): + time.sleep(BLOCK_S) # the loop thread blocks, the GIL is released + + +async def block_spinning(): + end = time.monotonic() + BLOCK_S + while time.monotonic() < end: # pure Python, CPU-bound + pass + + +async def block_holding_gil(): + import ctypes + + ctypes.PyDLL(None).sleep(BLOCK_S) # libc sleep() without releasing the GIL + + +async def fork_then_hold_gil(): + """fork() with a child that exits through full interpreter shutdown, then the multimodal CPU + pool pattern (fork-context ProcessPoolExecutor), then a GIL-held block. There is no await in + between, so only the at-fork re-arm (not the heartbeat) can have armed the C watchdog.""" + import concurrent.futures + import multiprocessing as mp + + sys.stdout.flush() + t = time.monotonic() + pid = os.fork() + if pid == 0: + sys.exit(0) # unwinds asyncio.run in the child, then Py_Finalize + while time.monotonic() - t < 5 and not os.waitpid(pid, os.WNOHANG)[0]: + time.sleep(0.01) + else: + if time.monotonic() - t >= 5: + os.kill(pid, signal.SIGKILL) + os.waitpid(pid, 0) + mark(f"FORK child {'HUNG, killed' if time.monotonic() - t >= 5 else 'exited'} after " + f"{time.monotonic() - t:.2f}s") + with concurrent.futures.ProcessPoolExecutor(2, mp_context=mp.get_context("fork")) as ex: + mark(f"POOL ok {list(ex.map(abs, [-1, -2, -3]))}") + await block_holding_gil() + + +def child_block(mod, loop_kind, blocker, env_install=False): + async def main(): + loop = asyncio.get_running_loop() + mod.install(loop) if env_install else mod.install(loop, 2, 2, PREFIX) + mark(f"loop={type(loop).__module__}.{type(loop).__name__} threads=" + f"{sorted(t.name for t in threading.enumerate())}") + await asyncio.sleep(1.5) + mark("BLOCK START") + await blocker() + mark("BLOCK END") + await asyncio.sleep(AFTER_S) + mark("CHILD EXIT") + + if loop_kind == "uvloop": + import uvloop + + uvloop.run(main()) + else: + asyncio.run(main()) + + +def child_uvicorn(mod, port): + from contextlib import asynccontextmanager + + import uvicorn + from fastapi import FastAPI + + @asynccontextmanager + async def lifespan(app): + mod.install(asyncio.get_running_loop()) # same call as the http_server.py hook + yield + mark("LIFESPAN SHUTDOWN") + + app = FastAPI(lifespan=lifespan) + + @app.get("/health") + async def health(): + return {"ok": True} + + @app.post("/v1/chat/completions") + async def chat_completions(): + mark("BLOCK START (request handler)") + time.sleep(BLOCK_S) # synchronous work on the loop, like the chat preprocessing + mark("BLOCK END") + return {"ok": True} + + uvicorn.run(app, host="127.0.0.1", port=port, loop="uvloop", log_level="warning") + + +# ----------------------------------------------------------------------------- parsing +def parse(err): + """Return (python dumps, faulthandler blocks, loop ident) from a child's stderr.""" + lines = err.splitlines() + m = re.search(r"loop thread (0x[0-9a-f]{16})", err) + ident = m.group(1) if m else None + dumps, cur = [], None + for i, line in enumerate(lines): + h = re.match(rf"{re.escape(PREFIX)} pid=\d+ event loop stalled for ([\d.]+)s .*dump (\d+), " + r"(\d+) threads, loop thread used ([-\d.na]+)s CPU", line) + if h: + cur = {"age": float(h.group(1)), "n": int(h.group(2)), "threads": int(h.group(3)), + "cpu": float(h.group(4)), "line": i, "sections": {}, "header": line} + sec = None + elif cur is not None and line.startswith(f"{PREFIX} --- thread"): + sec = line + cur["sections"][sec] = [] + elif cur is not None and re.match(rf"{re.escape(PREFIX)} pid=\d+ end of dump", line): + dumps.append(cur) + cur = None + elif cur is not None and sec is not None: + cur["sections"][sec].append(line[len(PREFIX) + 1:]) + blocks = [] + for i, line in enumerate(lines): + if line.startswith("Timeout ("): + secs, sec = {}, None + for nxt in lines[i + 1:]: + if nxt.startswith(("Thread 0x", "Current thread 0x")): + sec = nxt + secs[sec] = [] + elif nxt.startswith(" File ") and sec is not None: + secs[sec].append(nxt) + elif nxt.strip() == "": + continue + else: + break + blocks.append({"header": line, "line": i, "sections": secs}) + return dumps, blocks, ident, lines + + +def loop_section(dump): + for head, body in dump["sections"].items(): + if "(event loop)" in head: + return head, "\n".join(body) + return None, "" + + +def line_of(lines, pattern): + for i, line in enumerate(lines): + if re.search(pattern, line): + return i + return None + + +# ----------------------------------------------------------------------------- checks +def check_block(name, err, blocker, needle=None, expect_cpu_bound=False, gil_held=False): + dumps, blocks, ident, lines = parse(err) + res = [] + ok = lambda cond, what: res.append((bool(cond), what)) + ok(re.search(r"event-loop stall dump armed: stall=2s repeat=2s", err), "armed INFO line logged") + hit = [d for d in dumps if blocker in loop_section(d)[1]] + if not gil_held: + with_src = [d for d in hit if needle in loop_section(d)[1]] + ok(len(with_src) >= 2, f">=2 dumps whose event-loop thread stack shows {blocker} at " + f"'{needle}' (got {len(with_src)} of {len(dumps)} dumps)") + ok(dumps and 2.0 <= dumps[0]["age"] < 4.5, f"first dump after 2-4.5 s of stall (got " + f"{dumps[0]['age'] if dumps else None})") + ok(not blocks, f"no faulthandler C-watchdog block (the Python watcher kept up; got {len(blocks)})") + if expect_cpu_bound: + ok(dumps and all(d["cpu"] >= 0.5 * d["age"] for d in dumps), + "loop-thread CPU >= 50% of stall age in every dump (CPU-bound): " + + ", ".join(f"{d['cpu']:.1f}/{d['age']:.1f}s" for d in dumps)) + else: + ok(dumps and all(d["cpu"] < 0.5 for d in dumps), + "loop-thread CPU < 0.5 s in every dump (blocked, not spinning): " + + ", ".join(f"{d['cpu']:.1f}/{d['age']:.1f}s" for d in dumps)) + else: + loop_secs = [body for b in blocks for head, body in b["sections"].items() + if ident and ident in head] + ok(any(f" in {blocker}" in "\n".join(s) for s in loop_secs), + f"faulthandler C-watchdog block shows the loop thread {ident} in {blocker} " + f"({len(blocks)} block(s): {[b['header'] for b in blocks]})") + ok(dumps and dumps[0]["age"] >= BLOCK_S - 1.5, + f"Python watcher was starved while the GIL was held: its first dump came at " + f"{dumps[0]['age'] if dumps else None}s of stall, not ~2-3 s") + rec = line_of(lines, rf"{re.escape(PREFIX)} pid=\d+ event loop recovered after ([\d.]+)s") + ok(rec is not None, "'event loop recovered after N s' line present" + + (f": {lines[rec].split('] ', 1)[1]}" if rec is not None else "")) + if rec is not None: + after = [d for d in dumps if d["line"] > rec] + [b for b in blocks if b["line"] > rec] + ok(not after, "no dump after the recovery line") + return res, dumps, blocks + + +def check_uvicorn(err, health): + res, dumps, blocks = check_block("uvicorn", err, "chat_completions", needle="time.sleep(") + res = [r for r in res if "armed INFO" not in r[1]] + ok = lambda cond, what: res.append((bool(cond), what)) + ok(re.search(r"event-loop stall dump armed: stall=2s repeat=2s", err), + "armed INFO line logged from the FastAPI lifespan, values read from the env vars") + frames = "\n".join(loop_section(d)[1] for d in dumps) + ok(re.search(r"(starlette|fastapi)/", frames) and "uvicorn/" in frames, + "event-loop stack runs through uvicorn and starlette/fastapi frames") + during = [lat for lat in health if lat is not None] + worst = max(during) if during else None + ok(worst is not None and worst >= BLOCK_S - 2.5, + f"GET /health stalled while the loop was blocked (max latency {worst:.2f}s)" if worst + else "GET /health latencies recorded") + tail = health[-5:] + ok(tail and all(lat is not None and lat < 0.5 for lat in tail), + f"GET /health answers again after the stall (last 5: {[round(x, 3) for x in tail if x]})") + return res, dumps, blocks + + +# ----------------------------------------------------------------------------- parent +def run_child(args, extra_env=None): + """Start a child with stderr in a temp file (no pipe back-pressure on the timing).""" + env = dict(os.environ, **(extra_env or {})) + errf = tempfile.TemporaryFile(mode="w+") + p = subprocess.Popen([sys.executable, os.path.abspath(__file__), *args], env=env, + stdout=subprocess.DEVNULL, stderr=errf, text=True) + return p, errf + + +def finish(p, errf, timeout=120): + p.wait(timeout=timeout) + errf.seek(0) + return errf.read() + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def http(method, url, timeout): + t = time.monotonic() + try: + req = urllib.request.Request(url, method=method, data=b"{}" if method == "POST" else None) + urllib.request.urlopen(req, timeout=timeout).read() + return time.monotonic() - t + except Exception: + return None + + +def drive_uvicorn(module): + port = free_port() + env = {"SGLANG_EVENT_LOOP_STALL_DUMP_SECS": "2", "SGLANG_EVENT_LOOP_STALL_DUMP_REPEAT_SECS": "2"} + p, errf = run_child(["child-uvicorn", module, str(port)], env) + base = f"http://127.0.0.1:{port}" + deadline = time.monotonic() + 60 + while http("GET", base + "/health", 1) is None and time.monotonic() < deadline: + if p.poll() is not None: + break + time.sleep(0.2) + time.sleep(1.5) + health = [] + blocker = threading.Thread(target=http, args=("POST", base + "/v1/chat/completions", 30)) + blocker.start() + t_end = time.monotonic() + BLOCK_S + AFTER_S + 1 + while time.monotonic() < t_end: + t = time.monotonic() + health.append(http("GET", base + "/health", 15)) + time.sleep(max(0.0, 0.2 - (time.monotonic() - t))) + blocker.join() + p.send_signal(signal.SIGTERM) + err = finish(p, errf, timeout=60) + summary = (f"[parent] GET /health polled every 200 ms, {len(health)} probes; latencies (s): " + + " ".join(f"{lat:.2f}" if lat is not None else "timeout" for lat in health) + + f"\n[parent] child exit code after SIGTERM: {p.returncode}\n") + return err, health, summary, p.returncode + + +def check_fork(err): + res = check_block("", err, "block_holding_gil", gil_held=True)[0] + m = re.search(r"FORK child (exited|HUNG, killed) after ([\d.]+)s", err) + res.append((m is not None and m.group(1) == "exited" and float(m.group(2)) < 5, + "fork()-ed child exiting via full interpreter shutdown did not hang" + + (f" ({m.group(0)})" if m else ""))) + res.append(("POOL ok [1, 2, 3]" in err, "fork-context ProcessPoolExecutor ran and shut down")) + return res + + +def check_quiet(err, rc, bad_env): + dumps, blocks, _, _ = parse(err) + res = [(rc == 0, f"child exited 0 (got {rc})"), + (not dumps and not blocks, "no dump at all although the loop was blocked 7 s"), + ("event-loop-stall-watch" not in err, "no watcher thread was started"), + ("stall dump armed:" not in err, "no 'armed' line")] + if bad_env: + res.append(("event-loop stall dump not armed" in err and "ValueError" in err, + "a single 'not armed' warning (ValueError), nothing raised into the caller")) + return res + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--module", required=True) + ap.add_argument("--out") + a = ap.parse_args() + m = a.module + children = { # name: (child args, extra env, check) + "uvloop-sleep": (["child", m, "uvloop", "block_releasing_gil"], None, + lambda e: check_block("", e, "block_releasing_gil", needle="time.sleep(")[0]), + "asyncio-sleep": (["child", m, "asyncio", "block_releasing_gil"], None, + lambda e: check_block("", e, "block_releasing_gil", needle="time.sleep(")[0]), + "uvloop-spin": (["child", m, "uvloop", "block_spinning"], None, + lambda e: check_block("", e, "block_spinning", needle="in block_spinning", + expect_cpu_bound=True)[0]), + "uvloop-gil": (["child", m, "uvloop", "block_holding_gil"], None, + lambda e: check_block("", e, "block_holding_gil", gil_held=True)[0]), + "asyncio-fork": (["child", m, "asyncio", "fork_then_hold_gil"], None, check_fork), + "disabled": (["child-env", m, "uvloop", "block_releasing_gil"], + {"SGLANG_EVENT_LOOP_STALL_DUMP_SECS": "0"}, None), + "bad-env": (["child-env", m, "uvloop", "block_releasing_gil"], + {"SGLANG_EVENT_LOOP_STALL_DUMP_SECS": "abc"}, None), + } + started = {name: run_child(args, env) for name, (args, env, _) in children.items()} + uv_err, health, uv_summary, uv_rc = drive_uvicorn(m) + report = [] + for name, (p, errf) in started.items(): + err = finish(p, errf) + check = children[name][2] + if check is None: + res = check_quiet(err, p.returncode, bad_env=name == "bad-env") + else: + res = [(p.returncode == 0, f"child exited 0 (got {p.returncode})")] + check(err) + report.append((name, err, res, "")) + # uvicorn re-raises a captured SIGTERM after its graceful shutdown, so -15 is the normal code + res = [(uv_rc in (0, -signal.SIGTERM) and "LIFESPAN SHUTDOWN" in uv_err, + f"uvicorn child shut down gracefully on SIGTERM (lifespan exit ran, exit code {uv_rc})")] + report.append(("uvicorn", uv_err, res + check_uvicorn(uv_err, health)[0], uv_summary)) + + failures = 0 + text = [f"python {sys.version.split()[0]} | {sys.executable} | module {m}\n"] + for name, err, res, extra in report: + text.append(f"\n{'=' * 30} scenario {name} {'=' * 30}\n--- child stderr ---\n{err}") + text.append(extra) + text.append("--- checks ---\n") + for good, what in res: + failures += not good + text.append(f"{'PASS' if good else 'FAIL'} {what}\n") + total = sum(len(r) for _, _, r, _ in report) + text.append(f"\n{'=' * 70}\nSUMMARY: {total - failures} passed, {failures} failed\n") + for name, _, res, _ in report: + text.append(f" {name:14s} {'ok' if all(g for g, _ in res) else 'FAILED'}\n") + out = "".join(text) + sys.stdout.write(out) + if a.out: + with open(a.out, "w") as f: + f.write(out) + sys.exit(1 if failures else 0) + + +if __name__ == "__main__": + if len(sys.argv) > 1 and sys.argv[1] in ("child", "child-env"): + logging.basicConfig(level=logging.INFO, stream=sys.stderr, + format="[child %(asctime)s %(levelname)s] %(message)s") + mod = load(sys.argv[2]) + child_block(mod, sys.argv[3], globals()[sys.argv[4]], env_install=sys.argv[1] == "child-env") + elif len(sys.argv) > 1 and sys.argv[1] == "child-uvicorn": + logging.basicConfig(level=logging.INFO, stream=sys.stderr, + format="[child %(asctime)s %(levelname)s] %(message)s") + child_uvicorn(load(sys.argv[2]), int(sys.argv[3])) + else: + main()