Skip to content

Instantly share code, notes, and snippets.

@ShangmingCai
Last active October 12, 2026 05:01
Show Gist options
  • Select an option

  • Save ShangmingCai/bdcfb3131b000a17810b4dca256d40cf to your computer and use it in GitHub Desktop.

Select an option

Save ShangmingCai/bdcfb3131b000a17810b4dca256d40cf to your computer and use it in GitHub Desktop.
Reproducing the PD-disaggregation KV slot-reuse race on 2xH200 over RDMA (SGLang v0.5.21, Mooncake): red run shows donor KV leaking into a victim's output; green run (deferred KV release, default) is byte-identical to baseline

Reproducing the PD-Disaggregation KV Slot-Reuse Race on Real Hardware

Companion to the blog post "Making KVCache Transfer Abort-Safe: Solving a Family of Slot-Liveness Issues in PD Disaggregation", specifically its Making It Deterministic section. This gist contains everything needed to reproduce, on live GPUs over real RDMA, both the corruption (hold disabled) and the fix (hold enabled, the shipped default).

The race in one sentence: when a request is aborted while its prefill→decode KVCache transfer is in flight, writes already launched to the NIC cannot be cancelled; if decode frees the destination slots at abort time and the allocator reassigns them, the dead request's KV lands inside another request's cache and silently corrupts its output.

Environment

Hardware 1 node, 2×NVIDIA H200, RDMA NICs (Mooncake auto-discovers; same-host PD runs RDMA loopback)
Software SGLang v0.5.21 (lmsysorg/sglang:latest), Mooncake transfer backend (Mooncake 0.3.13, the version bundled in that image)
Model Qwen/Qwen3-0.6B (small on purpose: fast startup, high decode TPS)
Topology 2 prefill engines (both on GPU 0) + 1 decode engine (GPU 1)

Why two prefill engines: Mooncake's prefill-side transfer queues are sharded by destination session, so with a single prefill, the victim's transfer serializes behind the donor's in-flight chunk on the same worker thread and always lands after the donor's late write, scrubbing it cell by cell. Two prefill engines sharing one decode break that serialization and let the late landing arrive out of order, as it would across a real fleet.

Files

  • patch_harness.py: patches the installed SGLang in place:
    • conn.py: an env-gated sleep in the Mooncake transfer worker, placed after the per-chunk abort/status check and before the RDMA submit. Past that check, the chunk is "launched": an ABORT arriving during the sleep cannot stop the write below from landing. SGLANG_TEST_SEND_KV_DELAY_S sets the hold; SGLANG_TEST_SEND_KV_DELAY_MIN_TOKENS=300 makes only the long donor prompt trigger it.
    • decode.py: warning-level logs for every PREALLOC (room, rid, slot range), FREE, HOLD (deferred release armed, required acks), and RESOLVE (drained vs timeout).
  • launch_pd2.sh red|green: launches the 2P1D stack. red exports SGLANG_DISAGGREGATION_DEFERRED_DECODE_KV_RELEASE=false (the pre-fix behavior); green leaves the hold on (the default since v0.5.21). Decode runs with --max-total-tokens 512 --num-reserved-decode-tokens 64 so slot reuse is immediate. The script is written so that it reproduces on every run: it waits for the previous engines to exit and deletes the old logs (otherwise a still-exiting engine keeps writing into the truncated log at its old offset, exp3.py misses the "held" line, and assert held fails); it starts prefill-2 only after prefill-1 is healthy (otherwise prefill-2 can claim GPU 0 memory first and prefill-1 exits with Raise --mem-fraction-static above 0.265); it pins a distinct --nccl-port per engine (the default random pick can collide between engines starting at once, EADDRINUSE); it exits with an error as soon as any engine dies during startup (instead of polling /health until a long timeout); and it returns only when all three engines answer /health.
  • exp3.py baseline | race red | race green: the driver. It bypasses the router and sends the same payload to a prefill engine and the decode engine with injected bootstrap_host/port/room (exactly what the PD load balancer does). This matters twice: a router may retry the aborted request, and the retry re-writes the freed slots with identical KV, masking the corruption; and the abort must be one-sided (posted to decode only) to model the race. It exits with ERROR instead of a verdict if a decode request fails, so a dead engine can never be mistaken for corruption, and also if the harness "held" line for A's own bootstrap room does not appear within 20 s (harness not applied, or engines not started by launch_pd2.sh).

The experiment

Donor A: a 430-token prompt via prefill-1 (its single KV chunk exceeds the 300-token threshold, so its launched write is held 0.45 s before the RDMA submit). Victim B: a ~100-token prompt via prefill-2 asking the model to count from 1 to 150, temperature=0, max_new_tokens=400, ignore_eos (so it is still decoding when the late write lands). The driver watches the prefill-1 log for the harness "held" line (proof the chunk is past the cancellable stage), then posts /abort_request for A to decode only, then immediately sends B.

Three timing/topology traps will silently mask the race if ignored (each cost us one clean-but-wrong "no repro"):

  1. Router retry: the aborted request gets re-sent and re-writes the same slots with the same KV. Bypass the router.
  2. Per-dst-session queue serialization: on 1P1D the victim's transfer lands after the donor's late write and scrubs it. Use 2 prefill engines.
  3. Victim lifetime: corruption only affects cells the victim wrote before the late landing; if the victim finishes decoding first, nothing shows. Size the delay so the landing falls mid-decode.

Red run (hold disabled): corruption, with the donor's content leaking into the victim

Decode-side slot trace (from the instrumentation):

[HARNESS] PREALLOC room=8596337577093805153 rid=rA_red kv_slots=[1..430] n=430
Decode transfer failed for request ... rid='rA_red' ... KVTransferError(...): Aborted by AbortReq.
[HARNESS] FREE room=8596337577093805153 rid=rA_red: kv slots returned to allocator
[HARNESS] PREALLOC room=6931021827077952974 rid=vB_red kv_slots=[1..105] n=105     <-- inside A's freed range

Prefill-1 side, same seconds:

[HARNESS] room 8596337577093805153: launched write of 430 tokens held 0.45s before RDMA submit
[HARNESS] room 8596337577093805153: submitting held RDMA write now                 <-- lands in B's live slots

(On later races against the same engines the held write is 429 tokens, because prefill-1's prefix cache already holds A's prompt; that is still above the 300-token threshold and still lands in B's slots.)

Victim output vs the temperature-0 baseline (first divergence at character 301):

baseline: ..., 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, ...
race:     ..., 78, 79, 80,
          Okay, so I need to figure out the pattern here. Let me start by writing
          the sequence one two three four five six seven eight nine ten one two ...

The victim was counting correctly until the late write landed, then derailed into the donor's prompt content ("one two three four five…" is request A's prompt). This is not generic garbage: it is the aborted request's KV being read back out of another request's generation, cross-request contamination made visible. Every component reported success; nothing raised.

Reproducibility. Verified from scratch on two different 2×H200 nodes, each time with a clean SGLang tree and the gist files fetched on the box: the How-to-run sequence, then 4 fresh launches × 10 races per mode. Across both nodes red mismatched the baseline in 80/80 races and green matched it byte for byte in 80/80 (every green abort resolved drained, none by timeout). The current scripts (with the fail-fast startup check and the per-room "held" match) were then re-run on a clean tree: the How-to-run sequence plus 2 launches × 10 races per mode, red 20/20 and green 20/20. In every race the victim was preallocated slots [1..105] inside the donor's [1..430]. The first divergence fell between characters 261 and 301. Every red run leaked the donor's one-to-ten cycle into the victim: usually A's exact words ("one two three four five…", sometimes after an "Okay, so I need to figure out the pattern" preamble), sometimes as digits ("1234567890…", "8 9 10 1 2 3…") or as the model reasoning about a sequence "repeating every 10 numbers".

Green run (hold enabled, the shipped default): byte-identical output

Identical timing, identical one-sided abort. Decode now holds instead of freeing:

[HARNESS] PREALLOC room=5364971304770933278 rid=rA_green kv_slots=[1..430] n=430
Decode transfer failed for request ... rid='rA_green' ... Aborted by AbortReq.
[HARNESS] HOLD room=5364971304770933278 rid=rA_green: release deferred, required_acks=1
[HARNESS] RESOLVE room=5364971304770933278: releasing now, outcome=drained         <-- ABORT_ACK after prefill drained
[HARNESS] FREE room=5364971304770933278 rid=rA_green: kv slots returned to allocator
[HARNESS] PREALLOC room=170924350370374013 rid=vB_green kv_slots=[1..105] n=105    <-- same slots, AFTER the landing

The victim waited out the hold (wall time 1.34 s vs 0.65 s baseline, and 1.05 to 1.11 s in the re-runs: the cost lands on the aborted path, not the steady state) and its output matched the baseline byte for byte. The slots were reused just the same; the only difference is when: after the positive drain signal, so the late write landed in quarantined memory that was never read.

How to run

# inside an sglang v0.5.21 container (lmsysorg/sglang:latest) with 2 GPUs
# if the default HF cache is read-only, point HF_HOME at a writable dir first
HF_HOME=/scratch/hf hf download Qwen/Qwen3-0.6B --local-dir /scratch/qwen3-0.6b
python3 patch_harness.py     # needs an unpatched tree; to undo: git -C /sgl-workspace/sglang checkout -- python/sglang/srt/disaggregation
./launch_pd2.sh red          # or: green
python3 exp3.py baseline
python3 exp3.py race red     # expect MISMATCH_BASELINE + donor-content leak
./launch_pd2.sh green
python3 exp3.py baseline
python3 exp3.py race green   # expect MATCH_BASELINE + HOLD/RESOLVE(drained) in decode log

The harness changes nothing about the protocol under test: the delay only widens the window that already exists, the abort is the stock /abort_request path, and the hold/ack/release behavior is the unmodified v0.5.21 mechanism toggled by its own environment variable.

import random, threading, time, sys, requests
from transformers import AutoTokenizer
PREFILL = "http://127.0.0.1:30100"
PREFILL2 = "http://127.0.0.1:30101"
DECODE = "http://127.0.0.1:30200"
tok = AutoTokenizer.from_pretrained("/scratch/qwen3-0.6b")
words = "one two three four five six seven eight nine ten "
ids = tok(words * 60)["input_ids"]
A_PROMPT = tok.decode(ids[:430])
B_FILLER = tok.decode(tok("red blue green yellow purple orange pink brown black white " * 12)["input_ids"][:72])
B_PROMPT = B_FILLER + " Ignore the colors above. Count from 1 to 150, separated by commas, nothing else. Begin: 1, 2, 3,"
def gen_pair(prompt, rid, max_new, timeout=180, prefill=PREFILL, bport=8998):
"""Send the same request to prefill and decode with matching bootstrap info
(what the PD LB does); return decode's response text."""
room = random.randint(0, 2**63 - 1)
payload = {
"text": prompt, "rid": rid,
"sampling_params": {"temperature": 0.0, "max_new_tokens": max_new, "ignore_eos": True},
"bootstrap_host": "127.0.0.1", "bootstrap_port": bport, "bootstrap_room": room,
}
results = {}
def post(url, side):
try:
r = requests.post(url + "/generate", json=payload, timeout=timeout)
results[side] = r
except Exception as e:
results[side] = e
tp = threading.Thread(target=post, args=(prefill, "p")); tp.start()
td = threading.Thread(target=post, args=(DECODE, "d")); td.start()
return tp, td, results, room
def wait_text(td, results, timeout=180):
td.join(timeout)
r = results.get("d")
if isinstance(r, Exception) or r is None:
sys.exit(f"ERROR: decode request failed: {r}")
body = r.json()
if "text" not in body:
sys.exit(f"ERROR: decode returned no text: {body}")
return body["text"]
mode = sys.argv[1]
if mode == "baseline":
t0 = time.time()
tp, td, res, _ = gen_pair(B_PROMPT, "baseB2", 400, prefill=PREFILL2, bport=8999)
out = wait_text(td, res)
print(f"BASELINE: {len(out)} chars, {time.time()-t0:.2f}s")
open("/tmp/baseline_B2.txt", "w").write(out)
print(repr(out[:160])); tp.join(10)
else:
tag = sys.argv[2]
with open("/tmp/prefill1.log", "rb") as f:
f.seek(0, 2); pos = f.tell()
tpa, tda, resa, room_a = gen_pair(A_PROMPT, "rA_" + tag, 8, timeout=60)
deadline = time.time() + 20
held = False
while time.time() < deadline:
with open("/tmp/prefill1.log", "rb") as f:
f.seek(pos); chunk = f.read().decode(errors="ignore")
if f"[HARNESS] room {room_a}: launched write" in chunk:
held = True; break
time.sleep(0.02)
print("launched-write hold observed:", held)
if not held:
sys.exit("ERROR: no [HARNESS] held line for A's room in /tmp/prefill1.log within 20s "
"(harness not applied, or prefill-1 not started by launch_pd2.sh?)")
r = requests.post(DECODE + "/abort_request", json={"rid": "rA_" + tag}, timeout=5)
print("one-sided abort posted to decode only:", r.status_code)
t0 = time.time()
tpb, tdb, resb, _ = gen_pair(B_PROMPT, "vB_" + tag, 400, prefill=PREFILL2, bport=8999)
out = wait_text(tdb, resb)
print(f"B wall {time.time()-t0:.2f}s")
open(f"/tmp/race_B2_{tag}.txt", "w").write(out)
base = open("/tmp/baseline_B2.txt").read()
print("VERDICT:", "MATCH_BASELINE" if out == base else "MISMATCH_BASELINE")
if out != base:
i = next((k for k in range(min(len(out), len(base))) if out[k] != base[k]), min(len(out), len(base)))
print(f"first divergence at char {i}")
print("base:", repr(base[i:i+200]))
print("race:", repr(out[i:i+200]))
else:
print(repr(out[:160]))
#!/bin/bash
# launch_pd2.sh red|green: 2P1D, two prefill engines on GPU0, decode on GPU1.
# Prefill-2 starts only after prefill-1 is healthy: started concurrently, prefill-2
# can claim GPU0 memory first and prefill-1 (mem-fraction 0.25) fails to fit its KV cache.
MODE=$1
pkill -f sglang.launch_server; pkill -f sglang_router
# Wait for the old engines to really exit, and start from fresh log files. A previous
# engine that is still shutting down keeps writing at its old offset into the truncated
# log, leaving a NUL-filled tail; exp3.py seeks to EOF, so it would then miss the
# "[HARNESS] ... held" line and fail `assert held`.
for i in $(seq 1 30); do pgrep -f "sglang.launch_server|sglang::" >/dev/null || break; sleep 1; done
pkill -9 -f "sglang.launch_server|sglang::"; sleep 2
rm -f /tmp/prefill1.log /tmp/prefill2.log /tmp/decode.log
if [ "$MODE" = red ]; then HOLD=false; else HOLD=true; fi
export SGLANG_DISAGGREGATION_DEFERRED_DECODE_KV_RELEASE=$HOLD
MODEL=/scratch/qwen3-0.6b
# Fixed, distinct --nccl-port per engine: the default random pick can collide when two
# engines start at once (EADDRINUSE in torch.distributed init kills one of them).
CUDA_VISIBLE_DEVICES=0 SGLANG_TEST_SEND_KV_DELAY_S=0.45 SGLANG_TEST_SEND_KV_DELAY_MIN_TOKENS=300 \
nohup python3 -m sglang.launch_server --model-path $MODEL \
--disaggregation-mode prefill --host 0.0.0.0 --port 30100 \
--disaggregation-bootstrap-port 8998 --mem-fraction-static 0.25 --nccl-port 31100 \
> /tmp/prefill1.log 2>&1 &
P1=$!
CUDA_VISIBLE_DEVICES=1 \
nohup python3 -m sglang.launch_server --model-path $MODEL \
--disaggregation-mode decode --host 0.0.0.0 --port 30200 \
--max-total-tokens 512 --num-reserved-decode-tokens 64 --mem-fraction-static 0.4 --nccl-port 31200 \
> /tmp/decode.log 2>&1 &
D=$!
# fail fast if an engine exits during startup instead of polling /health until the timeout
alive() { for p in "$@"; do kill -0 $p 2>/dev/null || { echo "an engine exited during startup; see /tmp/prefill1.log /tmp/prefill2.log /tmp/decode.log"; exit 1; }; done; }
for i in $(seq 1 120); do curl -sf -m 3 localhost:30100/health >/dev/null && break; alive $P1 $D; sleep 3; done
CUDA_VISIBLE_DEVICES=0 \
nohup python3 -m sglang.launch_server --model-path $MODEL \
--disaggregation-mode prefill --host 0.0.0.0 --port 30101 \
--disaggregation-bootstrap-port 8999 --mem-fraction-static 0.3 --nccl-port 31101 \
> /tmp/prefill2.log 2>&1 &
P2=$!
# block until all three engines answer /health, so exp3.py can run right after this script
for i in $(seq 1 200); do
n=0; for p in 30100 30101 30200; do curl -sf -m 3 localhost:$p/health >/dev/null && n=$((n+1)); done
[ $n = 3 ] && break; alive $P1 $P2 $D; sleep 3
done
if [ $n != 3 ]; then echo "only $n/3 engines healthy; see /tmp/prefill1.log /tmp/prefill2.log /tmp/decode.log"; exit 1; fi
echo "launched 2P1D mode=$MODE hold=$HOLD (all 3 engines healthy)"
"""Apply the deterministic-race test harness to the installed sglang 0.5.21."""
CONN = '/sgl-workspace/sglang/python/sglang/srt/disaggregation/mooncake/conn.py'
DEC = '/sgl-workspace/sglang/python/sglang/srt/disaggregation/decode.py'
s = open(CONN).read()
assert '[HARNESS]' not in s, 'conn.py already patched'
anchor = ' skip_kv, skip_state = self._get_dsa_cache_transfer_skip_flags('
assert s.count(anchor) == 1
ins = ''' # [HARNESS] env-gated: hold this launched chunk before the RDMA submit.
# Placed AFTER the abort/status check at the top of the loop, so the
# chunk is past the cancellable stage: an ABORT arriving during the
# sleep cannot stop the write below from landing.
_hd = float(os.environ.get("SGLANG_TEST_SEND_KV_DELAY_S", "0") or 0)
_hmin = int(os.environ.get("SGLANG_TEST_SEND_KV_DELAY_MIN_TOKENS", "300"))
if _hd > 0 and len(kv_chunk.prefill_kv_indices) >= _hmin:
logger.warning(f"[HARNESS] room {kv_chunk.room}: launched write of {len(kv_chunk.prefill_kv_indices)} tokens held {_hd}s before RDMA submit")
time.sleep(_hd)
logger.warning(f"[HARNESS] room {kv_chunk.room}: submitting held RDMA write now")
'''
s = s.replace(anchor, ins + anchor)
open(CONN, 'w').write(s)
print('conn.py patched')
d = open(DEC).read()
assert '[HARNESS]' not in d, 'decode.py already patched'
# 1. log the slot range handed to each room at prealloc
a1 = ''' dst_kv_indices = self._pre_alloc(
decode_req.req,
prefix_indices,
prefix_len,
total_prefix_len,
)'''
assert d.count(a1) == 1
d = d.replace(a1, a1 + '''
try:
logger.warning(f"[HARNESS] PREALLOC room={decode_req.req.bootstrap_room} rid={decode_req.req.rid} kv_slots=[{int(dst_kv_indices.min())}..{int(dst_kv_indices.max())}] n={dst_kv_indices.numel()}")
except Exception:
pass''')
# 2. log the actual free
a2 = ' release_kv_cache(decode_req.req, self.tree_cache, is_insert=False)'
assert d.count(a2) == 1
d = d.replace(a2, ''' logger.warning(f"[HARNESS] FREE room={decode_req.req.bootstrap_room} rid={decode_req.req.rid}: kv slots returned to allocator")
''' + a2)
# 3. log the hold decision
a3 = ''' self._deferred_releases.append(
(decode_req, deadline, decode_req.metadata_buffer_index, required_acks)
)'''
assert d.count(a3) == 1
d = d.replace(a3, a3 + '''
logger.warning(f"[HARNESS] HOLD room={decode_req.req.bootstrap_room} rid={decode_req.req.rid}: release deferred, required_acks={required_acks}")''')
# 4. log drained-vs-timeout at resolve
a4 = ' drained = kv_mgr.is_abort_release_safe(room, required_acks)'
assert d.count(a4) == 1
d = d.replace(a4, a4 + '''
if drained or now >= deadline:
logger.warning(f"[HARNESS] RESOLVE room={room}: releasing now, outcome={'drained' if drained else 'timeout'}")''')
open(DEC, 'w').write(d)
print('decode.py patched')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment