Skip to content

[Refactor] pd: Consolidate sender and receiver implementations - #41140

Merged
ShangmingCai merged 17 commits into
sgl-project:mainfrom
jambow0320:refactor/pd-receiver-control-send
Oct 24, 2026
Merged

ShangmingCai merged 17 commits into
sgl-project:mainfrom
jambow0320:refactor/pd-receiver-control-send

Conversation

@jambow0320

@jambow0320 jambow0320 commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Mooncake, NIXL, and Mori each implement their own KV sender / receiver lifecycle (sending, registration, metadata publication, polling, timeouts, cleanup, failure handling). The code is duplicated, and the backends are inconsistent in details such as failure-reason recording, terminal-state latching, and timeout trigger conditions.

NIXL determines transfer completion differently from the other two backends:

  • Mooncake / Mori: after all chunks have been written, prefill sends a status message to decode over ZMQ, and decode determines completion by counting prefill ranks.
  • NIXL: prefill attaches a notif string to every RDMA WRITE ({room}_kv_*, {room}_aux, {room}_state_*, {room}_stg_*, etc.). Decode calls agent.get_new_notifs() in NixlKVReceiver.poll() and uses TransferStatus to count, per PP rank, the arrival of chunks, parts, aux, and state to determine completion. Decode has to maintain a separate set of counting logic, and notifs are only read inside the receiver's poll().

This PR consolidates the sender / receiver lifecycle of the three backends into a common implementation, and switches NIXL completion notification to the same ZMQ mechanism used by Mooncake / Mori, no longer using NIXL notifs.

Refs: RFC #33861, Tracking #34510.

Modifications

1. NIXL switches to the same ZMQ completion mechanism as Mooncake and removes notifs

Prefill side

  • For each chunk, the transfer worker waits until all of its handles reach DONE before processing the next chunk. When the last chunk completes, it calls conclude_transfer(Success), which sends a KV_STATUS message to all non-dummy decode endpoints of the room. The failure path is the same as upstream: it sends KV_STATUS=Failed with the failure reason.
  • Staging path: after the handle of each staged write reaches DONE, a ZMQ CHUNK_READY is sent, sharing send_chunk_ready with Mooncake. Before the next peer reuses the prefill-side packing buffer, the worker likewise waits for that handle to complete. [Feat] [Intel] disaggregation: Support XPU for staging-buffer KV transfer #40861 added the same per-write wait only on XPU, where it observed KV corruption when the next decode rank's gather overwrote a staging buffer that was still being written. This PR waits on every device, so the XPU-only wait is removed.
  • NIXL transfer calls no longer pass a notif and no longer call send_notif.

Decode side

  • The listener thread handles four message types: KV_STATUS, CHUNK_READY, STAGING_REQ, and ABORT_ACK. KV_STATUS is counted per prefill rank via apply_prefill_status, and the room is set to Success once required_prefill_response_num is reached; CHUNK_READY is passed to the staging handler via handle_chunk_ready, shared with Mooncake.
  • The receiver's poll() only reads request_status and no longer calls get_new_notifs().

Removed

  • TransferStatus, update_transfer_status() and its notif parsing functions (_track_kv_arrival, _track_kv_part_arrival, _handle_stg_notification, _handle_aux_notification, _maybe_submit_last_scatter), and check_transfer_done().
  • transfer_source_rank, TransferKVChunk.chunk_id, the chunk counter in the sender, the chunk_id parameter of add_transfer_request, the NIXL manager's exceptions dict, and the receiver's started_transfer / expects_state.
  • The notif parameter of each NIXL send function.
  • The per-room {room}_state_{rank} notification added by [Perf] NIXL: prepared dlists for hybrid-model state transfer #44740, which made decode wait for every state component instead of counting the first component's notification. Decode now concludes only on KV_STATUS=Success, which prefill sends after every handle of the last chunk, including the prepared and generic state handles, has completed. The Decode expects state but prefill has none warning is removed with it, matching Mooncake, which skips the state transfer without a warning in that case.

Unchanged

