Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
719402c
refactor(mori): move PD transfer control plane into transfer_worker
inkcherry Aug 24, 2026
b2308ba
fix(mori): address review on notify cleanup and SLA path
inkcherry Aug 25, 2026
70867b7
fix(mori): avoid terminal notification races
inkcherry Aug 25, 2026
0a77588
fix(mori): address minor review comments
inkcherry Aug 25, 2026
b516139
Merge remote-tracking branch 'upstream/main' into align-pd-failure-no…
jambow0320 Aug 26, 2026
21e48fa
align-pd-failure-notifi
jambow0320 Aug 27, 2026
fca052c
Drop conclude-once bookkeeping made redundant by per-room worker shar…
jambow0320 Aug 27, 2026
1a16e0a
modify nixl tests
jambow0320 Aug 27, 2026
fc10166
follow repo style rules
jambow0320 Aug 27, 2026
f0032ba
Merge branch 'main' into align-pd-failure-notifi
jambow0320 Aug 27, 2026
28a9339
Merge branch 'main' into align-pd-failure-notifi
jambow0320 Aug 27, 2026
3784e24
Drop the mori notify latch that the main merge resurrected
jambow0320 Aug 30, 2026
df4bc94
Bound the NIXL settle wait, and report a missing response count
jambow0320 Aug 30, 2026
92ed588
Merge remote-tracking branch 'upstream/main' into align-pd-failure-no…
jambow0320 Aug 30, 2026
e728e29
Trim the conclude_transfer docstring to the constraint
jambow0320 Aug 30, 2026
fd1987a
Log the prefill rank the missing-count warning already carried
jambow0320 Aug 30, 2026
d5a90f9
Merge branch 'main' into align-pd-failure-notifi
ShangmingCai Sep 1, 2026
94b605c
Resolve notify targets first, and settle handles on the failure path
jambow0320 Sep 2, 2026
c2db8eb
Merge branch 'main' into align-pd-failure-notifi
jambow0320 Sep 2, 2026
282dbcb
Merge branch 'main' into align-pd-failure-notifi
ShangmingCai Sep 3, 2026
79b9cd1
Merge branch 'main' into align-pd-failure-notifi
ShangmingCai Sep 3, 2026
6371c80
Merge branch 'main' into align-pd-failure-notifi
ShangmingCai Sep 5, 2026
ae63d89
Merge branch 'main' into align-pd-failure-notifi
ShangmingCai Sep 5, 2026
ca76734
Merge branch 'main' into align-pd-failure-notifi
ShangmingCai Sep 8, 2026
5223017
Merge branch 'main' into align-pd-failure-notifi
ShangmingCai Sep 9, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
239 changes: 223 additions & 16 deletions python/sglang/srt/disaggregation/common/conn.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,19 @@ def __post_init__(self):


class CommonKVManager(BaseKVManager):
# Wire layout of the prefill->decode terminal status message. The legacy
# layout (mooncake, and ascend which inherits it) is three untagged frames
# ``[room, status, prefill_rank]``; backends whose control socket also
# carries tagged messages prefix a tag frame and may append a reason:
# ``[tag, room, status, prefill_rank, reason]``.
kv_status_msg_tag: Optional[bytes] = None
kv_status_msg_carries_reason: bool = False

# Used by decode when the prefill reported Failed without a reason frame.
DEFAULT_PREFILL_FAILURE_REASON = (
"Failed to get kvcache from prefill instance, it might be dead"
)

def __init__(
self,
args: KVArgs,
Expand Down Expand Up @@ -223,7 +236,6 @@ def __init__(
self._socket_lock = threading.Lock()
self.failure_records: Dict[int, str] = {}
self.failure_lock = threading.Lock()

if self.disaggregation_mode == DisaggregationMode.PREFILL:
# When SGLANG_DISAGGREGATION_ALL_CP_RANKS_TRANSFER is True, all CP ranks
# participate in KV transfer; Otherwise only CP rank 0 sends.
Expand Down Expand Up @@ -253,6 +265,7 @@ def __init__(
self.bootstrap_timeout = envs.SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT.get()
elif self.disaggregation_mode == DisaggregationMode.DECODE:
self.enable_staging: bool = False
self._staging_handler = None
self.connection_pool: Dict[str, Dict[str, Union[str, int]]] = {}
self.connection_lock = threading.Lock()
self.required_prefill_response_num_table: Dict[int, int] = {}
Expand Down Expand Up @@ -344,26 +357,217 @@ def check_status(self, bootstrap_room: int) -> KVPoll:
return self.request_status[bootstrap_room]

def update_status(self, bootstrap_room: int, status: KVPoll):
if bootstrap_room not in self.request_status:
# Do not resurrect a cleared entry with Failed: once clear() has
# popped the room from request_status, any late update_status(Failed)
# (e.g. from abort()) must be a no-op. Otherwise a Failed entry could
# pollute a future request that reuses the same bootstrap_room.
if status == KVPoll.Failed:
return
self.request_status[bootstrap_room] = status
else:
if status == KVPoll.Failed:
self.request_status[bootstrap_room] = KVPoll.Failed
else:
self.request_status[bootstrap_room] = max(
self.request_status[bootstrap_room], status
)
current = self.request_status.get(bootstrap_room)
if current is None:
# The room does not exist yet, or clear() already popped it. Only a
# request's opening status may create it: Bootstrapping normally, or
# WaitingForInput for a dummy CP rank (see CommonKVSender.__init__).
# Anything else would resurrect a concluded room and pollute a later
# request that reuses the same bootstrap_room.
if status in (KVPoll.Bootstrapping, KVPoll.WaitingForInput):
self.request_status[bootstrap_room] = status
return
if status == KVPoll.Failed:
self.request_status[bootstrap_room] = KVPoll.Failed
return
if current == KVPoll.Failed:
# Failed is terminal. It also sorts lowest, so the max() below would
# happily promote it back to Transferring or Success.
return
self.request_status[bootstrap_room] = max(current, status)

def record_failure(self, bootstrap_room: int, failure_reason: str):
with self.failure_lock:
self.failure_records[bootstrap_room] = failure_reason

def _room_notify_targets(self, bootstrap_room: int) -> List[Tuple[str, int]]:
"""Every decode endpoint of a room that expects data from this rank.

A failure on one endpoint means the room is dead for all of them: the
other endpoints never receive the remaining chunks either, so telling
only the endpoint that raised leaves the rest waiting for the timeout.
"""
infos = getattr(self, "transfer_infos", {}).get(bootstrap_room)

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed, thanks! I also went through the PR again and cleaned up the code to make sure it follows the repo's rules.

if not infos:
return []
targets: List[Tuple[str, int]] = []
for info in list(infos.values()):
if info.is_dummy:
continue
target = (info.endpoint, info.dst_port)
if target not in targets:
targets.append(target)
return targets

def _encode_kv_status_message(
self,
bootstrap_room: int,
status: KVPoll,
failure_reason: Optional[str],
) -> List[bytes]:
parts = [
str(bootstrap_room).encode("ascii"),
str(int(status)).encode("ascii"),
str(self._prefill_unique_rank()).encode("ascii"),
]
if self.kv_status_msg_carries_reason:
parts.append((failure_reason or "").encode("utf-8"))
if self.kv_status_msg_tag is not None:
parts.insert(0, self.kv_status_msg_tag)
return parts

def parse_kv_status_message(
self, msg: List[bytes]
) -> Optional[Tuple[int, int, int, Optional[str]]]:
"""Decode a prefill status message, or None when it is not one."""
if self.kv_status_msg_tag is not None:
if not msg or msg[0] != self.kv_status_msg_tag:
return None
msg = msg[1:]
if len(msg) < 3:
logger.warning(
"Dropping malformed prefill status message with %d frames", len(msg)
)
return None
try:
bootstrap_room = int(msg[0].decode("ascii"))
status = int(msg[1].decode("ascii"))
prefill_rank = int(msg[2].decode("ascii"))
except (UnicodeDecodeError, ValueError):
logger.warning("Dropping unparsable prefill status message")
return None
failure_reason = (
msg[3].decode("utf-8", errors="replace")
if len(msg) > 3 and msg[3]
else None
)
return bootstrap_room, status, prefill_rank, failure_reason

def send_kv_status_message(
self,
targets: List[Tuple[str, int]],
bootstrap_room: int,
status: KVPoll,
failure_reason: Optional[str] = None,
) -> None:
"""Push of a terminal transfer status to decode endpoints."""
if not targets:
return
parts = self._encode_kv_status_message(bootstrap_room, status, failure_reason)
for endpoint, dst_port in targets:
na = NetworkAddress(endpoint, dst_port)
try:
self._send_multipart_locked(na.to_tcp(), parts, is_ipv6=na.is_ipv6)
except Exception as e:
logger.warning(
f"Failed to sync status {status} of room {bootstrap_room} to "
f"{na.to_host_port_str()}: {e}"
)

def conclude_transfer(
self,
bootstrap_room: int,
status: KVPoll,
targets: Optional[List[Tuple[str, int]]] = None,
failure_reason: Optional[str] = None,
) -> Optional[KVPoll]:
"""Mark a room's terminal status and push it to decode.

A Success requested after a failure was recorded is downgraded, so decode
never sees Success for a transfer that already broke. Returns the status
that was emitted, or None when the room had already been cleared.

Callers are transfer workers, and a room is sharded onto a single worker,
so this runs at most once per room without any at-most-once bookkeeping.

``targets`` defaults to every non-dummy decode endpoint of the room.
"""
if bootstrap_room not in self.request_status:
# The sender already cleared this room. Concluding now would
# re-create it in request_status and leave a failure record that a
# request reusing this bootstrap_room would adopt as its own.
return None
if status == KVPoll.Success:
with self.failure_lock:
recorded = self.failure_records.get(bootstrap_room)
if recorded is not None:
status = KVPoll.Failed
failure_reason = recorded
elif self.request_status.get(bootstrap_room) == KVPoll.Failed:
status = KVPoll.Failed
failure_reason = (
failure_reason or "Room marked Failed before the transfer ended"
)
if status == KVPoll.Failed:
with self.failure_lock:
# Keep the first root cause; later callers see the symptom.
failure_reason = self.failure_records.setdefault(
bootstrap_room, failure_reason or "KV transfer failed"
)

self.update_status(bootstrap_room, status)

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 move this after _room_notify_targets?We should postpone update_status incase there is a race for self.transfer_infos.get(bootstrap_room) and .clear()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. I also traced the incorrect ordering back to Mori's _notify_decode_for_room. When that logic was extracted into the common path, the same ordering was inadvertently propagated to all backends.

I've updated my local AGENTS.md and reviewed the PR again. For this kind of cross-backend refactoring, Mooncake should be treated as the reference implementation, since the other backends may already contain backend-specific inconsistencies or minor bugs.

if targets is None:
targets = self._room_notify_targets(bootstrap_room)
self.send_kv_status_message(targets, bootstrap_room, status, failure_reason)
return status

def conclude_failure(
self,
bootstrap_room: int,
failure_reason: str,
targets: Optional[List[Tuple[str, int]]] = None,
) -> Optional[KVPoll]:
"""Record the reason, mark the room Failed and tell decode."""
return self.conclude_transfer(
bootstrap_room, KVPoll.Failed, targets, failure_reason
)

def apply_prefill_status(
self,
bootstrap_room: int,
status: int,
prefill_rank: int,
failure_reason: Optional[str] = None,
) -> None:
"""Decode-side handling of one prefill rank's terminal status."""
if bootstrap_room not in self.request_status:
# The room concluded and was cleared. Recording a failure now would
# leave an entry that a later request reusing this bootstrap_room
# would pick up as its own root cause.
return
if status == KVPoll.Success:
self.prefill_response_tracker[bootstrap_room].add(prefill_rank)
expected_response_num = self.required_prefill_response_num_table.get(
bootstrap_room
)
if (
expected_response_num is None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

We might want to add a warning log here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed: split from the partial-response return and now warns.

or len(self.prefill_response_tracker[bootstrap_room])
< expected_response_num
):
return
# Tell the staging handler no more chunks are coming, before any
# poller can see Success. Only mooncake gets here: NIXL arms the
# handler from its own notifications, mori has no staging.
if self.enable_staging and self._staging_handler is not None:
handler = self._staging_handler
if handler.is_staging_room(bootstrap_room):
handler.submit_last_scatter_async(bootstrap_room)
self.update_status(bootstrap_room, KVPoll.Success)
return
if status == KVPoll.Failed:
self.record_failure(
bootstrap_room, failure_reason or self.DEFAULT_PREFILL_FAILURE_REASON
)
self.update_status(bootstrap_room, KVPoll.Failed)
return
logger.warning(
"Ignoring non-terminal status %s for room %s from prefill rank %s",
status,
bootstrap_room,
prefill_rank,
)

def register_deferred_abort_room(self, bootstrap_room: int) -> None:
"""Arm drain-ack accounting for a held room; a fresh set wipes stale acks
from a prior request that reused this bootstrap_room."""
Expand Down Expand Up @@ -1603,6 +1807,9 @@ def clear(self) -> None:
self.kv_mgr.request_status.pop(self.bootstrap_room, None)
self.kv_mgr.required_prefill_response_num_table.pop(self.bootstrap_room, None)
self.kv_mgr.prefill_response_tracker.pop(self.bootstrap_room, None)
self.kv_mgr.addr_to_rooms_tracker[self.bootstrap_addr].discard(
self.bootstrap_room
)

def abort(self):
self.kv_mgr.record_failure(
Expand Down
2 changes: 2 additions & 0 deletions python/sglang/srt/disaggregation/common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ class TransferKVChunk:
# Set when the staging worker first counts this chunk toward the per-room
# outstanding count; stays set across re-enqueue on a watermark defer.
staging_counted: bool = False
# Mori early-send: CUDA event to synchronize before RDMA (optional).
wait_event: Optional[object] = None


def pack_list_of_buffers(buffers: List[bytes]) -> bytes:
Expand Down
Loading
Loading