2. Sender / receiver lifecycle consolidated into the common implementation

  • send, poll, poll_pp_consensus, clear, failure_exception, abort on the sender and _register_kv_args, send_metadata, clear, failure_exception, abort on the receiver are implemented in CommonKVSender / CommonKVReceiver. poll() and poll_pp_consensus() share _poll_with_status(), parameterized by check_status vs check_status_pp_consensus. The receiver's poll() uses the upstream common implementation.
  • Backend subclasses:
    • NixlKVSender, NixlKVReceiver, MooncakeKVReceiver, and MoriKVReceiver are empty subclasses.
    • MooncakeKVSender only keeps the trace decorator mooncake_trace_func on send and the supports_host_tensor_indices = True opt-in from [Perf] pd: Send prefill KV chunks without a host sync on the scheduler thread #45492.
    • MoriKVSender only keeps clear, which holds the Mori-specific _abort_ack_lock when deferred KV release is enabled.
  • Backend differences are provided through hooks on the manager:
    • build_receiver_registration_message() / build_receiver_metadata_message(): per-backend message encoding; the wire format is unchanged. Mooncake's device_kv_indices for DSV4 HiSparse is an explicit parameter of send_metadata() and of every builder; NIXL and Mori accept and ignore it.
    • prepare_send_state_indices(): returns the input unchanged by default; Mori uses it to skip CP-replicated state and to normalize per component.
    • sender_trace_module: set to "mooncake" by Mooncake, used to create the sender's trace context.
    • add_transfer_request(): unified across the three backends to 4 positional arguments plus keyword arguments wait_event, indices_event and trace_ctx, with each backend ignoring unused parameters. wait_event is used by Mooncake and Mori: both workers call wait_event.synchronize() before reading source KV, preserving Mooncake's existing path on main. NIXL currently ignores it; NIXL's wait_event support is handled by [Fix] disaggregation: Fix the early-send wait event on non-CUDA devices and in nixl #43299. indices_event is used only by Mooncake: CommonKVSender.send() forwards it, and the worker synchronizes on it before reading the pinned host indices ([Perf] pd: Send prefill KV chunks without a host sync on the scheduler thread #45492). trace_ctx is used only by Mooncake.
  • send_chunk_ready() / handle_chunk_ready() are moved to CommonKVManager and shared by Mooncake and NIXL.
  • The decode-side prefill_response_tracker changes from defaultdict(set) to a plain dict, with the entry created when the receiver is constructed. The listener thread only reads the entry, so a Success arriving after clear() does not re-create it.
  • _staging_ctx is declared on CommonKVManager with a default value of None.

Behavior Changes After Unification

NIXL protocol

  • Source of the completion signal: decode completion changes from counting RDMA notifications to counting KV_STATUS=Success messages sent by prefill ranks, matching Mooncake.

  • When Success is sent: Success is sent when all handles of the last chunk have completed. If an earlier staging chunk has been deferred due to insufficient staging space and is still queued:

    • the prefill sender returns Transferring while _staging_outstanding > 0, so the source KV is not released;
    • the decode staging handler only marks the request complete after all allocations have been scattered.

    This matches how Mooncake handles it. Before this change, NIXL decode relied on notif counting to wait for all chunks to arrive.

  • Staging deferral retry: when a chunk is deferred, the worker first waits for the writes already posted in the current round to complete, and then retries; previously it retried immediately without waiting for the posted handles. The retry still reprocesses all decode peers of the chunk, the same as before this change and as Mooncake.

  • Failure exception: the sender's failure_exception() raises KVTransferError, with the reason text taken from failure_records. Before this change, NIXL re-raised the original exception object caught in the worker, so the exception type and text format in scheduler logs change.

  • Abort received only by prefill: if an abort reaches only the prefill side while the last chunk's writes are in flight, prefill does not send Success, and decode does not complete the request. When prefill has already cleared the room, it sends no status, and decode fails the request after SGLANG_DISAGGREGATION_WAITING_TIMEOUT. This matches Mooncake. Before this change, NIXL decode counted all notifs once the writes landed and completed the request.

Sender (all three backends)

  • send() returns immediately once the sender has reached a terminal state (Success / Failed) and no longer enqueues. Before this change, Mooncake / Mori relied on the status check inside add_transfer_request, and NIXL relied on _send_failed, which was only set in failure_exception().
  • transfer_latency_s is still reported by the sender only for NIXL (reports_transfer_latency); Mooncake and Mori keep the metrics collector's last-chunk fallback, so sglang:kv_transfer_latency_ms and sglang:kv_transfer_speed_gb_s are unchanged for every backend.
  • failure_exception() clears the room before popping the failure reason, on both the sender and the receiver, as on main.
  • poll() returns Failed when the room is not in request_status. Before this change, Mooncake raised KeyError in this case and NIXL returned WaitingForInput. poll() writes conclude_state once it observes a terminal state; before this change NIXL did not latch it.
  • clear() saves the terminal state before removing manager state; cleanup of staging prefetch records (prefetched_rooms / prefetch_requested) is extended from NIXL to Mooncake.
  • aux_index and state_indices are only passed with the last chunk. Before this change NIXL passed them with every chunk, but the worker only read them on the last chunk, so behavior is unchanged.
  • When no failure reason was recorded locally, the default text of failure_exception() is unified as Failed due to an unknown reason from another rank, replacing NIXL KVSender Exception for NIXL and KV transfer failed for Mori.

Receiver (all three backends)

  • When bootstrap_infos is None, send_metadata() uniformly records a failure reason and sets the status to Failed. Before this change, NIXL only logged without recording a reason, and Mori returned directly.
  • send_metadata() raises NotImplementedError when given KVTransferDestination.HOST. None of the three backends implements host destinations; before this change, passing this argument raised TypeError due to a signature mismatch.
  • clear() writes conclude_state before removing manager state: a terminal state keeps its value, and a non-terminal state is recorded as Failed.
  • abort() can be called repeatedly and does not overwrite an already recorded failure reason when already Failed. Mori's abort() no longer immediately calls clear() and removes the failure reason: cleanup is done by failure_exception(), which the scheduler calls after the next poll() returns Failed, so reasons such as Aborted by AbortReq. are preserved. Before this change, Mori's failure reason was removed early, and failure_exception() could only report unknown reason from another rank.
  • When no failure reason was recorded locally, the default text of failure_exception() is unified, replacing NIXL KVReceiver Exception for NIXL and KV transfer failed for Mori.
  • The NIXL and Mori receivers switch to the upstream common poll(): after metadata is published, the waiting timeout is checked in the WaitingForInput state. Before this change, NIXL conditioned this on started_transfer and read notifs inside poll().
  • The bootstrap_room is None checks in the Mori receiver are removed. The scheduler already rejects disaggregation requests without a bootstrap_room on intake, except for the FAKE backend, which uses FakeKVReceiver.

Mooncake decode CHUNK_READY handling

  • Switches to the common handle_chunk_ready(): malformed messages are dropped after logging a warning; late messages for cleared rooms are dropped; a warning is logged when the staging handler is not initialized. Before this change these cases raised an exception and triggered an assert, respectively.

Wire compatibility

  • The registration, metadata, and status message formats of Mooncake and Mori are unchanged, and the registration and metadata message formats of NIXL are unchanged. Unit tests assert the registration and metadata messages of all three backends frame by frame.

Accuracy Tests

  • CPU unit tests test/registered/unit/disaggregation/ on the revision rebased onto main after [Test] cpu: prune mirror and tautology cases from the per-commit CPU suite #45672 pruned the suite: 359 passed, 298 subtests passed (14 cases that require CUDA were skipped).
  • Added and adjusted tests:
    • New test_common_sender_lifecycle.py:
      • the add_transfer_request argument contract of the three backends with two chunks, where aux_index and state_indices are only passed with the last chunk;
      • Mori's early-send event is handed to only one chunk, and CP-replicated state is skipped;
      • the sender's Success is held while a staging chunk is deferred;
      • poll_pp_consensus() concludes on the slowest PP stage while holding Success for outstanding deferred staging chunks;
      • the Mooncake trace context is passed to the worker and finished correctly.
    • Added to test_receiver_connection_pool.py:
    • test_nixl_backend_basic.py:
      • new tests for the NIXL ZMQ completion path: Success is sent only after the KV, aux, and state handles have all completed; Success is not sent when any handle fails; a deferred staging chunk still completes its transfer after the last chunk has sent Success;
      • a new test for the decode listener thread handling CHUNK_READY and KV_STATUS.
    • test_mooncake_transfer_batching.py: the early-send tests also assert that MooncakeKVSender.send() and MooncakeKVManager.add_transfer_request() carry indices_event onto the queued chunk.
    • Adaptations of upstream tests:
      • the helpers in test_mooncake_deferred_kv_release.py and test_nixl_deferred_kv_release.py drop chunk_id;
      • the fake agent in test_disaggregation_wire.py adds a default value for the notif parameter; the SWA state transfer test in test_disaggregation_wire.py and the prepared-state stride-mismatch test from [Perf] NIXL: prepared dlists for hybrid-model state transfer #44740 in test_nixl_backend_basic.py drop the removed notif argument.
  • The GPU results below were measured on the revision before the rebase onto current main (f5e25e52a7). The rebase adds the indices_event forwarding for [Perf] pd: Send prefill KV chunks without a host sync on the scheduler thread #45492 and removes the XPU-only staging wait from [Feat] [Intel] disaggregation: Support XPU for staging-buffer KV transfer #40861.
  • Single-node GPU end-to-end validation on 8× H200 with NIXL over UCX cuda_ipc and TCP, and Mooncake over TCP, on Qwen3-8B and Qwen3.6-27B: GSM8K accuracy differs from the baseline within run-to-run variation; at concurrency 1 the output tokens are bitwise identical to a non-PD deployment; the servers stay healthy with no KV leak after abort stress and failure injection.
  • Cross-node RDMA + staging end-to-end validation with NIXL:
    • Setup: prefill TP2 on one node and decode TP1 on a second node, with the staging buffer enabled (SGLANG_DISAGG_STAGING_BUFFER=1) on Qwen3-8B.
    • 2×8 H200 over InfiniBand with the UCX backend:
      • Greedy output tokens match the baseline on 18/18 prompts.
      • Full GSM8K accuracy is 0.9386 vs 0.9356 on the baseline.
      • Under abort stress, hung requests are 0, all /health endpoints return 200, all queue gauges return to 0, and there are no KV leaks or tracebacks. A subsequent GSM8K-200 run scores 0.96 on both versions.
    • 2×8 B300 over EFA with the LIBFABRIC backend:
      • Greedy output tokens on a 32k-token prompt match the baseline, and hardware RDMA write counters match the theoretical KV size of 4.832 GB.
    • Baseline hang fixes across both clusters:
      • B300 (EFA / LIBFABRIC): the baseline hung in 7 out of 10 launches, whereas this PR completed 100% of runs. On the last chunk, the baseline prefill transfer_worker posts send_kvcache_staged as a GPU VRAM RDMA write and immediately posts send_aux as a CPU DRAM RDMA write before waiting on _await_handles. Having an in-flight VRAM write and an in-flight DRAM write concurrently on the same worker causes the NIXL LIBFABRIC backend to intermittently stall. This PR waits for the staged KV write to finish and sends CHUNK_READY before calling send_aux, serializing the two writes and eliminating the hang.
      • H200 (InfiniBand / UCX): in 3 out of 3 runs at 16k input tokens and concurrency 32, the baseline left 1 request permanently stuck in the decode transfer queue, whereas this PR completed all 128/128 requests in every run. When the staging ring is saturated and chunks are deferred and re-enqueued, a non-last chunk can arrive at decode after the last chunk and aux notifications; the baseline only called _maybe_submit_last_scatter upon receiving the last chunk or aux notification, so the late arrival of an earlier chunk never triggered final completion. This PR marks transfer completion via KV_STATUS=Success and checks all chunk scatters in advance_scatter, eliminating this out-of-order deadlock.

Speed Tests and Profiling

Setup: a single node with 8× H200, Qwen3-8B, one prefill (TP1) and one decode (TP1) instance, NIXL backend (UCX). The baseline and this PR were run alternately, restarting the servers for every run, with random-token inputs and fixed output lengths.

  • TCP transport (UCX_TLS=tcp,cuda_copy): across loads with 2048–32768 input tokens and concurrency 1–128 (3 runs per version), no detectable difference in TTFT, ITL, or throughput.
  • NVLink transport (UCX cuda_ipc): at concurrency 1 with 2048 input and 4 output tokens (15 runs per version), mean TTFT increases by 0.99 ms (69.59 → 70.58 ms, +1.4%) and p99 TTFT by 1.21 ms. The added time is in transfer-completion detection: decode-side decode_transferred increases by about 1.1 ms and prefill-side prefill_transfer_kv_cache by about 0.6 ms, while prefill forward time is unchanged. At concurrency 16–256, no detectable difference was observed.
    • Decode-side ~1.1 ms increase: in the baseline, the decode scheduler thread calls agent.get_new_notifs() directly inside poll() to read NIC-delivered notifications from memory, which takes about 1 µs. In this PR, prefill sends KV_STATUS over ZMQ to the background decode_listener_thread blocked in recv_multipart(), which wakes both ZMQ I/O threads and the sleeping listener thread and hands off the Python GIL to the decode scheduler thread, taking about 1.0–1.3 ms per message.
    • Prefill-side ~0.6 ms increase: prefill_transfer_kv_cache measures the time from entering disagg_prefill_inflight_queue until the scheduler thread observes Success in sender.poll(). The synchronous ZMQ send in the transfer worker interacts with GIL scheduling against the prefill main thread, shifting when sender.poll() observes Success by roughly one scheduler iteration at concurrency 1; at concurrency 16–256 this is hidden by batch execution.

Cross-node RDMA + staging performance

Setup matches the cross-node validation above: prefill TP2 on one node, decode TP1 on a second node, default 4096 MB staging ring buffer, Qwen3-8B, alternating runs with full server restarts.

  1. Summary of results:

    • No end-to-end regression under normal or non-saturated loads: on H200 across low-concurrency and medium-context loads (2k–32k input at concurrency 1, and 4k input / 256 output at concurrency 32 and 128), as well as on B300 across all default-config loads, end-to-end TTFT, ITL, and throughput show no statistically significant difference from the baseline.
    • Prefill stage prefill_transfer_kv_cache increases by a fixed 0.2–0.4 ms per request at low concurrency: on H200 at concurrency 1, prefill_transfer_kv_cache increases by 0.24 ms at 2k input (7.31 → 7.54 ms) and by 0.38 ms at 32k input (31.20 → 31.59 ms); on B300 the last-chunk tail similarly increases by about 0.40 ms. Because this is a tiny fraction of total TTFT, end-to-end TTFT is unchanged.
    • Queuing amplification when the staging ring buffer is fully saturated: on H200 under a heavy load of 128 requests with 16k input tokens and 16 output tokens at concurrency 32, where the 4096 MB staging ring is continuously full and triggers ~524k chunk deferrals, prefill_transfer_kv_cache increases from 1460 ms to 1836 ms (+376 ms, +26%), decode_transferred increases from 9349 ms to 9551 ms, and mean TTFT increases from 9668 ms to 9870 ms (+2.1%). On B300, faster compute and EFA transfer keep the default staging buffer from saturating, so both versions perform identically; artificially shrinking the staging pool to fit only a single chunk reproduces the same saturation mechanism, increasing per-request ring wait time by 48% and deferral count by 72%.
  2. Root causes:

    • Why prefill_transfer_kv_cache increases by 0.2–0.4 ms per request:
      • On the last chunk of a staged transfer, the baseline posts send_kvcache_staged and send_aux together and waits for both in a single _await_handles call, hiding the small aux write behind the KV write, at the cost of the LIBFABRIC concurrent-write hang noted above.
      • To match Mooncake's staging flow safely, this PR serializes the last chunk: it first awaits the staged KV write, sends a synchronous ZMQ CHUNK_READY (~0.09 ms), then posts send_aux and runs a second _await_handles for aux completion (~0.30 ms on average including posting and waiting), and finally marks Success. Multi-chunk requests also pay ~0.10 ms per non-last chunk for synchronous CHUNK_READY sends.
    • Why saturation amplifies queuing delay:
      • When the staging ring is full, prefill cannot send the next chunk until decode scatters the previous chunk, retires its CUDA event in advance_scatter at the start of the decode loop, and sends back a ZMQ WATERMARK.
      • In the baseline, the decode main thread reads NIC-delivered RDMA notifications directly inside poll() via agent.get_new_notifs() and submits the scatter kernel immediately, taking 0.54 ms on average from prefill write completion to scatter submission. In this PR, prefill first observes write completion and sends ZMQ CHUNK_READY to decode's blocking decode_listener_thread; waking the background thread and acquiring the GIL under load takes 1.97 ms on average. Because the background thread can submit scatters while the decode main thread is inside run_batch, subsequent wait time until the next advance_scatter check is about 0.6 ms shorter than in the baseline, leaving a net turnaround increase of ~0.8–1.0 ms per staging slot.
      • When the ring is not full, freeing a slot ~0.8 ms later does not delay any waiting chunk. When 32 concurrent 16k-token requests saturate the ring so that arrival rate exceeds slot drain rate, 128 requests (384 chunks) queue behind each other; the ~1–2 ms slower slot turnaround per chunk accumulates across the backlog in disagg_prefill_inflight_queue, adding 376 ms to average queue residency while increasing end-to-end mean TTFT by 2.1%.
  3. Comparison with other backends and design trade-off:

    • Mooncake's staging path uses the exact same control-plane structure—synchronous write completion followed by ZMQ CHUNK_READY, background decode listener thread scatter submission, and KV_STATUS—and shares the same performance characteristics. Mori does not use a staging buffer and is unaffected.
    • This overhead is the inherent cost of replacing NIXL's private RDMA notification state machine with the shared ZMQ control plane used by Mooncake. Eliminating the ~1 ms background-thread wake-up latency would require re-introducing NIXL-specific notification paths or redesigning the shared staging threading model, which would add substantial complexity and work against the goal of unifying the three backends. Given that the unified implementation fixes both cross-node baseline hang bugs, has no end-to-end regression on normal workloads, and changes end-to-end TTFT by only ~2% under extreme staging saturation, we keep the simple, unified design.

Checklist

  • pre-commit checks passed (isort, ruff format, ruff check).
  • Added tests for the sender / receiver lifecycle, wire format, and NIXL completion ordering.
  • Re-run the two-process NIXL validation on the revision before the rebase onto current main.
  • Cross-node RDMA end-to-end validation and performance testing for NIXL (H200 InfiniBand and B300 EFA, including staging).

CI States

Latest PR Test (Base): ❌ Run #39944512143
Latest PR Test (Extra): ❌ Run #39944512107
Latest PR Test (AMD ROCm 10): ❌ Run #39944512192

@Lzy17 Lzy17 left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the PR. Items:

  1. Rebase. Main's Mooncake worker already calls wait_event.synchronize(). Keep that path in the unified send() and correct the "only Mori uses wait_event" statement.
  2. Agree the merge order with #38959 (poll_pp_consensus), #37358 (four new mori registration fields) and #40861 (NIXL wait_event accessor).
  3. Add cross-node RDMA, staging and mori/AMD validation; only single-node H200 is covered.
  4. Mooncake/mori transfer_latency_s is now measured from the first enqueue, which shifts nightly baselines. Please flag this to the nightly owners.

@jambow0320
jambow0320 force-pushed the refactor/pd-receiver-control-send branch from c4fa949 to 540545d Compare October 9, 2026 11:42
@jambow0320

Copy link
Copy Markdown
Contributor Author

@Lzy17 Thanks for the review! I have rebased onto the latest main and resolved the conflicts. Once #38959, #37358, and #40861 are merged, I will update this PR accordingly. For performance testing, I currently only have a single H200 node locally, so I will ask around whether someone can help run the tests. Finally, regarding transfer_latency_s, who specifically should I flag this to?

@Lzy17

Lzy17 commented Oct 14, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the rebase. I don't know of a specific owner for transfer_latency_s. It only feeds the sglang:kv_transfer_latency_ms and kv_transfer_speed_gb_s metrics, and I couldn't find anything in the repo that reads them. For mori this is a fix: it does not report the value today, so it falls back to timing only the last chunk. Please note the new measurement start (first enqueue) in the PR description so anyone with a dashboard on these metrics can see why the numbers move.

@jambow0320
jambow0320 force-pushed the refactor/pd-receiver-control-send branch from 540545d to 049050b Compare October 16, 2026 12:34
@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

Mooncake now consumes the early-send wait event in its worker, as Mori
does, so the shared send() comment names both. Drive the Mooncake
early-send case through a real MooncakeKVSender, since send() delegates
to CommonKVSender. Drop the removed chunk_id, notif and NIXL manager
fields from the invalidated-peer reload tests.
Mori registration now carries the DCP size and rank and the state and KV
layer ids, so the wire test expects those four frames. Drop the removed
chunk_id and NIXL notif arguments from the new Mooncake abort-ack and
heterogeneous-TP SWA tests. Cover poll_pp_consensus on the shared sender.
NIXL decode registration now carries the state pool data lengths for
prepared state transfers, so the wire test expects that frame. Drop the
removed notification argument from the new prepared-state rejection test.
The NIXL manager no longer has transfer_source_rank, the exceptions dict,
transfer statuses or check_transfer_done, and the receiver no longer has
started_transfer. Stop setting them on the fixtures, and drop the
update_transfer_status assertion that a MagicMock always satisfies.
…event

prefill.py passes indices_event to senders that set
supports_host_tensor_indices, and the Mooncake worker synchronizes on it
before reading the pinned indices. Assert that MooncakeKVSender.send and
MooncakeKVManager.add_transfer_request carry it onto the queued chunk.
CommonKVSender.__init__ always sets both fields, so clear() and
failure_exception() access them without getattr. The tests that build a
sender with __new__ now set conclude_state themselves.
CommonKVReceiver.send_metadata and every build_receiver_metadata_message
take device_kv_indices explicitly instead of forwarding **backend_kwargs.
Only Mooncake encodes it; NIXL and Mori accept and ignore it.
The registration and metadata builders return List[bytes], and the
metadata builder takes is_dummy per peer. send_metadata invalidates the
cached bootstrap infos itself when a send fails, so _send_bootstrap_message
uses operation only for the failure reason.
Comment on lines +2402 to +2403
with self.kv_mgr.failure_lock:
failure_reason = self.kv_mgr.failure_records.pop(self.bootstrap_room, None)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

maybe put pop after clear, that order seems more reasonable to me

Comment on lines +2901 to +2903
with self.kv_mgr.failure_lock:
failure_reason = self.kv_mgr.failure_records.pop(self.bootstrap_room, None)
self.clear()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

ditto

ShangmingCai and others added 2 commits October 23, 2026 18:37
…taking the failure reason

Only NIXL measured transfer_latency_s on the sender before the lifecycle
was shared; Mooncake and Mori used the last-chunk fallback in the metrics
collector. Gate the sender measurement behind reports_transfer_latency so
kv_transfer_latency_ms and kv_transfer_speed_gb_s keep their meaning for
every backend.

failure_exception() now clears the room before popping failure_records,
matching main. Popping first left the room live during clear(), so a late
Failed status or worker failure could re-record a reason under a room
that was about to be dropped and never be removed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The backend senders used to set init_time after the shared constructor
returned, so the bootstrap timeout window never included the DP-rank
registration call. Set it at the end of CommonKVSender.__init__ to keep
that window.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@ShangmingCai ShangmingCai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@ShangmingCai

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

@ShangmingCai ShangmingCai added the highest-priority CI: all three control labels, plus never batch-cancelled or stale-closed label Oct 23, 2026
@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Oct 23, 2026
@ShangmingCai ShangmingCai added the bypass-fail-fast CI: a failing job no longer aborts its siblings (lint still gates) label Oct 23, 2026
@ShangmingCai
ShangmingCai merged commit de7055f into sgl-project:main Oct 24, 2026
398 of 430 checks passed
kpjeeja added a commit to kpjeeja/sglang that referenced this pull request Oct 26, 2026
maybe_send_cached_prefix_chunk records a completion event on forward_stream and
attaches it to the sender so the transfer worker can wait for the prior step's
prefill writes before reading those prefix pages. Since sgl-project#41140 the shared
CommonKVSender.send passes it to add_transfer_request, but nixl's
add_transfer_request accepted wait_event and never put it on the queued chunk,
and its worker never waited, so the RDMA read raced the writes it was meant to
order against. SGLANG_DISAGG_PREFILL_EARLY_SEND_CACHED_PREFIX defaults to True,
so this is the default PD path.

The failure is silent: the transfer did move the bytes, they just were not final,
so decode reads partially written KV and only an output-quality check can catch
it.

nixl's add_transfer_request now carries the event on the TransferKVChunk, and
the worker waits the way mooncake's does: before the failed-room check and
before the staging gather, skipped for a room that already failed, and cleared
so a chunk re-enqueued on a watermark defer does not wait again. The wait is
the worker thread's first device call, so the thread binds to kv_args.gpu_id
before its first wait, as create_backend does; otherwise CUDA opens a context on
device 0 on every prefill rank not on GPU 0. The CommonKVSender.send comment now
lists nixl among the workers that synchronize on the event.

Adds tests that the mooncake worker waits before the staging gather, that the
nixl worker binds its device and waits before reading KV and before the staging
gather and skips the wait for a failed room, and that NixlKVSender.send hands
the event to the next queued chunk only.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bypass-fail-fast CI: a failing job no longer aborts its siblings (lint still gates) highest-priority CI: all three control labels, plus never batch-cancelled or stale-closed mooncake run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants