diff --git a/docs/distributed-cluster.md b/docs/distributed-cluster.md index 07ffe67bcb..e53d4b4bd3 100644 --- a/docs/distributed-cluster.md +++ b/docs/distributed-cluster.md @@ -75,6 +75,11 @@ KV cache stays on the rank that owns the corresponding layers. Centralizing KV on one Mac would add a network read/write to every layer and generated token, so it is not the default. +Each inference rank and synthetic performance worker also holds a kernel-owned +`flock` lease for the device. The lease releases automatically on crash or +SIGKILL, so it prevents cross-process races without creating a stale-lock +recovery problem. + ## Requirements On every Mac: diff --git a/omlx/admin/routes.py b/omlx/admin/routes.py index 479b00e104..0319dae6f7 100644 --- a/omlx/admin/routes.py +++ b/omlx/admin/routes.py @@ -14,8 +14,10 @@ import logging import os import re +import shlex import shutil import signal +import subprocess import sys import time from collections import deque @@ -63,6 +65,87 @@ PRESET_REMOTE_URL = "https://omlx.ai/assets/omlx_preset.json" +def _clear_cold_remote_cluster_cache_roots( + roots: tuple[Path, ...], + *, + runner: Any = subprocess.run, +) -> tuple[int, int]: + """Remove unloaded cluster snapshots from every configured peer Mac. + + Loaded ranks clear through their live cache managers. With no resident + engine, the normal SSD-clear action still has to reach peer-local snapshot + trees; deleting only the coordinator root makes the next load silently + restore data the user explicitly cleared. + """ + + from ..cluster.launch import _run_cluster_ssh + from ..cluster.registry import get_cluster_registry + + try: + deployments = get_cluster_registry().list() + except RuntimeError: + return 0, 0 + if not deployments: + return 0, 0 + + allowed = {"cluster-prompt-snapshots", "prompt-cache-ssd"} + if any(path.expanduser().name not in allowed for path in roots): + raise RuntimeError("refusing to clear an unexpected cluster cache root") + + node_ids: set[str] = set() + remote_targets: set[str] = set() + for deployment in deployments: + for rank, host in enumerate(deployment.hosts): + node_ids.add(host.node_id) + if rank > 0: + remote_targets.add(host.ssh) + + # Resolve settings on the peer. Sending the coordinator's expanded + # /Users//... roots breaks as soon as the Macs use different login + # names, data roots, or SSD-cache locations. + script = r""" +import shutil +from pathlib import Path +from omlx.settings import GlobalSettings +settings = GlobalSettings.load() +roots = [ + settings.cache.get_ssd_cache_dir(settings.base_path) / 'cluster-prompt-snapshots', + Path(settings.base_path) / 'cluster/runtime/prompt-cache-ssd', +] +allowed = {'cluster-prompt-snapshots', 'prompt-cache-ssd'} +if any(root.name not in allowed for root in roots): + raise SystemExit(3) +deleted = 0 +for root in roots: + if not root.exists(): + continue + deleted += sum(1 for item in root.rglob('*') if item.is_file()) + shutil.rmtree(root) +print(deleted) +""".strip() + command = shlex.join(["python3", "-c", script]) + deleted = 0 + for target in sorted(remote_targets): + completed = _run_cluster_ssh( + target, + command, + timeout=45.0, + runner=runner, + ) + if completed.returncode != 0: + detail = completed.stderr.strip() or completed.stdout.strip() + raise RuntimeError( + f"cold cluster SSD clear failed on {target}: {detail[:300]}" + ) + try: + deleted += max(0, int(completed.stdout.strip() or "0")) + except ValueError as exc: + raise RuntimeError( + f"cold cluster SSD clear returned invalid output on {target}" + ) from exc + return deleted, len(node_ids) + + # ============================================================================= # Pydantic Models # ============================================================================= @@ -5604,8 +5687,8 @@ async def clear_alltime_stats(is_admin: bool = Depends(require_admin)): return {"status": "ok"} -def _iter_loaded_scheduler_records(): - """Yield (model_id, scheduler, core) for each loaded model. +def _iter_loaded_engine_records(): + """Yield (model_id, scheduler-or-None, core) for each loaded model. Traverses the internal engine hierarchy: pool entry → async engine → core engine → scheduler. @@ -5620,9 +5703,26 @@ def _iter_loaded_scheduler_records(): entry = engine_pool._entries.get(model_id) if entry is None or entry.engine is None: continue - async_core = getattr(entry.engine, "_engine", None) - core = getattr(async_core, "engine", None) if async_core is not None else None + # DistributedBatchedEngine is stored directly in the pool; local + # batched engines retain the historical async-wrapper chain. + direct = entry.engine + async_core = getattr(direct, "_engine", None) + core = ( + direct + if callable(getattr(direct, "clear_prompt_caches", None)) + else getattr(async_core, "engine", None) + if async_core is not None + else None + ) scheduler = getattr(core, "scheduler", None) if core is not None else None + if core is not None: + yield model_id, scheduler, core + + +def _iter_loaded_scheduler_records(): + """Yield local scheduler records, excluding distributed proxy engines.""" + + for model_id, scheduler, core in _iter_loaded_engine_records(): if scheduler is not None: yield model_id, scheduler, core @@ -5645,8 +5745,24 @@ async def clear_ssd_cache(is_admin: bool = Depends(require_admin)): is loaded. """ total_deleted = 0 + distributed_ranks = 0 + distributed_failures = [] - for model_id, scheduler in _iter_loaded_schedulers(): + for model_id, scheduler, core in _iter_loaded_engine_records(): + distributed_clear = getattr(core, "clear_prompt_caches", None) + if callable(distributed_clear): + try: + report = await distributed_clear(ssd=True) + total_deleted += int(report.get("ssd_deleted", 0)) + distributed_ranks += len(report.get("ranks", ())) + except Exception as exc: + logger.warning( + "Failed to clear distributed SSD cache for model '%s': %s", + model_id, + exc, + ) + distributed_failures.append(f"{model_id}: {exc}") + continue ssd_manager = getattr(scheduler, "paged_ssd_cache_manager", None) if ssd_manager is not None: try: @@ -5679,7 +5795,50 @@ async def clear_ssd_cache(is_admin: bool = Depends(require_admin)): except Exception as exc: logger.warning("Failed to clean SSD cache directory: %s", exc) - return {"status": "ok", "total_deleted": total_deleted} + # When no distributed engine is resident, no rank-local maintenance + # endpoint exists. Clear the coordinator's cold cluster trees directly + # and ask every configured peer to resolve and clear its own paths. + if distributed_ranks == 0: + cluster_roots = ( + cache_dir / "cluster-prompt-snapshots", + Path(global_settings.base_path) + / "cluster/runtime/prompt-cache-ssd", + ) + for cluster_root in cluster_roots: + if not cluster_root.exists(): + continue + try: + total_deleted += sum( + 1 for item in cluster_root.rglob("*") if item.is_file() + ) + shutil.rmtree(cluster_root) + except Exception as exc: + logger.warning( + "Failed to clean distributed SSD cache directory %s: %s", + cluster_root, + exc, + ) + try: + remote_deleted, configured_ranks = await asyncio.to_thread( + _clear_cold_remote_cluster_cache_roots, + cluster_roots, + ) + total_deleted += remote_deleted + distributed_ranks = configured_ranks + except Exception as exc: + logger.warning("Failed to clean cold peer SSD cache: %s", exc) + distributed_failures.append(f"cold cluster peers: {exc}") + + if distributed_failures: + raise HTTPException( + status_code=503, + detail="; ".join(distributed_failures)[:1000], + ) + return { + "status": "ok", + "total_deleted": total_deleted, + "distributed_ranks": distributed_ranks, + } @router.post("/api/hot-cache/clear") @@ -5699,7 +5858,24 @@ async def clear_hot_cache(is_admin: bool = Depends(require_admin)): footprint_before = get_phys_footprint() total_cleared = 0 + distributed_ranks = 0 + distributed_failures = [] reclaim_targets = [] + for model_id, scheduler, core in _iter_loaded_engine_records(): + distributed_clear = getattr(core, "clear_prompt_caches", None) + if not callable(distributed_clear): + continue + try: + report = await distributed_clear(hot=True) + total_cleared += int(report.get("hot_cleared", 0)) + distributed_ranks += len(report.get("ranks", ())) + except Exception as exc: + logger.warning( + "Failed to clear distributed hot cache for model '%s': %s", + model_id, + exc, + ) + distributed_failures.append(f"{model_id}: {exc}") for model_id, scheduler, core in _iter_loaded_scheduler_records(): ssd_manager = getattr(scheduler, "paged_ssd_cache_manager", None) if ssd_manager is not None and hasattr(ssd_manager, "clear_hot_cache"): @@ -5756,10 +5932,16 @@ async def clear_hot_cache(is_admin: bool = Depends(require_admin)): await loop.run_in_executor(get_mlx_executor(), _sync_and_clear_cache) bytes_reclaimed = max(0, footprint_before - get_phys_footprint()) + if distributed_failures: + raise HTTPException( + status_code=503, + detail="; ".join(distributed_failures)[:1000], + ) return { "status": "ok", "total_cleared": total_cleared, "bytes_reclaimed": bytes_reclaimed, + "distributed_ranks": distributed_ranks, } diff --git a/omlx/api/openai_models.py b/omlx/api/openai_models.py index d0df0743a7..4cfb779d32 100644 --- a/omlx/api/openai_models.py +++ b/omlx/api/openai_models.py @@ -374,6 +374,11 @@ class Usage(BaseUsage): # Timing metrics (oMLX extension, seconds) model_load_duration: Optional[float] = None time_to_first_token: Optional[float] = None + # Chat streaming only, measured from stream_chat_completion entry (not HTTP + # endpoint arrival): first nonempty reasoning/content/structured-tool SSE + # delta after all output filters. This may be later than model TTFT for tool + # envelopes; Responses/Completions do not currently populate it. + time_to_first_visible_token: Optional[float] = None total_time: Optional[float] = None prompt_eval_duration: Optional[float] = None generation_duration: Optional[float] = None diff --git a/omlx/api/tool_calling.py b/omlx/api/tool_calling.py index 3675fa3514..2ac61eec87 100644 --- a/omlx/api/tool_calling.py +++ b/omlx/api/tool_calling.py @@ -1858,6 +1858,14 @@ def parse_tool_calls_with_thinking_fallback( return result.cleaned_text, result.tool_calls +@dataclass(frozen=True) +class ToolCallStreamSegment: + """One FIFO-safe visible-content or complete-envelope stream event.""" + + kind: str + text: str + + class ToolCallStreamFilter: """Streaming filter that suppresses tool-call markup from content deltas. @@ -1878,9 +1886,21 @@ class ToolCallStreamFilter: that never contains a separator-prefixed tool-call block (the thinking channel), where holding trailing newlines would flush them only after the channel closed. + capture_ordered_segments: Retain an opt-in FIFO of visible-content and + complete-envelope events for the narrow qwen3_coder Chat path. + Other filters pay no segment-copying cost. """ - def __init__(self, tokenizer: Any, *, consume_dsml_separator: bool = True): + _COMPLETED_ENVELOPE_MAX_COUNT = 16 + _COMPLETED_ENVELOPE_MAX_BYTES = 2 * 1024 * 1024 + + def __init__( + self, + tokenizer: Any, + *, + consume_dsml_separator: bool = True, + capture_ordered_segments: bool = False, + ): marker = getattr(tokenizer, "tool_call_start", None) marker_end = getattr(tokenizer, "tool_call_end", None) # Normalize None-like values but preserve empty strings. @@ -1936,6 +1956,11 @@ def __init__(self, tokenizer: Any, *, consume_dsml_separator: bool = True): self._pending_envelope_parts: List[str] = [] self._pending_start_marker: Optional[str] = None self._recovery_candidate = "" + self._completed_envelopes: List[str] = [] + self._completed_envelope_bytes = 0 + self._completed_envelope_overflowed = False + self._capture_ordered_segments = bool(capture_ordered_segments) + self._ordered_segments: List[ToolCallStreamSegment] = [] self._reset_json_scan() @staticmethod @@ -1958,6 +1983,75 @@ def take_recovery_candidate(self) -> str: self._recovery_candidate = "" return candidate + def take_completed_envelopes(self) -> List[str]: + """Return complete suppressed envelopes ready for exact parsing. + + Populated only when ``capture_ordered_segments=True``. Callers may emit + a structured tool-call delta as soon as the complete envelope validates + instead of waiting for generation to terminate. Partial/malformed + envelopes never enter this queue. + """ + + completed = self._completed_envelopes + self._completed_envelopes = [] + self._completed_envelope_bytes = 0 + return completed + + def take_ordered_segments(self) -> List[ToolCallStreamSegment]: + """Return content/envelope events in their exact raw stream order.""" + + segments = self._ordered_segments + self._ordered_segments = [] + return segments + + @property + def completed_envelope_overflowed(self) -> bool: + """Whether an envelope exceeded the bounded early-stream queue.""" + + return self._completed_envelope_overflowed + + @property + def envelope_open(self) -> bool: + """Whether model output is currently buffered inside a tool envelope.""" + + return bool(self._suppressing or self._suppressing_until is not None) + + def _record_content(self, out: List[str], text: str) -> None: + if not text: + return + out.append(text) + if self._capture_ordered_segments: + self._ordered_segments.append(ToolCallStreamSegment("content", text)) + + def _record_completed_envelope(self, completed: str) -> None: + if not self._capture_ordered_segments: + return + if self._completed_envelope_overflowed: + return + if ( + len(self._completed_envelopes) >= self._COMPLETED_ENVELOPE_MAX_COUNT + or self._completed_envelope_bytes + len(completed) + > self._COMPLETED_ENVELOPE_MAX_BYTES + ): + # Latch for the lifetime of this filter. Clear the not-yet-consumed + # queue/segments so a dropped earlier call can never be followed by + # a later early-emitted call out of sequence. + self._completed_envelope_overflowed = True + self._completed_envelopes = [] + self._completed_envelope_bytes = 0 + self._ordered_segments = [ + segment + for segment in self._ordered_segments + if segment.kind != "envelope" + ] + return + self._completed_envelopes.append(completed) + self._completed_envelope_bytes += len(completed) + if self._capture_ordered_segments: + self._ordered_segments.append( + ToolCallStreamSegment("envelope", completed) + ) + def _clear_pending_envelope(self) -> None: self._pending_envelope_parts = [] self._pending_start_marker = None @@ -2533,6 +2627,11 @@ def feed(self, text: str) -> str: self._shift_json_scan(len(moved), moved) self._buffer = "" break + completed = ( + "".join(self._pending_envelope_parts) + + self._buffer[: end_idx + len(self._suppressing_until)] + ) + self._record_completed_envelope(completed) self._buffer = self._buffer[end_idx + len(self._suppressing_until) :] self._suppressing_until = None self._clear_pending_envelope() @@ -2543,7 +2642,8 @@ def feed(self, text: str) -> str: idx, consume_len, close_marker = start opening_marker = self._buffer[idx : idx + consume_len] if idx > 0: - out.append( + self._record_content( + out, self._sanitize_prefix_before_suppression(self._buffer[:idx]) ) self._buffer = self._buffer[idx + consume_len :] @@ -2560,11 +2660,11 @@ def feed(self, text: str) -> str: keep = self._partial_suffix_len(self._buffer) if keep == 0: - out.append(self._buffer) + self._record_content(out, self._buffer) self._buffer = "" break if len(self._buffer) > keep: - out.append(self._buffer[:-keep]) + self._record_content(out, self._buffer[:-keep]) self._buffer = self._buffer[-keep:] break diff --git a/omlx/cache/prefix_cache.py b/omlx/cache/prefix_cache.py index ae2700e0fb..d99805443d 100644 --- a/omlx/cache/prefix_cache.py +++ b/omlx/cache/prefix_cache.py @@ -1590,8 +1590,10 @@ def restore_exact_prefix( return None try: - if promote_to_hot_cache: - self.preload_blocks(block_table) + # reconstruct_cache performs the same SSD load and promotes each + # block as it is consumed. preload_blocks is serialized for Metal + # safety, so running it here would deserialize the exact chain + # twice before returning it. restored_cache = self.reconstruct_cache( block_table, promote_to_hot_cache=promote_to_hot_cache, diff --git a/omlx/cluster/backends.py b/omlx/cluster/backends.py new file mode 100644 index 0000000000..cf96a561ab --- /dev/null +++ b/omlx/cluster/backends.py @@ -0,0 +1,158 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Per-cluster collective backend selection: JACCL everywhere, or TCP ring. + +The rule is deliberately binary and fail-safe: ``jaccl`` is selected only when +**every** cluster member reports ``rdma_ctl`` enabled *and* at least one RDMA +device; anything else selects the TCP ``ring``. A single member without RDMA +silently downgrading only its own stage is exactly how half-configured JACCL +clusters hang at ``mx.distributed.init`` — the whole cluster shares one +backend, so the weakest member decides, out loud. + +This module is pure: members arrive as data (from ``collect_cluster_status`` +locally, from peer probes remotely, or from posted host records), which keeps +selection offline-testable. Live ``rdma_ctl`` state is re-verified at launch +preflight; a selection made from stale evidence can only fail closed there. + +Ring is a first-class runtime path, not a degraded one: ring deployments run +through the same ``DistributedJobSupervisor`` verified teardown (process-group +SIGTERM→SIGKILL escalation with proof, plus the marker-pid rank sweep — +including remote ranks over SSH) as JACCL deployments. Nothing in the teardown +machinery is backend-conditional. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from dataclasses import dataclass, field +from typing import Any + + +@dataclass(frozen=True) +class MemberFabric: + """One member's RDMA capability, as observed by a probe or host record.""" + + node_id: str + rdma_ctl_enabled: bool = False + rdma_devices: tuple[str, ...] = () + + def __post_init__(self) -> None: + if not self.node_id: + raise ValueError("member node_id is required") + object.__setattr__(self, "rdma_devices", tuple(sorted(set(self.rdma_devices)))) + + @property + def jaccl_ready(self) -> bool: + return self.rdma_ctl_enabled and bool(self.rdma_devices) + + def to_dict(self) -> dict[str, Any]: + return { + "node_id": self.node_id, + "rdma_ctl_enabled": self.rdma_ctl_enabled, + "rdma_devices": list(self.rdma_devices), + "jaccl_ready": self.jaccl_ready, + } + + +@dataclass(frozen=True) +class BackendSelection: + """The backend a whole cluster will use, and why.""" + + backend: str # "jaccl" | "ring" + reason: str + blockers: tuple[str, ...] = () + members: tuple[MemberFabric, ...] = field(default_factory=tuple) + + def to_dict(self) -> dict[str, Any]: + return { + "backend": self.backend, + "reason": self.reason, + "blockers": list(self.blockers), + "members": [member.to_dict() for member in self.members], + } + + +def select_cluster_backend(members: Iterable[MemberFabric]) -> BackendSelection: + """Pick ``jaccl`` when rdma_ctl is enabled on ALL members, else ``ring``. + + ``jaccl-ring`` (Thunderbolt without RDMA) remains manually selectable on + the deployment endpoints; automatic selection never picks it because its + hostfile still needs a complete RDMA device matrix, which "no RDMA" + members by definition cannot supply. + """ + + members = tuple(members) + if len(members) < 2: + raise ValueError("backend selection needs at least two cluster members") + node_ids = [member.node_id for member in members] + if len(set(node_ids)) != len(node_ids): + raise ValueError("cluster member node IDs must be unique") + + blockers = tuple(member.node_id for member in members if not member.jaccl_ready) + if not blockers: + return BackendSelection( + backend="jaccl", + reason=( + f"rdma_ctl is enabled with RDMA devices on all {len(members)} members" + ), + members=members, + ) + details = [] + for member in members: + if member.jaccl_ready: + continue + if not member.rdma_ctl_enabled: + details.append(f"{member.node_id} has rdma_ctl disabled") + else: + details.append(f"{member.node_id} reports no RDMA device") + return BackendSelection( + backend="ring", + reason=( + "JACCL needs rdma_ctl enabled on every member; falling back to " + "the TCP ring for the whole cluster (" + "; ".join(details) + ")" + ), + blockers=blockers, + members=members, + ) + + +def members_from_host_records(hosts: Iterable[Any]) -> tuple[MemberFabric, ...]: + """Derive member fabric evidence from posted host records. + + A host that carries a complete RDMA connectivity matrix (one entry per + peer, null diagonal, no null off-diagonal) is treated as rdma_ctl-enabled: + that matrix can only be produced from live interface names. This is + request evidence, not a probe — launch preflight re-verifies the live + state, so stale input fails closed at activation rather than launching a + collective that blocks. + """ + + hosts = list(hosts) + size = len(hosts) + members: list[MemberFabric] = [] + for host in hosts: + rdma = list(getattr(host, "rdma", ()) or ()) + complete = len(rdma) == size and size >= 2 + devices: list[str] = [] + if complete: + for index, path in enumerate(rdma): + expected_none = index == len(members) + if expected_none: + if path is not None: + complete = False + break + continue + if path is None: + complete = False + break + if isinstance(path, (list, tuple)): + devices.extend(str(item) for item in path) + else: + devices.append(str(path)) + members.append( + MemberFabric( + node_id=str(getattr(host, "node_id", "")), + rdma_ctl_enabled=complete, + rdma_devices=tuple(devices) if complete else (), + ) + ) + return tuple(members) diff --git a/omlx/cluster/control_plane.py b/omlx/cluster/control_plane.py new file mode 100644 index 0000000000..cf255032b3 --- /dev/null +++ b/omlx/cluster/control_plane.py @@ -0,0 +1,537 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Small reliable rank-control channel kept separate from tensor collectives.""" + +from __future__ import annotations + +import hashlib +import hmac +import pickle +import secrets +import socket +import struct +import threading +import time +import zlib +from contextlib import AbstractContextManager, suppress +from typing import Any + +from .system_socket_proxy import ( + SystemSocketProxy, + open_system_tcp_proxy, + should_proxy_control_socket, +) + +_HANDSHAKE_MAGIC = b"OC2H" +_HANDSHAKE_CHALLENGE_MAGIC = b"OC2C" +_HANDSHAKE_ACK_MAGIC = b"OC2A" +_MESSAGE_MAGIC = b"OC2M" +_OWNED_BYTES_MAGIC = b"OC2B" +_BARRIER_MAGIC = b"OC2R" +_VERSION = 1 +_HANDSHAKE_CHALLENGE = struct.Struct("!4sI32s") +_HANDSHAKE = struct.Struct("!4sII32s") +_HANDSHAKE_ACK = struct.Struct("!4sI32s") +_HEADER_PREFIX = struct.Struct("!4sIIII") +_HEADER = struct.Struct("!4sIIII32s") +_OWNED_BYTES_PREFIX = struct.Struct("!4sIIIII") +_OWNED_BYTES_HEADER = struct.Struct("!4sIIIII32s") +_BARRIER_PREFIX = struct.Struct("!4sIII") +_BARRIER_PACKET = struct.Struct("!4sIII32s") +_MAX_OBJECT_BYTES = 256 * 1024 * 1024 +_WORKER_AUTH_DOMAIN = b"omlx-rank-control-worker-v1" +_COORDINATOR_AUTH_DOMAIN = b"omlx-rank-control-coordinator-v1" +_MESSAGE_AUTH_DOMAIN = b"omlx-rank-control-message-v1" +_OWNED_BYTES_AUTH_DOMAIN = b"omlx-rank-control-owned-bytes-v1" +_BARRIER_AUTH_DOMAIN = b"omlx-rank-control-barrier-v1" + + +def _recv_exact(stream: socket.socket, size: int) -> bytes: + chunks = bytearray() + while len(chunks) < size: + part = stream.recv(size - len(chunks)) + if not part: + raise ConnectionError("rank-control peer closed its socket") + chunks.extend(part) + return bytes(chunks) + + +class RankControlPlane(AbstractContextManager["RankControlPlane"]): + """Rank-zero object broadcast over TCP, with strict ordering/integrity. + + JACCL remains the high-bandwidth tensor transport. Request metadata and + cancellation lists are single-producer control messages, and routing them + through tiny RDMA reductions caused corrupt headers and lost completions. + One persistent socket per worker avoids per-token connection setup while + keeping control failures explicit and bounded. + """ + + def __init__( + self, + *, + rank: int, + world_size: int, + host: str, + port: int, + token: str, + connect_timeout: float = 120.0, + io_timeout: float = 120.0, + ) -> None: + if not 0 <= rank < world_size or world_size < 2: + raise ValueError("rank-control identity is invalid") + if not 1 <= int(port) <= 65535: + raise ValueError("rank-control port is invalid") + encoded_token = token.encode("ascii", "strict") + if not encoded_token or len(encoded_token) > 64: + raise ValueError("rank-control token must be 1..64 ASCII bytes") + self.rank = int(rank) + self.world_size = int(world_size) + self.host = str(host) + self.port = int(port) + self._token = encoded_token.ljust(64, b"\0") + self._connect_timeout = float(connect_timeout) + self._io_timeout = float(io_timeout) + self._listener: socket.socket | None = None + self._peers: dict[int, socket.socket] = {} + self._stream: socket.socket | None = None + self._stream_proxy: SystemSocketProxy | None = None + self._sequence = 0 + # Model decisions and cancellation normally share one generation + # thread. Serialize defensively so a future second caller cannot + # interleave frames or consume the ordered sequence twice. + self._operation_lock = threading.RLock() + + def __enter__(self) -> RankControlPlane: + try: + if self.rank == 0: + self._accept_workers() + else: + self._connect_to_coordinator() + except BaseException: + self.close() + raise + return self + + def _configure(self, stream: socket.socket) -> None: + stream.settimeout(self._io_timeout) + stream.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + stream.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + + def _handshake_tag(self, domain: bytes, challenge: bytes, rank: int) -> bytes: + identity = struct.pack("!II", _VERSION, int(rank)) + return hmac.new( + self._token, + domain + challenge + identity, + hashlib.sha256, + ).digest() + + def _accept_workers(self) -> None: + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind((self.host, self.port)) + listener.listen(self.world_size - 1) + listener.settimeout(min(1.0, self._connect_timeout)) + self._listener = listener + deadline = time.monotonic() + self._connect_timeout + while len(self._peers) < self.world_size - 1: + if time.monotonic() >= deadline: + raise TimeoutError("rank-control workers did not connect") + try: + stream, _address = listener.accept() + except TimeoutError: + continue + remaining = max(0.1, deadline - time.monotonic()) + stream.settimeout(min(5.0, remaining)) + try: + challenge = secrets.token_bytes(32) + stream.sendall( + _HANDSHAKE_CHALLENGE.pack( + _HANDSHAKE_CHALLENGE_MAGIC, + _VERSION, + challenge, + ) + ) + magic, version, rank, observed_tag = _HANDSHAKE.unpack( + _recv_exact(stream, _HANDSHAKE.size) + ) + expected_tag = self._handshake_tag( + _WORKER_AUTH_DOMAIN, + challenge, + rank, + ) + if ( + magic != _HANDSHAKE_MAGIC + or version != _VERSION + or not 0 < rank < self.world_size + or rank in self._peers + or not hmac.compare_digest(observed_tag, expected_tag) + ): + stream.close() + continue + self._configure(stream) + stream.sendall( + _HANDSHAKE_ACK.pack( + _HANDSHAKE_ACK_MAGIC, + _VERSION, + self._handshake_tag( + _COORDINATOR_AUTH_DOMAIN, + challenge, + rank, + ), + ) + ) + self._peers[rank] = stream + except (OSError, TimeoutError, ConnectionError, struct.error): + stream.close() + continue + + def _authenticate_worker_stream(self, stream: socket.socket) -> None: + challenge_magic, challenge_version, challenge = _HANDSHAKE_CHALLENGE.unpack( + _recv_exact(stream, _HANDSHAKE_CHALLENGE.size) + ) + if ( + challenge_magic != _HANDSHAKE_CHALLENGE_MAGIC + or challenge_version != _VERSION + ): + raise RuntimeError("rank-control challenge is invalid") + stream.sendall( + _HANDSHAKE.pack( + _HANDSHAKE_MAGIC, + _VERSION, + self.rank, + self._handshake_tag( + _WORKER_AUTH_DOMAIN, + challenge, + self.rank, + ), + ) + ) + ack_magic, ack_version, ack_tag = _HANDSHAKE_ACK.unpack( + _recv_exact(stream, _HANDSHAKE_ACK.size) + ) + expected_ack = self._handshake_tag( + _COORDINATOR_AUTH_DOMAIN, + challenge, + self.rank, + ) + if ( + ack_magic != _HANDSHAKE_ACK_MAGIC + or ack_version != _VERSION + or not hmac.compare_digest(ack_tag, expected_ack) + ): + raise RuntimeError("rank-control handshake was not acknowledged") + + def _connect_to_coordinator(self) -> None: + if should_proxy_control_socket(self.host): + proxy = open_system_tcp_proxy( + self.host, + self.port, + timeout=self._connect_timeout, + ) + stream = proxy.stream + try: + self._configure(stream) + self._authenticate_worker_stream(stream) + except BaseException: + proxy.close() + raise + self._stream_proxy = proxy + self._stream = stream + return + deadline = time.monotonic() + self._connect_timeout + last_error: OSError | None = None + while time.monotonic() < deadline: + stream = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + stream.settimeout(min(1.0, self._connect_timeout)) + stream.connect((self.host, self.port)) + self._configure(stream) + self._authenticate_worker_stream(stream) + self._stream = stream + return + except RuntimeError: + stream.close() + raise + except OSError as exc: + last_error = exc + stream.close() + time.sleep(0.05) + raise TimeoutError(f"rank-control coordinator was unreachable: {last_error}") + + def broadcast_object(self, obj: Any) -> Any: + """Broadcast one rank-zero-owned Python object in strict sequence.""" + + with self._operation_lock: + self._sequence += 1 + if self.rank == 0: + payload = pickle.dumps(obj) if obj is not None else b"" + if len(payload) > _MAX_OBJECT_BYTES: + raise RuntimeError("rank-control object exceeds 256 MiB") + checksum = zlib.crc32(payload) + prefix = _HEADER_PREFIX.pack( + _MESSAGE_MAGIC, + _VERSION, + self._sequence, + len(payload), + checksum, + ) + tag = hmac.new( + self._token, + _MESSAGE_AUTH_DOMAIN + prefix + payload, + hashlib.sha256, + ).digest() + header = _HEADER.pack( + _MESSAGE_MAGIC, + _VERSION, + self._sequence, + len(payload), + checksum, + tag, + ) + packet = header + payload + for rank in range(1, self.world_size): + self._peers[rank].sendall(packet) + return obj + + stream = self._stream + if stream is None: + raise RuntimeError("rank-control worker is not connected") + magic, version, sequence, size, checksum, observed_tag = _HEADER.unpack( + _recv_exact(stream, _HEADER.size) + ) + if magic != _MESSAGE_MAGIC or version != _VERSION: + raise RuntimeError("rank-control message header is invalid") + if sequence != self._sequence: + raise RuntimeError( + f"rank-control sequence diverged: expected {self._sequence}, " + f"received {sequence}" + ) + if size > _MAX_OBJECT_BYTES: + raise RuntimeError("rank-control object has an invalid size") + payload = _recv_exact(stream, size) if size else b"" + if zlib.crc32(payload) != checksum: + raise RuntimeError("rank-control object failed CRC32") + prefix = _HEADER_PREFIX.pack(magic, version, sequence, size, checksum) + expected_tag = hmac.new( + self._token, + _MESSAGE_AUTH_DOMAIN + prefix + payload, + hashlib.sha256, + ).digest() + if not hmac.compare_digest(observed_tag, expected_tag): + raise RuntimeError("rank-control object failed authentication") + return pickle.loads(payload) if payload else None + + def _owned_bytes_packet( + self, + stream: socket.socket, + *, + sequence: int, + source_rank: int, + expected_size: int, + ) -> tuple[bytes, bytes]: + header = _recv_exact(stream, _OWNED_BYTES_HEADER.size) + magic, version, received_sequence, source, size, checksum, observed_tag = ( + _OWNED_BYTES_HEADER.unpack(header) + ) + if magic != _OWNED_BYTES_MAGIC or version != _VERSION: + raise RuntimeError("rank-control owned-bytes header is invalid") + if received_sequence != sequence: + raise RuntimeError( + f"rank-control sequence diverged: expected {sequence}, " + f"received {received_sequence}" + ) + if source != source_rank: + raise RuntimeError( + f"rank-control owned-bytes source diverged: expected {source_rank}, " + f"received {source}" + ) + if size != expected_size or size > _MAX_OBJECT_BYTES: + raise RuntimeError( + f"rank-control owned-bytes size diverged: expected {expected_size}, " + f"received {size}" + ) + payload = _recv_exact(stream, size) if size else b"" + if zlib.crc32(payload) != checksum: + raise RuntimeError("rank-control owned bytes failed CRC32") + prefix = _OWNED_BYTES_PREFIX.pack( + magic, version, received_sequence, source, size, checksum + ) + expected_tag = hmac.new( + self._token, + _OWNED_BYTES_AUTH_DOMAIN + prefix + payload, + hashlib.sha256, + ).digest() + if not hmac.compare_digest(observed_tag, expected_tag): + raise RuntimeError("rank-control owned bytes failed authentication") + return header + payload, payload + + def broadcast_owned_bytes( + self, + payload: bytes | None, + *, + source_rank: int, + expected_size: int, + ) -> bytes: + """Broadcast fixed-size bytes owned by any rank in strict sequence.""" + + if not 0 <= int(source_rank) < self.world_size: + raise ValueError("rank-control owned-bytes source is invalid") + if not 0 <= int(expected_size) <= _MAX_OBJECT_BYTES: + raise ValueError("rank-control owned-bytes size is invalid") + if payload is not None and not isinstance(payload, bytes): + raise TypeError("rank-control owned payload must be bytes") + if self.rank == source_rank: + if payload is None or len(payload) != expected_size: + raise RuntimeError( + "rank-control owned source produced an invalid payload" + ) + elif payload is not None: + raise RuntimeError("rank-control non-source supplied owned bytes") + + with self._operation_lock: + self._sequence += 1 + sequence = self._sequence + if self.rank == source_rank: + checksum = zlib.crc32(payload) + prefix = _OWNED_BYTES_PREFIX.pack( + _OWNED_BYTES_MAGIC, + _VERSION, + sequence, + source_rank, + expected_size, + checksum, + ) + tag = hmac.new( + self._token, + _OWNED_BYTES_AUTH_DOMAIN + prefix + payload, + hashlib.sha256, + ).digest() + packet = ( + _OWNED_BYTES_HEADER.pack( + _OWNED_BYTES_MAGIC, + _VERSION, + sequence, + source_rank, + expected_size, + checksum, + tag, + ) + + payload + ) + else: + packet = b"" + + if self.rank == 0: + if source_rank == 0: + owned = payload + else: + source = self._peers.get(source_rank) + if source is None: + raise RuntimeError("rank-control owned source is not connected") + packet, owned = self._owned_bytes_packet( + source, + sequence=sequence, + source_rank=source_rank, + expected_size=expected_size, + ) + for rank in range(1, self.world_size): + if rank != source_rank: + self._peers[rank].sendall(packet) + return owned + + stream = self._stream + if stream is None: + raise RuntimeError("rank-control worker is not connected") + if self.rank == source_rank: + stream.sendall(packet) + return payload + _packet, owned = self._owned_bytes_packet( + stream, + sequence=sequence, + source_rank=source_rank, + expected_size=expected_size, + ) + return owned + + def _barrier_packet(self, *, sequence: int, rank: int) -> bytes: + prefix = _BARRIER_PREFIX.pack(_BARRIER_MAGIC, _VERSION, sequence, rank) + tag = hmac.new( + self._token, + _BARRIER_AUTH_DOMAIN + prefix, + hashlib.sha256, + ).digest() + return _BARRIER_PACKET.pack(_BARRIER_MAGIC, _VERSION, sequence, rank, tag) + + def _recv_barrier_packet( + self, + stream: socket.socket, + *, + sequence: int, + rank: int, + ) -> None: + magic, version, received_sequence, received_rank, observed_tag = ( + _BARRIER_PACKET.unpack(_recv_exact(stream, _BARRIER_PACKET.size)) + ) + prefix = _BARRIER_PREFIX.pack(magic, version, received_sequence, received_rank) + expected_tag = hmac.new( + self._token, + _BARRIER_AUTH_DOMAIN + prefix, + hashlib.sha256, + ).digest() + if ( + magic != _BARRIER_MAGIC + or version != _VERSION + or received_sequence != sequence + or received_rank != rank + or not hmac.compare_digest(observed_tag, expected_tag) + ): + raise RuntimeError("rank-control barrier packet is invalid") + + def barrier(self) -> None: + """Wait until every rank reaches one ordered control boundary.""" + + with self._operation_lock: + self._sequence += 1 + sequence = self._sequence + if self.rank == 0: + for rank in range(1, self.world_size): + stream = self._peers.get(rank) + if stream is None: + raise RuntimeError("rank-control barrier peer is not connected") + self._recv_barrier_packet( + stream, + sequence=sequence, + rank=rank, + ) + release = self._barrier_packet(sequence=sequence, rank=0) + for rank in range(1, self.world_size): + self._peers[rank].sendall(release) + return + + stream = self._stream + if stream is None: + raise RuntimeError("rank-control worker is not connected") + stream.sendall(self._barrier_packet(sequence=sequence, rank=self.rank)) + self._recv_barrier_packet(stream, sequence=sequence, rank=0) + + def close(self) -> None: + for stream in self._peers.values(): + with suppress(OSError): + stream.close() + self._peers.clear() + if self._stream is not None: + with suppress(OSError): + self._stream.close() + self._stream = None + if self._stream_proxy is not None: + self._stream_proxy.close() + self._stream_proxy = None + if self._listener is not None: + with suppress(OSError): + self._listener.close() + self._listener = None + + def __exit__(self, *_exc: Any) -> None: + self.close() + + +__all__ = ["RankControlPlane"] diff --git a/omlx/cluster/deployment.py b/omlx/cluster/deployment.py index cb14c0a5f2..773e993227 100644 --- a/omlx/cluster/deployment.py +++ b/omlx/cluster/deployment.py @@ -8,6 +8,7 @@ import ipaddress import json import math +import os import re import zlib from dataclasses import dataclass, field @@ -44,6 +45,39 @@ _MAX_MODEL_ID_BYTES = 16 * 1024 _MAX_PLAN_BYTES = 256 * 1024 +# Rank-environment defaults carried by the mlx launch hostfile. Each value +# yields to the coordinator's own environment: an operator who pinned a knob +# keeps their value, and everyone else gets the tuned default. +# +# MLX_MAX_OPS_PER_BUFFER / MLX_MAX_MB_PER_BUFFER bound how much work lands in +# one Metal command buffer. An unbounded buffer overruns the GPU driver's +# ~10 s execution timeout (kIOGPUCommandBufferCallbackErrorTimeout), which the +# driver answers with SIGABRT and stranded wired memory — the crash class +# ThunderMLX root-caused to missing caps. +# +# JACCL_PROGRESS_TIMEOUT_MS / JACCL_TIMEOUT_ACTION pair with the ProgressGuard +# and emergency-teardown symbols compiled into the serving wheel's libjaccl +# (``progress_timeout_ms()`` and the ``teardown-exit`` action calling +# ``emergency_teardown()``): an RDMA polling loop that sees no completion for +# 30 s unwinds and exits instead of spinning forever with memory wired. The +# wheel ships compiled defaults; pinning them here keeps the posture explicit +# and identical across every rank. +_RANK_ENV_DEFAULTS = ( + ("MLX_METAL_FAST_SYNCH", "1"), + ("MLX_MAX_OPS_PER_BUFFER", "16"), + ("MLX_MAX_MB_PER_BUFFER", "512"), + ("JACCL_PROGRESS_TIMEOUT_MS", "30000"), + ("JACCL_TIMEOUT_ACTION", "teardown-exit"), +) + + +def _hostfile_envs() -> list[str]: + return [ + f"{name}={os.environ.get(name) or default}" + for name, default in _RANK_ENV_DEFAULTS + ] + + RDMAPath = str | tuple[str, ...] | None @@ -432,7 +466,7 @@ def model_path_for(self, node_id: str) -> str: def hostfile_dict(self) -> dict[str, Any]: return { "backend": self.backend, - "envs": ["MLX_METAL_FAST_SYNCH=1"], + "envs": _hostfile_envs(), "hosts": [ { "ssh": host.ssh, diff --git a/omlx/cluster/inference_worker.py b/omlx/cluster/inference_worker.py index 2e3e156bbd..bb19554c77 100644 --- a/omlx/cluster/inference_worker.py +++ b/omlx/cluster/inference_worker.py @@ -5,6 +5,7 @@ import argparse import json +import logging import os import re import signal @@ -13,14 +14,19 @@ import threading import time from collections.abc import Sequence -from contextlib import contextmanager, suppress +from contextlib import contextmanager, nullcontext, suppress from datetime import UTC, datetime from functools import wraps from pathlib import Path from types import SimpleNamespace from typing import Any -from .deployment import decode_worker_contract, decode_worker_path_map +from .control_plane import RankControlPlane +from .deployment import ( + decode_worker_contract, + decode_worker_path_map, +) +from .jaccl_lease import acquire_jaccl_communicator_lease from .liveness import PeerWatchdog from .memory_guard import ( admission_budget, @@ -42,6 +48,8 @@ _EVENT_PREFIX = "OMLX_CLUSTER_EVENT:" +logger = logging.getLogger(__name__) + def _emit_event(payload: dict[str, Any]) -> None: print( @@ -50,6 +58,48 @@ def _emit_event(payload: dict[str, Any]) -> None: ) +def _wait_for_serve_release( + state_dir: str | Path, + deployment_id: str, + plan_hash: str, + world_size: int, + *, + timeout: float = 1800.0, + clock: Any = time.monotonic, + sleep: Any = time.sleep, +) -> None: + """Wait for the supervisor to confirm that every rank finished loading. + + Ranks cannot use a JACCL collective as this barrier: the first Mac may be + fully wired while a smaller peer is still materializing layers, and an + early all-reduce then times out and destroys an otherwise healthy load. + Every rank publishes ``rank_ready`` first; the supervisor observes all of + them and atomically writes this local release marker on every host. + """ + + path = Path(state_dir).expanduser() / f"{deployment_id}-serve.json" + deadline = float(clock()) + max(0.0, float(timeout)) + while True: + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + payload = None + if ( + isinstance(payload, dict) + and payload.get("schema_version") == 1 + and payload.get("deployment_id") == deployment_id + and payload.get("plan_hash") == plan_hash + and payload.get("world_size") == world_size + ): + return + remaining = deadline - float(clock()) + if remaining <= 0: + raise TimeoutError( + "supervisor did not release all loaded ranks into serving" + ) + sleep(min(0.05, remaining)) + + def _cross_thread_generation_stream(mx: Any) -> Any: """Create the one MLX stream used by both rank loading and generation. @@ -470,34 +520,143 @@ def _execution_settings(args: argparse.Namespace) -> ExecutionSettings: def _prompt_cache_ssd_dir(args: argparse.Namespace, rank: int) -> str | None: """Per-rank SSD directory for prompt-cache snapshots, or None when off. - Kept beside the runtime markers and scoped by deployment and rank, so two - deployments never read each other's snapshots and a rank only ever loads its - own layer slice. + Kept beside the runtime markers and scoped by deployment, signed plan and + rank, so a changed tensor split can never restore another shard layout. """ if not args.prompt_cache_ssd: return None root = Path(args.state_dir).expanduser() / "prompt-cache-ssd" - return str(root / f"{args.deployment_id}-rank-{rank}") + plan_hash = str(getattr(args, "plan_hash", "") or "unplanned") + return str(root / args.deployment_id / plan_hash / f"rank-{rank}") + + +def _release_metal_memory(reason: str) -> None: + """Best-effort Metal release before a force-exit. + + Ported from ThunderMLX's ``clear_mlx_cache`` (run_with_watchdog.py), the + fix for "176 GB wired with no owning process": ``clear_cache()`` alone only + drops the Metal *cache pool* — the wired model weights stay stranded in + kernel wired memory when ``os._exit`` skips every finally/atexit handler. + ``set_wired_limit(0)`` unwires the model allocation so the OS reclaims it + on process death. Every step is guarded: a rank whose MLX import or Metal + queue is already broken must still reach its exit. + """ + + try: + import mlx.core as mx + except Exception: + # MLX never imported (or unimportable): nothing is wired, nothing to do. + return + try: + # Unwire first: this is what actually releases the memory the weights + # hold. A safe no-op when nothing is wired. + mx.set_wired_limit(0) + except Exception as exc: + logger.warning("set_wired_limit(0) failed (%s): %s", reason, exc) + with suppress(Exception): + mx.clear_cache() + metal = getattr(mx, "metal", None) + metal_clear = getattr(metal, "clear_cache", None) + if metal_clear is not None: + with suppress(Exception): + metal_clear() def _install_signal_handlers() -> None: - def interrupt(_signum: int, _frame: Any) -> None: + def hard_exit(signum: int, _frame: Any) -> None: + # The Metal release hung on a wedged GPU queue; the cleanup path must + # not itself stall the SIGKILL escalation waiting behind it. + name = signal.Signals(signum).name + sys.stderr.write(f"[RANK] {name} while releasing Metal memory; hard-exiting\n") + sys.stderr.flush() + os._exit(128 + signum) + + def interrupt(signum: int, _frame: Any) -> None: + name = signal.Signals(signum).name + # Release wired Metal memory while the rank can still do it itself — + # the coordinator escalates a wedged rank from SIGTERM to SIGKILL, and + # a SIGKILL cannot unwire anything (ThunderMLX's TERM/INT handlers in + # run_with_watchdog.py, alarm escape hatch included). The graceful + # KeyboardInterrupt path is unchanged for a rank that answers promptly. + try: + signal.signal(signal.SIGALRM, hard_exit) + signal.alarm( + int(os.environ.get("OMLX_CLUSTER_SIGNAL_CLEAR_TIMEOUT", "10") or "10") + ) + except Exception: + pass + _release_metal_memory(f"rank received {name}") + with suppress(Exception): + signal.alarm(0) raise KeyboardInterrupt signal.signal(signal.SIGTERM, interrupt) signal.signal(signal.SIGINT, interrupt) +def _write_cancel_request( + state_dir: str, + deployment_id: str, + reason: str, + *, + plan_hash: str | None = None, +) -> None: + """Ask this rank's telemetry to force-cancel in-flight requests. + + Best effort and silent on failure: the file is consumed by the rank's + telemetry heartbeat, which cancels through ``BatchGenerator.remove`` at + a batch step boundary shared with peer ranks. Writing it before a + watchdog exit lets in-flight work unwind instead of being severed + mid-collective. + """ + + try: + root = Path(state_dir).expanduser() + root.mkdir(parents=True, exist_ok=True) + path = root / f"{deployment_id}-cancel.json" + epoch = int(time.time() * 1000) + # A reused deployment ID can leave a marker from a future-skewed + # clock. Keep the edge monotonically newer so the live worker cannot + # mistake a watchdog request for its startup watermark. + try: + existing = json.loads(path.read_text(encoding="utf-8")) + previous_epoch = existing.get("epoch") if isinstance(existing, dict) else 0 + if isinstance(previous_epoch, int) and not isinstance(previous_epoch, bool): + epoch = max(epoch, previous_epoch + 1) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + pass + payload: dict[str, Any] = { + "schema_version": 1, + "deployment_id": deployment_id, + "epoch": epoch, + "scope": "all", + "reason": reason, + } + if plan_hash: + payload["plan_hash"] = plan_hash + temporary = path.with_name(path.name + ".tmp") + descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(payload, stream, sort_keys=True) + os.replace(temporary, path) + except OSError as exc: + logger.warning("Could not write the rank cancel request: %s", exc) + + def _watch_launcher_parent( parent_pid: int, marker: RuntimeMarker, *, poll_interval: float = 0.2, + watched_marker_path: Any = None, + marker_stale_after: float = 45.0, get_parent_pid: Any = os.getppid, wait: Any = time.sleep, exit_process: Any = os._exit, emit_event: Any = _emit_event, + on_abort: Any = None, + release_memory: Any = _release_metal_memory, ) -> None: """Fail fast if MLX's launcher exits without reaping this rank. @@ -505,23 +664,58 @@ def _watch_launcher_parent( after its main thread handles SIGTERM. The launcher is the lifetime owner of every rank, so a reparented worker cannot make useful collective progress and must not remain resident on a node. + + Two conditions are watched: the parent pid changing (the original check), + and — when ``watched_marker_path`` is configured — a launcher- or + coordinator-maintained lease file going stale for ``marker_stale_after`` + seconds, which catches a launcher that is alive but wedged (its ranks + would otherwise wait in a collective forever). ``os._exit`` stays the + last resort: ``on_abort`` fires first so in-flight requests can be + cancelled at a step boundary, and ``release_memory`` unwires the rank's + Metal allocations before the process disappears — ``os._exit`` skips + every finally/atexit handler, and a skipped release strands wired memory + until the Mac is rebooted. """ + watched = Path(watched_marker_path) if watched_marker_path else None while True: wait(poll_interval) - if get_parent_pid() == parent_pid: + reason = None + if get_parent_pid() != parent_pid: + current_parent = get_parent_pid() + reason = ( + f"rank launcher parent changed from {parent_pid} to " + f"{current_parent}; the rank cannot safely continue" + ) + elif watched is not None and marker_stale_after > 0: + try: + age = time.time() - watched.stat().st_mtime + except OSError: + age = None + # A lease that never appeared yet is not stale; the launcher may + # still be starting. Once it exists, it must stay fresh. + if age is not None and age > marker_stale_after: + reason = ( + f"launcher lease {watched} is stale ({age:.1f}s > " + f"{marker_stale_after:.1f}s); the launcher is wedged" + ) + if reason is None: continue - current_parent = get_parent_pid() - reason = ( - f"rank launcher parent changed from {parent_pid} to " - f"{current_parent}; the rank cannot safely continue" - ) # Keep the marker as bounded crash evidence. The next activation # overwrites the deterministic path, and liveness already ignores a # marker whose owner is dead. Removing it here reduced this exact # failure to "heartbeat missing" with no explanation. marker.update("launcher_lost", error=reason) + if on_abort is not None: + try: + on_abort(reason) + except Exception: + logger.warning("Launcher watchdog abort stage failed", exc_info=True) emit_event({"type": "launcher_lost", "reason": reason}) + try: + release_memory(f"launcher watchdog exit: {reason}") + except Exception: + logger.warning("Launcher watchdog Metal release failed", exc_info=True) exit_process(1) return @@ -592,13 +786,32 @@ def _start_peer_watchdog( def on_lost(reason: str) -> None: marker.update("peer_lost", error=reason) _emit_event({"type": "peer_lost", "reason": reason}) + # Unwire and release Metal memory before the force-exit: os._exit + # skips every finally/atexit handler, and a skipped release strands + # the rank's wired allocation until the Mac is rebooted. + with suppress(Exception): + _release_metal_memory(f"peer watchdog exit: {reason}") os._exit(1) + def on_abort(reason: str) -> None: + # The cancel file is consumed by this rank's telemetry heartbeat, + # which cancels in-flight requests through BatchGenerator.remove at + # a batch step boundary shared with every rank — never mid-collective. + _write_cancel_request( + state_dir, + deployment_id, + f"peer watchdog aborting before teardown: {reason}", + plan_hash=marker.payload.get("plan_hash"), + ) + + abort_grace = float(os.environ.get("OMLX_CLUSTER_PEER_ABORT_GRACE", "5.0") or 0.0) watchdog = PeerWatchdog( hosts_by_rank, deployment_id=deployment_id, state_dir=state_dir, on_lost=on_lost, + on_abort=on_abort, + abort_grace=abort_grace, ) thread = threading.Thread( target=watchdog.run, name="omlx-cluster-peer-watchdog", daemon=True @@ -607,10 +820,35 @@ def on_lost(reason: str) -> None: return watchdog -def _start_launcher_watchdog(marker: RuntimeMarker, parent_pid: int) -> None: +def _start_launcher_watchdog( + marker: RuntimeMarker, + parent_pid: int, + *, + state_dir: str | None = None, +) -> None: + # Optional coordinator/launcher lease file: when configured (and once + # it exists), the watchdog also fires if it goes stale — covering a + # launcher that is alive but wedged, which the parent-pid check alone + # cannot see. Off by default, preserving the original PPID-only watch. + lease = os.environ.get("OMLX_CLUSTER_LAUNCHER_LEASE", "").strip() + deployment_id = str(marker.payload.get("deployment_id") or "") + + def on_abort(reason: str) -> None: + if state_dir and deployment_id: + _write_cancel_request( + state_dir, + deployment_id, + reason, + plan_hash=marker.payload.get("plan_hash"), + ) + thread = threading.Thread( target=_watch_launcher_parent, args=(parent_pid, marker), + kwargs={ + "watched_marker_path": lease or None, + "on_abort": on_abort, + }, name="omlx-cluster-launcher-watchdog", daemon=True, ) @@ -959,7 +1197,17 @@ def run_worker(args: argparse.Namespace) -> int: ) execution = _execution_settings(args) init_backend = "jaccl" if args.backend.startswith("jaccl") else "ring" - group = mx.distributed.init(backend=init_backend, strict=True) + jaccl_lease = ( + acquire_jaccl_communicator_lease( + deployment_id=args.deployment_id, + state_dir=args.state_dir, + ) + if init_backend == "jaccl" + else None + ) + from .jaccl_side_channel import init_cluster_group + + group = init_cluster_group(mx, backend=init_backend, strict=True) rank = group.rank() world_size = group.size() if world_size != len(assignments): @@ -996,7 +1244,7 @@ def run_worker(args: argparse.Namespace) -> int: ) marker.start_heartbeat() _install_signal_handlers() - _start_launcher_watchdog(marker, launcher_parent_pid) + _start_launcher_watchdog(marker, launcher_parent_pid, state_dir=args.state_dir) # Before the load, not after it. Loading a 300 GB model takes twenty # minutes, and a peer that goes away inside that window left every other # rank blocked in its first collective with nothing watching at all. @@ -1212,12 +1460,32 @@ def run_worker(args: argparse.Namespace) -> int: "optimizations": optimizations, } ) + _wait_for_serve_release( + args.state_dir, + args.deployment_id, + plan_hash, + world_size, + timeout=args.load_timeout, + ) + control_context = ( + RankControlPlane( + rank=rank, + world_size=world_size, + host=args.control_host, + port=args.control_port, + token=args.control_token, + ) + if args.control_host and args.control_port and args.control_token + else nullcontext(None) + ) with ( + control_context as control_plane, install_server_telemetry( marker, execution=execution, assignment=assignment, ssd_cache_dir=_prompt_cache_ssd_dir(args, rank), + ssd_cache_persistent=bool(args.prompt_cache_ssd), prefill_step_size=args.prefill_step_size, prefill_guard=build_guard( provider.model, @@ -1231,6 +1499,7 @@ def run_worker(args: argparse.Namespace) -> int: # really use, not from mlx-lm's 2048 default. prefill_step_size=args.prefill_step_size, ), + control_plane=control_plane, ), _bind_generation_thread_stream( ResponseGenerator, @@ -1263,6 +1532,8 @@ def run_worker(args: argparse.Namespace) -> int: marker.stop_heartbeat() if not preserve_failure_marker: marker.remove() + if jaccl_lease is not None: + jaccl_lease.close() return 0 @@ -1311,6 +1582,10 @@ def build_parser() -> argparse.ArgumentParser: default="~/.omlx/cluster/runtime", help="Local state directory shown by the oMLX GUI on each node", ) + parser.add_argument("--control-host", default="") + parser.add_argument("--control-port", type=int, default=0) + parser.add_argument("--control-token", default="") + parser.add_argument("--load-timeout", type=float, default=1800.0) parser.add_argument("--trust-remote-code", action="store_true") parser.add_argument( "--execution-profile", @@ -1345,6 +1620,17 @@ def main(argv: list[str] | None = None) -> int: args.model = str(Path(args.model).expanduser()) if not 1 <= args.port <= 65535: raise SystemExit("--port must be between 1 and 65535") + control_values = ( + bool(args.control_host), + bool(args.control_port), + bool(args.control_token), + ) + if any(control_values) and not all(control_values): + raise SystemExit( + "--control-host, --control-port and --control-token are required together" + ) + if args.control_port and not 1 <= args.control_port <= 65535: + raise SystemExit("--control-port must be between 1 and 65535") for name in ( "decode_concurrency", "prompt_concurrency", diff --git a/omlx/cluster/jaccl_lease.py b/omlx/cluster/jaccl_lease.py new file mode 100644 index 0000000000..d516b31a27 --- /dev/null +++ b/omlx/cluster/jaccl_lease.py @@ -0,0 +1,116 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Per-Mac process lease for the Thunderbolt JACCL communicator.""" + +from __future__ import annotations + +import fcntl +import json +import os +import time +from contextlib import suppress +from pathlib import Path +from typing import Any + +_MAX_OWNER_BYTES = 4096 + + +class JacclCommunicatorBusyError(RuntimeError): + """Another live process owns this Mac's RDMA communicator.""" + + +class JacclCommunicatorLease: + """An advisory lock held for one rank process's complete lifetime.""" + + def __init__(self, descriptor: int, path: Path) -> None: + self._descriptor = descriptor + self.path = path + + @property + def active(self) -> bool: + return self._descriptor >= 0 + + def close(self) -> None: + descriptor, self._descriptor = self._descriptor, -1 + if descriptor < 0: + return + try: + fcntl.flock(descriptor, fcntl.LOCK_UN) + finally: + os.close(descriptor) + + def __enter__(self) -> JacclCommunicatorLease: + return self + + def __exit__(self, *_exc: Any) -> None: + self.close() + + def __del__(self) -> None: + with suppress(Exception): + self.close() + + +def acquire_jaccl_communicator_lease( + *, + deployment_id: str, + state_dir: str | Path = "~/.omlx/cluster/runtime", +) -> JacclCommunicatorLease: + """Acquire the one-communicator-per-Mac safety contract. + + The lock is kernel-owned and releases when a rank crashes or is killed; + the small JSON body is diagnostics only and is never trusted as liveness. + """ + + root = Path(state_dir).expanduser() + root.mkdir(parents=True, exist_ok=True) + path = root / "jaccl-communicator.lock" + descriptor = os.open(path, os.O_RDWR | os.O_CREAT, 0o600) + try: + os.fchmod(descriptor, 0o600) + try: + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as exc: + owner = "" + try: + os.lseek(descriptor, 0, os.SEEK_SET) + owner = os.read(descriptor, _MAX_OWNER_BYTES).decode( + "utf-8", errors="replace" + ) + parsed = json.loads(owner) + owner = ( + f"deployment {parsed.get('deployment_id', 'unknown')} " + f"(pid {parsed.get('pid', 'unknown')})" + ) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + owner = "another live rank process" + raise JacclCommunicatorBusyError( + "Thunderbolt RDMA is already owned by " + f"{owner or 'another live rank process'}; oMLX permits one " + "JACCL communicator per Mac until the multi-communicator " + "lost-completion soak passes" + ) from exc + + payload = json.dumps( + { + "schema_version": 1, + "deployment_id": str(deployment_id)[:128], + "pid": os.getpid(), + "acquired_at": time.time(), + }, + sort_keys=True, + separators=(",", ":"), + ).encode() + os.ftruncate(descriptor, 0) + os.lseek(descriptor, 0, os.SEEK_SET) + os.write(descriptor, payload) + os.fsync(descriptor) + return JacclCommunicatorLease(descriptor, path) + except BaseException: + os.close(descriptor) + raise + + +__all__ = [ + "JacclCommunicatorBusyError", + "JacclCommunicatorLease", + "acquire_jaccl_communicator_lease", +] diff --git a/omlx/cluster/jaccl_side_channel.py b/omlx/cluster/jaccl_side_channel.py new file mode 100644 index 0000000000..a5f35fbfd7 --- /dev/null +++ b/omlx/cluster/jaccl_side_channel.py @@ -0,0 +1,477 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Reliable JACCL metadata exchange for distributed oMLX workers. + +JACCL uses a tiny TCP all-gather only while it creates its RDMA queue pairs. +The native helper is normally sufficient, but a direct Thunderbolt interface +can occasionally leave its client bootstrap sockets in ``SYN_SENT`` even +though ordinary TCP on the same interface succeeds. MLX exposes a supported +``all_gather_factory`` specifically for replacing that bootstrap path. This +module supplies a bounded, ordered implementation without changing the RDMA +data path used after initialization. +""" + +from __future__ import annotations + +import os +import socket +import struct +import subprocess +import sys +import threading +import time +from collections.abc import Callable +from pathlib import Path + +_RANK_BYTES = struct.Struct("!I") +_DEFAULT_BOOTSTRAP_TIMEOUT_SECONDS = 20.0 +_DEFAULT_CONNECT_RETRY_SECONDS = 0.05 +_MAX_METADATA_BYTES = 8 * 1024 * 1024 + +# The serving interpreter can be denied macOS Local Network access even when +# Apple's system Python is allowed to use the same direct Thunderbolt IP. This +# tiny, standard-library-only helper owns only the one-time JACCL metadata +# socket. The parent still owns every RDMA queue pair and collective. +_SIDECAR_PROGRAM = r""" +import socket, struct, sys, time + +RANK = struct.Struct("!I") + +def recv_exact(stream, count, allow_eof=False): + parts = [] + remaining = count + while remaining: + part = stream.read(remaining) + if not part: + if allow_eof and not parts: + return None + raise RuntimeError("side-channel stream closed") + parts.append(part) + remaining -= len(part) + return b"".join(parts) + +def sock_recv_exact(peer, count): + parts = [] + remaining = count + while remaining: + part = peer.recv(remaining) + if not part: + raise RuntimeError("side-channel peer disconnected") + parts.append(part) + remaining -= len(part) + return b"".join(parts) + +def connect(host, port, timeout): + deadline = time.monotonic() + timeout + error = None + while time.monotonic() < deadline: + peer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + peer.settimeout(min(1.0, max(0.05, deadline - time.monotonic()))) + peer.connect((host, port)) + peer.settimeout(timeout) + return peer + except OSError as exc: + error = exc + peer.close() + time.sleep(0.05) + raise RuntimeError("side-channel could not reach coordinator: %s" % error) + +def bootstrap(host, port, rank, size, timeout): + if rank: + peer = connect(host, port, timeout) + peer.sendall(RANK.pack(rank)) + return peer + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + listener.bind((host, port)) + listener.listen(size) + listener.settimeout(timeout) + peers = [None] * size + deadline = time.monotonic() + timeout + while any(peer is None for peer in peers[1:]): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise RuntimeError("side-channel timed out waiting for ranks") + listener.settimeout(remaining) + peer, _ = listener.accept() + try: + peer.settimeout(timeout) + peer_rank = RANK.unpack(sock_recv_exact(peer, RANK.size))[0] + if not 1 <= peer_rank < size or peers[peer_rank] is not None: + raise RuntimeError("side-channel received invalid rank") + except BaseException: + peer.close() + raise + peers[peer_rank] = peer + return peers + finally: + listener.close() + +def main(): + host, port, rank, size, timeout = ( + sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), float(sys.argv[5]) + ) + peers = bootstrap(host, port, rank, size, timeout) + source, sink = sys.stdin.buffer, sys.stdout.buffer + while True: + header = recv_exact(source, RANK.size, allow_eof=True) + if header is None: + return + count = RANK.unpack(header)[0] + payload = recv_exact(source, count) + if rank == 0: + gathered = [payload] + for peer in peers[1:]: + gathered.append(sock_recv_exact(peer, count)) + result = b"".join(gathered) + for peer in peers[1:]: + peer.sendall(result) + else: + peers.sendall(payload) + result = sock_recv_exact(peers, size * count) + sink.write(result) + sink.flush() + +if __name__ == "__main__": + try: + main() + except BaseException as exc: + print("oMLX JACCL side-channel helper failed: %s" % exc, file=sys.stderr, flush=True) + raise +""" + + +def _positive_float(name: str, default: float) -> float: + raw = os.environ.get(name, "").strip() + if not raw: + return default + try: + value = float(raw) + except ValueError: + return default + return value if value > 0 else default + + +def _enabled() -> bool: + """Whether to replace JACCL's native metadata side channel. + + This is default-on for oMLX JACCL jobs, with an escape hatch for precise + upstream comparison and incident recovery. + """ + + return os.environ.get( + "OMLX_JACCL_PYTHON_SIDE_CHANNEL", "1" + ).strip().lower() not in { + "0", + "false", + "no", + "off", + } + + +def _coordinator_endpoint() -> tuple[str, int]: + raw = os.environ.get("MLX_JACCL_COORDINATOR", "").strip() + host, separator, port_text = raw.rpartition(":") + if not separator or not host or not port_text.isdecimal(): + raise RuntimeError( + "JACCL side channel requires MLX_JACCL_COORDINATOR as IPv4:port" + ) + port = int(port_text) + if not 1 <= port <= 65535: + raise RuntimeError("JACCL side channel coordinator port is invalid") + try: + socket.inet_aton(host) + except OSError as exc: + raise RuntimeError( + "JACCL side channel currently requires an IPv4 coordinator" + ) from exc + return host, port + + +def _recv_exact(sock: socket.socket, n_bytes: int) -> bytes: + chunks: list[bytes] = [] + remaining = n_bytes + while remaining: + chunk = sock.recv(remaining) + if not chunk: + raise RuntimeError("JACCL side channel peer disconnected") + chunks.append(chunk) + remaining -= len(chunk) + return b"".join(chunks) + + +def _read_exact_stream(stream: object, n_bytes: int) -> bytes: + """Read a fixed frame from a local sidecar pipe.""" + + chunks: list[bytes] = [] + remaining = n_bytes + read = stream.read + while remaining: + chunk = read(remaining) + if not chunk: + raise RuntimeError("JACCL side-channel helper closed its pipe") + chunks.append(chunk) + remaining -= len(chunk) + return b"".join(chunks) + + +def _send_all(sock: socket.socket, payload: bytes) -> None: + view = memoryview(payload) + while view: + written = sock.send(view) + if written <= 0: + raise RuntimeError("JACCL side channel peer rejected metadata") + view = view[written:] + + +def _trace(message: str) -> None: + if os.environ.get("OMLX_JACCL_SIDE_CHANNEL_TRACE", "0") == "1": + print(f"OMLX_JACCL_SIDE_CHANNEL {message}", file=sys.stderr, flush=True) + + +class _SocketAllGather: + """One rank's persistent, serialized bootstrap TCP connection set.""" + + def __init__(self, rank: int, size: int) -> None: + if not 0 <= rank < size or size < 2: + raise RuntimeError("JACCL side channel received invalid rank metadata") + self.rank = rank + self.size = size + self.timeout = _positive_float( + "OMLX_JACCL_SIDE_CHANNEL_TIMEOUT_SECONDS", + _DEFAULT_BOOTSTRAP_TIMEOUT_SECONDS, + ) + self._lock = threading.Lock() + self._peers: list[socket.socket] | socket.socket + host, port = _coordinator_endpoint() + if rank == 0: + self._peers = self._accept_peers(host, port) + else: + self._peers = self._connect(host, port) + _trace(f"ready rank={rank} size={size} coordinator={host}:{port}") + + def _accept_peers(self, host: str, port: int) -> list[socket.socket]: + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + server.bind((host, port)) + server.listen(self.size) + server.settimeout(self.timeout) + peers: list[socket.socket | None] = [None] * self.size + deadline = time.monotonic() + self.timeout + while any(peer is None for peer in peers[1:]): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise RuntimeError( + "JACCL side channel timed out waiting for every rank" + ) + server.settimeout(remaining) + peer, _address = server.accept() + try: + peer.settimeout(self.timeout) + peer_rank = _RANK_BYTES.unpack(_recv_exact(peer, _RANK_BYTES.size))[ + 0 + ] + if not 1 <= peer_rank < self.size or peers[peer_rank] is not None: + raise RuntimeError( + "JACCL side channel received an invalid peer rank" + ) + except BaseException: + peer.close() + raise + peers[peer_rank] = peer + return [peer for peer in peers[1:] if peer is not None] + except BaseException: + for peer in locals().get("peers", []): + if peer is not None: + peer.close() + raise + finally: + server.close() + + def _connect(self, host: str, port: int) -> socket.socket: + deadline = time.monotonic() + self.timeout + last_error: OSError | None = None + while time.monotonic() < deadline: + peer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + peer.settimeout(min(1.0, max(0.05, deadline - time.monotonic()))) + peer.connect((host, port)) + peer.settimeout(self.timeout) + _send_all(peer, _RANK_BYTES.pack(self.rank)) + return peer + except OSError as exc: + last_error = exc + peer.close() + time.sleep(_DEFAULT_CONNECT_RETRY_SECONDS) + detail = f": {last_error}" if last_error else "" + raise RuntimeError(f"JACCL side channel could not reach coordinator{detail}") + + def __call__(self, src: bytes, n_bytes: int) -> bytes: + if n_bytes < 0 or len(src) != n_bytes: + raise RuntimeError("JACCL side channel received malformed metadata") + with self._lock: + if self.rank == 0: + assert isinstance(self._peers, list) + gathered = [src] + for peer in self._peers: + gathered.append(_recv_exact(peer, n_bytes)) + result = b"".join(gathered) + for peer in self._peers: + _send_all(peer, result) + return result + assert isinstance(self._peers, socket.socket) + _send_all(self._peers, src) + return _recv_exact(self._peers, self.size * n_bytes) + + +def _sidecar_python() -> str | None: + """Return Apple's system Python when it is usable as a network carrier.""" + + candidate = Path( + os.environ.get("OMLX_JACCL_SIDE_CHANNEL_PYTHON", "/usr/bin/python3") + ) + if candidate.is_file() and os.access(candidate, os.X_OK): + return str(candidate) + return None + + +def _side_channel_transport() -> str: + value = os.environ.get("OMLX_JACCL_SIDE_CHANNEL_TRANSPORT", "auto").strip() + selected = value.lower() or "auto" + if selected not in {"auto", "direct", "sidecar"}: + raise RuntimeError( + "OMLX_JACCL_SIDE_CHANNEL_TRANSPORT must be auto, direct, or sidecar" + ) + if selected == "auto": + # The helper is off the hot path and prevents a macOS Local Network + # entitlement mismatch from making an otherwise verified TB fabric + # unusable. Non-macOS hosts retain the direct standard-library path. + return "sidecar" if sys.platform == "darwin" and _sidecar_python() else "direct" + if selected == "sidecar" and _sidecar_python() is None: + raise RuntimeError("JACCL side-channel helper Python is unavailable") + return selected + + +class _SidecarAllGather: + """A local-pipe adapter whose bootstrap sockets live in system Python.""" + + def __init__(self, rank: int, size: int) -> None: + if not 0 <= rank < size or size < 2: + raise RuntimeError("JACCL side channel received invalid rank metadata") + host, port = _coordinator_endpoint() + self.rank = rank + self.size = size + self.timeout = _positive_float( + "OMLX_JACCL_SIDE_CHANNEL_TIMEOUT_SECONDS", + _DEFAULT_BOOTSTRAP_TIMEOUT_SECONDS, + ) + self._lock = threading.Lock() + executable = _sidecar_python() + if executable is None: # defensive: transport selection already checks + raise RuntimeError("JACCL side-channel helper Python is unavailable") + self._process = subprocess.Popen( + [ + executable, + "-u", + "-c", + _SIDECAR_PROGRAM, + host, + str(port), + str(rank), + str(size), + str(self.timeout), + ], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + bufsize=0, + ) + _trace(f"sidecar started rank={rank} size={size} coordinator={host}:{port}") + + def _failure(self) -> RuntimeError: + status = self._process.poll() + detail = "" + if status is not None and self._process.stderr is not None: + detail = self._process.stderr.read().decode("utf-8", "replace").strip() + suffix = f": {detail[-1000:]}" if detail else "" + return RuntimeError( + f"JACCL side-channel helper stopped (status={status}){suffix}" + ) + + def __call__(self, src: bytes, n_bytes: int) -> bytes: + if n_bytes < 0 or n_bytes > _MAX_METADATA_BYTES or len(src) != n_bytes: + raise RuntimeError("JACCL side channel received malformed metadata") + if self._process.stdin is None or self._process.stdout is None: + raise self._failure() + with self._lock: + try: + self._process.stdin.write(_RANK_BYTES.pack(n_bytes) + src) + self._process.stdin.flush() + result = _read_exact_stream(self._process.stdout, self.size * n_bytes) + except (BrokenPipeError, OSError, RuntimeError) as exc: + raise self._failure() from exc + return result + + def close(self) -> None: + """Close the local control pipe; used by isolated verification tests.""" + + if self._process.stdin is not None and not self._process.stdin.closed: + self._process.stdin.close() + try: + self._process.wait(timeout=1.0) + except subprocess.TimeoutExpired: + self._process.terminate() + self._process.wait(timeout=1.0) + + +def jaccl_all_gather_factory(rank: int, size: int) -> Callable[[bytes, int], bytes]: + """Return JACCL's supported metadata all-gather callable for one rank.""" + + if _side_channel_transport() == "sidecar": + return _SidecarAllGather(rank, size) + return _SocketAllGather(rank, size) + + +def _mlx_supports_all_gather_factory(distributed: object) -> bool: + """Detect the *loaded* nanobind API, not an optionally newer stub file. + + Development installs can briefly pair an updated ``distributed.pyi`` with + an older ``core`` extension. Retrying through a TypeError would be safe, + but inspecting the native function documentation first keeps a failed + JACCL load from looking like a fabric failure. + """ + + init = distributed.init + return "all_gather_factory" in (getattr(init, "__doc__", "") or "") + + +def init_cluster_group( + mx: object, + *, + backend: str | None = None, + strict: bool = False, +) -> object: + """Initialize a distributed group with the resilient JACCL bootstrap. + + Ring/NCCL execution remains byte-for-byte on MLX's normal path. For a + JACCL worker, only connection metadata travels through this small TCP + control channel; collectives immediately thereafter remain RDMA/JACCL. + """ + + distributed = mx.distributed + selected = backend + if selected is None and os.environ.get("MLX_JACCL_COORDINATOR"): + selected = "jaccl" + if selected == "jaccl" and _enabled(): + if _mlx_supports_all_gather_factory(distributed): + return distributed.init( + backend="jaccl", + strict=strict, + all_gather_factory=jaccl_all_gather_factory, + ) + _trace("native MLX has no all_gather_factory; using its default bootstrap") + if selected is None: + return distributed.init(strict=strict) + return distributed.init(backend=selected, strict=strict) diff --git a/omlx/cluster/launch.py b/omlx/cluster/launch.py index 523ea4ed3f..61b57e4a8d 100644 --- a/omlx/cluster/launch.py +++ b/omlx/cluster/launch.py @@ -12,6 +12,7 @@ import os import platform import re +import secrets import shlex import shutil import signal @@ -31,9 +32,15 @@ from omlx.utils import hardware from .deployment import ClusterDeployment, validate_ssh_target -from .liveness import _LOOPBACK_TARGETS, read_marker, read_remote_marker +from .liveness import ( + _LOOPBACK_TARGETS, + marker_owner_is_live, + read_marker, + read_remote_marker, +) from .models import CLUSTER_PROTOCOL_VERSION from .performance import performance_profiles_from_records +from .runtime import read_runtime_markers from .ssh_policy import cluster_ssh_options from .staging import home_relative_model_path, validate_staged_model @@ -45,12 +52,159 @@ _REMOTE_OUTPUT_LIMIT = 64 * 1024 _FABRIC_INTERFACE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$") _DEFAULT_CONNECTX_MIN_BYTES_PER_SECOND = 2 * 1024**3 +_LAUNCHER_RANK_EXIT_RE = re.compile( + r"Node with rank\s+(?P\d+)\s+exited with code\s+(?P-?\d+)" +) +_JACCL_NO_PROGRESS_RE = re.compile( + r"\[jaccl\]\s+(?P[^\r\n]*made no progress[^\r\n]*)", + re.IGNORECASE, +) +_REBOOT_REQUIRED_GUIDANCE = ( + "A distributed rank survived SIGKILL and may be stuck in the macOS " + "Metal driver. Reboot this Mac before starting another distributed launch." +) class DistributedLaunchError(RuntimeError): """Raised when a distributed job cannot become or remain ready.""" +class DistributedTeardownError(DistributedLaunchError): + """Raised when a distributed job survives a verified teardown attempt. + + A rank that survives SIGKILL (unkillable Metal/JACCL kernel wait, + D-state, or a ``PermissionError`` that ``_process_group_alive`` + deliberately reads as alive) keeps its unified-memory allocation + resident. Reporting success anyway was the orphaned-GPU-memory hole: + the engine pool released the model's memory budget while the weights + were still wired. Callers must treat this as "teardown NOT complete" + and keep enough state to retry. + """ + + +@dataclass(frozen=True) +class _LocalProcessState: + """One read-only row from the macOS/Linux process table.""" + + pid: int + ppid: int + process_group: int + status: str + rss_kib: int + command: str + + @property + def zombie(self) -> bool: + return self.status.upper().startswith("Z") + + +def _read_local_process_table( + *, + runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run, +) -> tuple[tuple[_LocalProcessState, ...] | None, str]: + """Read process state; an unreadable table is not teardown evidence.""" + + argv = ["ps", "-axo", "pid=,ppid=,pgid=,stat=,rss=,command="] + try: + completed = runner( + argv, + capture_output=True, + text=True, + check=False, + timeout=5.0, + ) + except (OSError, subprocess.SubprocessError) as exc: + return None, f"could not read the local process table: {exc}" + if completed.returncode != 0: + detail = completed.stderr.strip() or f"ps exited {completed.returncode}" + return None, f"could not read the local process table: {detail}" + + rows: list[_LocalProcessState] = [] + for line_number, raw_line in enumerate(completed.stdout.splitlines(), 1): + fields = raw_line.strip().split(None, 5) + if not fields: + continue + if len(fields) != 6: + return None, ( + "could not verify the local process table: malformed ps row " + f"{line_number}" + ) + pid, ppid, process_group, status, rss_kib, command = fields + try: + numeric = tuple(int(value) for value in (pid, ppid, process_group, rss_kib)) + except ValueError: + return None, ( + "could not verify the local process table: invalid ps row " + f"{line_number}" + ) + if numeric[0] <= 0 or numeric[2] < 0 or numeric[3] < 0: + return None, ( + "could not verify the local process table: invalid ps row " + f"{line_number}" + ) + rows.append( + _LocalProcessState( + pid=numeric[0], + ppid=numeric[1], + process_group=numeric[2], + status=status, + rss_kib=numeric[3], + command=command, + ) + ) + return tuple(rows), "" + + +def _command_deployment_id(command: str) -> str | None: + try: + arguments = shlex.split(command) + except ValueError: + return None + for index, argument in enumerate(arguments): + if argument == "--deployment-id" and index + 1 < len(arguments): + return arguments[index + 1] + if argument.startswith("--deployment-id="): + return argument.partition("=")[2] + return None + + +def _belongs_to_launch(process: _LocalProcessState, *, deployment_id: str) -> bool: + return _command_deployment_id(process.command) == deployment_id and ( + "mlx._distributed_utils.launch" in process.command + or "omlx.cluster.inference_worker" in process.command + ) + + +def _local_launch_survivors( + processes: tuple[_LocalProcessState, ...], + *, + deployment_id: str, + process_group: int | None = None, + known_pids: set[int] | None = None, +) -> tuple[_LocalProcessState, ...]: + return tuple( + process + for process in processes + if not process.zombie + and ( + (known_pids is not None and process.pid in known_pids) + or (process_group is not None and process.process_group == process_group) + or _belongs_to_launch(process, deployment_id=deployment_id) + ) + ) + + +def _survivor_description(process: _LocalProcessState) -> str: + return ( + f"pid {process.pid} (ppid {process.ppid}, pgid {process.process_group}, " + f"state {process.status!r}, rss {process.rss_kib} KiB) survived SIGKILL" + ) + + +def _is_macos_exit_wedge(process: _LocalProcessState) -> bool: + return "E" in process.status.upper() and process.rss_kib == 0 + + @dataclass(frozen=True) class CudaFabricProbeHost: """One CUDA worker and its direct-link NCCL endpoint.""" @@ -123,6 +277,671 @@ def _wait_for_process_group_exit(process_group: int, timeout: float) -> bool: return True +def _pid_alive(pid: int) -> bool: + """Local mirror of ``liveness._pid_is_live`` for reaper bookkeeping.""" + + try: + os.kill(int(pid), 0) + except ProcessLookupError: + return False + except (PermissionError, OverflowError): + return True + except (TypeError, ValueError): + return False + return True + + +_LAUNCH_MANIFEST_PREFIX = "launch-" +_LOOPBACK_SSH_TARGETS = {"127.0.0.1", "localhost", "::1"} + + +def _launch_manifest_path(state_dir: str | Path, deployment_id: str) -> Path: + return ( + Path(state_dir).expanduser() / f"{_LAUNCH_MANIFEST_PREFIX}{deployment_id}.json" + ) + + +def _serve_release_path(state_dir: str | Path, deployment_id: str) -> Path: + """Coordinator-owned gate that releases loaded ranks into serving.""" + + return Path(state_dir).expanduser() / f"{deployment_id}-serve.json" + + +_REMOTE_SERVE_MARKER_SCRIPT = ( + "import json,os,pathlib,sys;" + "p=pathlib.Path(sys.argv[1]).expanduser();" + "raw=sys.argv[2];" + "p.parent.mkdir(parents=True,exist_ok=True);" + "tmp=p.with_name(p.name+'.tmp');" + "tmp.write_text(raw,encoding='utf-8');" + "os.chmod(tmp,0o600);" + "os.replace(tmp,p)" +) + +_REMOTE_CLEAR_SERVE_MARKER_SCRIPT = ( + "import pathlib,sys;pathlib.Path(sys.argv[1]).expanduser().unlink(missing_ok=True)" +) + + +def _set_serve_release( + deployment: ClusterDeployment, + state_dir: str | Path, + payload: dict[str, Any] | None, + *, + runner: SSHRunner = subprocess.run, +) -> None: + """Atomically publish or clear the post-load serve gate on every rank.""" + + filename = f"{deployment.deployment_id}-serve.json" + encoded = ( + json.dumps(payload, sort_keys=True, separators=(",", ":")) + if payload is not None + else None + ) + local_path = _serve_release_path(state_dir, deployment.deployment_id) + local_path.parent.mkdir(parents=True, exist_ok=True) + if encoded is None: + local_path.unlink(missing_ok=True) + else: + temporary = local_path.with_name(local_path.name + ".tmp") + descriptor = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_TRUNC, + 0o600, + ) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + stream.write(encoded) + os.replace(temporary, local_path) + + remote_root = str(state_dir).rstrip("/") or "." + remote_path = f"{remote_root}/{filename}" + for host in deployment.hosts: + if host.ssh in _LOOPBACK_SSH_TARGETS: + continue + script = ( + _REMOTE_CLEAR_SERVE_MARKER_SCRIPT + if encoded is None + else _REMOTE_SERVE_MARKER_SCRIPT + ) + arguments = [remote_path] if encoded is None else [remote_path, encoded] + command = " ".join( + ["python3", "-c", shlex.quote(script)] + + [shlex.quote(item) for item in arguments] + ) + completed = _run_cluster_ssh( + host.ssh, + command, + timeout=15.0, + runner=runner, + ) + _raise_for_ssh_transport_failure(host.ssh, completed) + if completed.returncode != 0: + detail = completed.stderr.strip() or "remote marker update failed" + raise DistributedLaunchError( + f"Could not update serve gate on {host.ssh}: {detail}" + ) + + +def _write_launch_manifest( + state_dir: str | Path, + deployment: ClusterDeployment, + *, + launcher_pid: int, + api_port: int | None, +) -> Path: + """Persist launch identity so a *new* coordinator can reap leftovers. + + Every teardown path lives in the coordinator process, so a SIGKILL or + panic of omlx-server strands the launcher and every rank with no owner + (G8). The manifest records the process group and the marker directory + of the job; ``reap_orphaned_launches`` consumes it at the next server + start. It is removed only after verified process-group exit. + """ + + root = Path(state_dir).expanduser() + root.mkdir(parents=True, exist_ok=True) + manifest = { + "schema_version": 1, + "deployment_id": deployment.deployment_id, + "plan_hash": deployment.plan_hash, + # start_new_session=True makes the launcher its own group leader. + "launcher_pid": int(launcher_pid), + "process_group": int(launcher_pid), + "coordinator_pid": os.getpid(), + "api_port": api_port, + "started_at": time.time(), + "hosts": [ + {"rank": rank, "node_id": host.node_id, "ssh": host.ssh} + for rank, host in enumerate(deployment.hosts) + ], + } + path = _launch_manifest_path(state_dir, deployment.deployment_id) + temporary = path.with_name(path.name + ".tmp") + descriptor = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_TRUNC, + 0o600, + ) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(manifest, stream, indent=2, sort_keys=True) + stream.write("\n") + os.replace(temporary, path) + return path + + +def _read_launch_manifest(path: Path) -> dict[str, Any] | None: + """Read one manifest; anything malformed is ignored, never reaped.""" + + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + return None + if not isinstance(payload, dict) or payload.get("schema_version") != 1: + return None + deployment_id = payload.get("deployment_id") + launcher_pid = payload.get("launcher_pid") + coordinator_pid = payload.get("coordinator_pid") + hosts = payload.get("hosts") + if not isinstance(deployment_id, str) or not deployment_id: + return None + if not all( + isinstance(pid, int) and not isinstance(pid, bool) and pid > 0 + for pid in (launcher_pid, coordinator_pid) + ): + return None + if not isinstance(hosts, list): + return None + return payload + + +def _kill_local_pid(pid: int, *, grace: float) -> bool: + """SIGTERM, brief grace, then SIGKILL; True once the pid is gone.""" + + with suppress(ProcessLookupError): + os.kill(pid, signal.SIGTERM) + deadline = time.monotonic() + max(0.0, grace) + while _pid_alive(pid): + remaining = deadline - time.monotonic() + if remaining <= 0: + break + time.sleep(min(0.05, remaining)) + if not _pid_alive(pid): + return True + with suppress(ProcessLookupError): + os.kill(pid, signal.SIGKILL) + deadline = time.monotonic() + 2.0 + while _pid_alive(pid): + remaining = deadline - time.monotonic() + if remaining <= 0: + break + time.sleep(min(0.05, remaining)) + return not _pid_alive(pid) + + +def _kill_remote_pid( + ssh_target: str, + pid: int, + *, + grace: float, + runner: SSHRunner = subprocess.run, +) -> bool: + """Best-effort remote TERM->grace->KILL of one rank pid over SSH. + + killpg only reaches the *local* process group (G2): a remote rank whose + launcher-parent watchdog never fired keeps its shard resident. The rank + pid recorded in its runtime marker gives the coordinator a direct kill + path that does not depend on the SSH session teardown chain. + """ + + command = ( + f"kill -TERM {pid} 2>/dev/null; sleep {max(0.0, grace):.1f}; " + f"kill -KILL {pid} 2>/dev/null; sleep 0.5; " + f"if kill -0 {pid} 2>/dev/null; then echo alive; else echo gone; fi" + ) + try: + completed = _run_cluster_ssh( + ssh_target, + command, + timeout=max(5.0, grace) + 15.0, + runner=runner, + ) + except DistributedLaunchError as exc: + logger.warning("Remote rank kill via %s failed: %s", ssh_target, exc) + return False + return "gone" in completed.stdout and "alive" not in completed.stdout + + +_REMOTE_WORKER_SCAN_SCRIPT = ( + "import json,shlex,subprocess,sys;" + "dep=sys.argv[1];" + "r=subprocess.run(['ps','-axo','pid=,command='],capture_output=True,text=True,check=False);" + "p=[];" + "\nfor line in r.stdout.splitlines():" + "\n s=line.strip(); fields=s.split(None,1)" + "\n if len(fields)!=2 or not fields[0].isdigit(): continue" + "\n try: args=shlex.split(fields[1])" + "\n except ValueError: continue" + "\n if 'omlx.cluster.inference_worker' not in args: continue" + "\n try: i=args.index('--deployment-id')" + "\n except ValueError: continue" + "\n if i+1 tuple[list[int] | None, str]: + """Find rank workers even when a hard crash removed their marker.""" + + command = " ".join( + ( + "python3", + "-c", + shlex.quote(_REMOTE_WORKER_SCAN_SCRIPT), + shlex.quote(deployment_id), + ) + ) + try: + completed = _run_cluster_ssh( + ssh_target, + command, + timeout=10.0, + runner=runner, + ) + except DistributedLaunchError as exc: + return None, str(exc) + if len(completed.stdout.encode()) > _REMOTE_OUTPUT_LIMIT: + return None, "remote worker scan response was too large" + try: + payload = json.loads(completed.stdout) + except json.JSONDecodeError as exc: + return None, f"remote worker scan response was invalid: {exc}" + pids = payload.get("pids") + if payload.get("returncode") != 0 or not isinstance(pids, list): + return None, "remote worker process table could not be read" + if any( + isinstance(pid, bool) or not isinstance(pid, int) or pid <= 0 for pid in pids + ): + return None, "remote worker scan returned an invalid pid" + return pids, "" + + +def _rank_marker_matches( + marker: dict[str, Any] | None, + *, + deployment_id: str, + plan_hash: str | None, + rank: int, +) -> bool: + if not isinstance(marker, dict): + return False + if marker.get("deployment_id") != deployment_id or marker.get("rank") != rank: + return False + recorded = marker.get("plan_hash") + return not ( + plan_hash is not None and recorded is not None and recorded != plan_hash + ) + + +def _sweep_rank_processes( + deployment_id: str, + hosts: list[dict[str, Any]], + *, + state_dir: str | Path, + plan_hash: str | None = None, + process_group: int | None = None, + kill_grace: float = 3.0, + runner: SSHRunner = subprocess.run, +) -> list[str]: + """Kill rank processes recorded in runtime markers that are still live. + + Returns a bounded list of human-readable failures; empty means no rank + of this job remains resident anywhere the sweep could reach. + """ + + failures: list[str] = [] + attempted_local_pids: set[int] = set() + local_root = Path(state_dir).expanduser() + remote_root = str(state_dir).rstrip("/") or "." + initial_processes, process_error = _read_local_process_table() + processes_by_pid = ( + {process.pid: process for process in initial_processes} + if initial_processes is not None + else {} + ) + if initial_processes is None: + failures.append(process_error) + local_markers: dict[int, dict[str, Any]] = {} + try: + for job in read_runtime_markers(local_root).get("jobs", []): + if job.get("deployment_id") == deployment_id: + local_markers[job["rank"]] = job + except (OSError, KeyError, TypeError) as exc: + failures.append(f"could not read local runtime markers: {exc}") + + for host in hosts: + rank = host.get("rank") + ssh_target = host.get("ssh") + node_id = host.get("node_id", "?") + if not isinstance(rank, int) or not isinstance(ssh_target, str): + continue + filename = f"{deployment_id}-rank-{rank}.json" + if ssh_target in _LOOPBACK_SSH_TARGETS: + marker = local_markers.get(rank) + if marker is None: + marker = read_marker(local_root / filename) + if not _rank_marker_matches( + marker, + deployment_id=deployment_id, + plan_hash=plan_hash, + rank=rank, + ): + continue + if not marker_owner_is_live(marker): + continue + pid = marker.get("pid") + if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0: + failures.append(f"rank {rank} ({node_id}) marker has an invalid pid") + continue + process_state = processes_by_pid.get(pid) + if process_state is None: + failures.append( + f"rank {rank} ({node_id}) pid {pid} is addressable but " + "absent from the process table; refusing an unverified signal" + ) + continue + if process_state.zombie: + continue + if not _belongs_to_launch( + process_state, + deployment_id=deployment_id, + ) and not _is_macos_exit_wedge(process_state): + failures.append( + f"rank {rank} ({node_id}) pid {pid} identity changed; " + "refusing to signal a reused PID" + ) + continue + attempted_local_pids.add(pid) + if _kill_local_pid(pid, grace=kill_grace): + logger.warning( + "Reaped leftover rank %d (%s) pid %d of deployment %s", + rank, + node_id, + pid, + deployment_id, + ) + else: + failures.append(f"rank {rank} ({node_id}) pid {pid} survived SIGKILL") + continue + # Remote rank: its marker lives on the peer. + marker, process_live, _, error = read_remote_marker( + ssh_target, + f"{remote_root}/{filename}", + ) + if error: + pids, scan_error = _remote_deployment_worker_pids( + ssh_target, + deployment_id, + runner=runner, + ) + if scan_error: + failures.append( + f"rank {rank} ({node_id}) marker unreadable ({error}) and " + f"worker scan failed: {scan_error}" + ) + continue + for pid in pids or (): + if not _kill_remote_pid( + ssh_target, + pid, + grace=kill_grace, + runner=runner, + ): + failures.append( + f"remote rank {rank} ({node_id}) pid {pid} could not be killed" + ) + continue + if not _rank_marker_matches( + marker, + deployment_id=deployment_id, + plan_hash=plan_hash, + rank=rank, + ): + continue + if process_live is not True: + continue + pid = marker.get("pid") + if not isinstance(pid, int) or pid <= 0: + continue + if _kill_remote_pid(ssh_target, pid, grace=kill_grace, runner=runner): + logger.warning( + "Reaped leftover remote rank %d (%s) pid %d of deployment %s", + rank, + node_id, + pid, + deployment_id, + ) + else: + failures.append( + f"remote rank {rank} ({node_id}) pid {pid} could not be killed" + ) + + # Markers and successful signal calls are not exit evidence. Sweep any + # markerless local worker by its exact deployment argv, then require a + # fresh process-table snapshot to contain neither its PID nor launch group. + processes, process_error = _read_local_process_table() + if processes is None: + failures.append(process_error) + return list(dict.fromkeys(failures)) + for process in _local_launch_survivors( + processes, + deployment_id=deployment_id, + ): + if process.pid in attempted_local_pids: + continue + attempted_local_pids.add(process.pid) + if not _kill_local_pid(process.pid, grace=kill_grace): + failures.append("markerless local rank " + _survivor_description(process)) + + processes, process_error = _read_local_process_table() + if processes is None: + failures.append(process_error) + return list(dict.fromkeys(failures)) + survivors = _local_launch_survivors( + processes, + deployment_id=deployment_id, + process_group=process_group, + known_pids=attempted_local_pids, + ) + failures.extend(_survivor_description(process) for process in survivors) + if survivors: + failures.append(_REBOOT_REQUIRED_GUIDANCE) + return list(dict.fromkeys(failures)) + + +def stop_deployment_processes( + deployment: ClusterDeployment, + *, + state_dir: str | Path = "~/.omlx/cluster/runtime", + kill_grace: float = 3.0, + runner: SSHRunner = subprocess.run, +) -> dict[str, Any]: + """Stop and prove exit of one deployment without trusting pool ownership. + + The normal engine path owns a :class:`DistributedJobSupervisor`, but an + admin unload can arrive after that Python object was lost while its local + or SSH-launched rank still owns unified memory. This deployment-scoped + backstop verifies the persisted launcher identity, terminates its process + group when present, sweeps exact worker argv/marker PIDs on every signed + host, and returns only after the final process-table checks pass. + """ + + manifest_path = _launch_manifest_path(state_dir, deployment.deployment_id) + manifest = _read_launch_manifest(manifest_path) if manifest_path.exists() else None + failures: list[str] = [] + process_group: int | None = None + if manifest_path.exists() and manifest is None: + failures.append("launch manifest is unreadable; refusing unverified unload") + elif manifest is not None: + if manifest.get("deployment_id") != deployment.deployment_id or manifest.get( + "plan_hash" + ) not in {None, deployment.plan_hash}: + failures.append("launch manifest identity does not match deployment") + else: + candidate_group = int(manifest["process_group"]) + if _process_group_alive(candidate_group): + processes, process_error = _read_local_process_table() + if processes is None: + failures.append(process_error) + else: + members = tuple( + process + for process in processes + if process.process_group == candidate_group + and not process.zombie + ) + foreign = tuple( + process + for process in members + if not _belongs_to_launch( + process, + deployment_id=deployment.deployment_id, + ) + ) + if foreign: + identities = ", ".join( + f"pid {process.pid} state {process.status!r}" + for process in foreign[:4] + ) + failures.append( + "launch process-group identity changed " + f"({identities}); refusing to signal a reused PGID" + ) + elif members: + process_group = candidate_group + with suppress(ProcessLookupError): + os.killpg(candidate_group, signal.SIGTERM) + group_gone = _wait_for_process_group_exit( + candidate_group, + max(0.0, kill_grace), + ) + if not group_gone: + with suppress(ProcessLookupError): + os.killpg(candidate_group, signal.SIGKILL) + group_gone = _wait_for_process_group_exit( + candidate_group, + 2.0, + ) + if not group_gone: + failures.append( + f"process group {candidate_group} survived unload" + ) + + hosts = [ + {"rank": rank, "node_id": host.node_id, "ssh": host.ssh} + for rank, host in enumerate(deployment.hosts) + ] + failures.extend( + _sweep_rank_processes( + deployment.deployment_id, + hosts, + state_dir=state_dir, + plan_hash=deployment.plan_hash, + process_group=process_group, + kill_grace=kill_grace, + runner=runner, + ) + ) + failures = list(dict.fromkeys(failures)) + if failures: + detail = "; ".join(failures) + if any("survived" in item for item in failures): + detail += f". {_REBOOT_REQUIRED_GUIDANCE}" + raise DistributedTeardownError( + f"distributed unload of {deployment.deployment_id} could not be " + f"verified: {detail}" + ) + if manifest_path.exists(): + try: + manifest_path.unlink() + except OSError as exc: + raise DistributedTeardownError( + "rank exit was verified but the launch manifest could not be " + f"retired: {exc}" + ) from exc + return { + "verified": True, + "deployment_id": deployment.deployment_id, + "ranks_checked": len(hosts), + "manifest_retired": manifest is not None, + } + + +def reap_orphaned_launches( + state_dir: str | Path = "~/.omlx/cluster/runtime", + *, + kill_grace: float = 5.0, + runner: SSHRunner = subprocess.run, +) -> dict[str, Any]: + """Reap jobs whose coordinator died without tearing them down (G8). + + Every launch writes a manifest next to the runtime markers. A manifest + whose coordinator *and* launcher group are both gone belongs to a + crashed predecessor: any rank processes its markers still name are + orphans holding unified memory, so kill them and retire the manifest. + A manifest with a live coordinator is an active job and is left alone. + + Returns ``{"reaped": [...], "failures": [...], "active": [...]}``. + """ + + report: dict[str, Any] = {"reaped": [], "failures": [], "active": []} + root = Path(state_dir).expanduser() + if not root.exists(): + return report + try: + manifests = sorted(root.glob(f"{_LAUNCH_MANIFEST_PREFIX}*.json")) + except OSError as exc: + report["failures"].append(f"runtime state unavailable: {exc}") + return report + + for path in manifests: + manifest = _read_launch_manifest(path) + if manifest is None: + continue + deployment_id = manifest["deployment_id"] + coordinator_pid = manifest["coordinator_pid"] + launcher_pid = manifest["launcher_pid"] + if _pid_alive(coordinator_pid): + report["active"].append(deployment_id) + continue + # The coordinator is gone. Kill the launcher group if it somehow + # survived, then sweep rank processes by their marker pids. + if _process_group_alive(launcher_pid): + with suppress(ProcessLookupError, PermissionError): + os.killpg(launcher_pid, signal.SIGKILL) + failures = _sweep_rank_processes( + deployment_id, + manifest.get("hosts", []), + state_dir=state_dir, + plan_hash=manifest.get("plan_hash"), + kill_grace=kill_grace, + runner=runner, + ) + if failures: + report["failures"].extend( + f"{deployment_id}: {failure}" for failure in failures + ) + continue + report["reaped"].append(deployment_id) + with suppress(OSError): + path.unlink() + return report + + def _available_launch_ports( deployment: ClusterDeployment, ) -> tuple[int, int]: @@ -168,6 +987,23 @@ def _available_launch_ports( ) +def _available_control_port(host: str) -> int: + """Reserve a rank-zero TCP control port on the verified cluster address.""" + + try: + address = str(ipaddress.ip_address(host)) + except ValueError as exc: + raise DistributedLaunchError("rank-control host is not an IP address") from exc + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: + try: + listener.bind((address, 0)) + except OSError as exc: + raise DistributedLaunchError( + f"could not reserve rank-control port on {address}: {exc}" + ) from exc + return int(listener.getsockname()[1]) + + def _package_version(name: str) -> str: if name == "omlx": try: @@ -296,6 +1132,10 @@ def build_mlx_launch_argv( python_executable: str = sys.executable, cwd: Path | None = None, state_dir: str = "~/.omlx/cluster/runtime", + control_host: str | None = None, + control_port: int | None = None, + control_token: str | None = None, + load_timeout: float = 1800.0, ) -> list[str]: """Build an argument vector without a user-controlled shell fragment. @@ -323,6 +1163,24 @@ def build_mlx_launch_argv( raise ValueError(f"{label} must be between 1 and 65535") if api_port == collective_port: raise ValueError("API and collective ports must be distinct") + control_values = (control_host, control_port, control_token) + if any(value is not None for value in control_values) and not all( + value is not None for value in control_values + ): + raise ValueError("rank-control host, port, and token must be provided together") + if control_host is not None: + try: + control_host = str(ipaddress.ip_address(control_host)) + except ValueError as exc: + raise ValueError("rank-control host must be an IP address") from exc + if not 1 <= int(control_port) <= 65535: + raise ValueError("rank-control port must be between 1 and 65535") + try: + encoded_control_token = str(control_token).encode("ascii", "strict") + except UnicodeEncodeError as exc: + raise ValueError("rank-control token must be ASCII") from exc + if len(encoded_control_token) != 64: + raise ValueError("rank-control token must be 64 ASCII bytes") if cwd is not None and not cwd.is_absolute(): raise ValueError("distributed working directory must be absolute") @@ -367,6 +1225,8 @@ def build_mlx_launch_argv( deployment.backend, "--port", str(api_port), + "--load-timeout", + str(load_timeout), "--deployment-id", deployment.deployment_id, "--plan-hash", @@ -395,6 +1255,21 @@ def build_mlx_launch_argv( deployment.execution.tuning_reason, ] ) + if ( + control_host is not None + and control_port is not None + and control_token is not None + ): + argv.extend( + [ + "--control-host", + control_host, + "--control-port", + str(control_port), + "--control-token", + control_token, + ] + ) if deployment.execution.prompt_cache_bytes is not None: argv.extend( [ @@ -1744,6 +2619,8 @@ def __init__( self.process: subprocess.Popen[str] | None = None self.port: int | None = None self.collective_port: int | None = None + self.control_port: int | None = None + self.control_token: str | None = None self.ready_event: dict[str, Any] | None = None self.rank_ready_events: dict[int, dict[str, Any]] = {} self.failure_event: dict[str, Any] | None = None @@ -1761,12 +2638,27 @@ def endpoint(self) -> str | None: def start(self) -> dict[str, Any]: if self.process is not None: raise RuntimeError("distributed job is already started") + # A previous coordinator may have died mid-job (G8); reap its + # leftover ranks before admitting a new launch against the memory + # ceiling. Best effort: reaping must never block a launch. + try: + orphan_report = reap_orphaned_launches(self.state_dir) + if orphan_report["reaped"] or orphan_report["failures"]: + logger.warning( + "Reaped orphaned distributed launches: %s", orphan_report + ) + except Exception as exc: # pragma: no cover - defensive + logger.warning("Orphaned-launch reaper failed: %s", exc) self._phase = "preflight" if self.preflight: preflight_remote_hosts( self.deployment, python_executable=self.python_executable, ) + # A deployment ID and plan hash are stable across reloads. Remove the + # prior launch's gate before any rank can mistake it for this launch's + # release signal. + _set_serve_release(self.deployment, self.state_dir, None) self._temporary = tempfile.TemporaryDirectory(prefix="omlx-distributed-launch-") hostfile = Path(self._temporary.name) / "hostfile.json" @@ -1780,6 +2672,12 @@ def start(self) -> dict[str, Any]: encoding="utf-8", ) self.port, self.collective_port = _available_launch_ports(self.deployment) + control_host = self.deployment.hosts[0].ips[0] + self.control_port = _available_control_port(control_host) + # The plan hash is public deployment identity, not authentication. + # Mint a fresh launch-scoped secret so an unauthenticated peer on the + # fabric cannot join rank control by reading the signed plan. + self.control_token = secrets.token_hex(32) argv = build_mlx_launch_argv( self.deployment, hostfile=hostfile, @@ -1788,6 +2686,10 @@ def start(self) -> dict[str, Any]: python_executable=self.python_executable, cwd=self.cwd, state_dir=self.state_dir, + control_host=control_host, + control_port=self.control_port, + control_token=self.control_token, + load_timeout=self.load_timeout, ) self._phase = "loading" try: @@ -1807,14 +2709,35 @@ def start(self) -> dict[str, Any]: env=environment, start_new_session=True, ) + self._write_launch_manifest() self._start_readers() event = self._wait_for_ready() + _set_serve_release( + self.deployment, + self.state_dir, + { + "schema_version": 1, + "deployment_id": self.deployment.deployment_id, + "plan_hash": self.deployment.plan_hash, + "world_size": self.deployment.world_size, + "released_at": time.time(), + }, + ) self._wait_for_listener() self._phase = "ready" self.ready_event = event return event except Exception: - self._terminate() + # A failed start still owns a spawned group; tear it down, but + # never mask the launch error with a teardown error. + try: + self._terminate() + except Exception: + logger.error( + "Teardown after failed distributed start also failed; " + "the launch manifest lets a later sweep reap the job", + exc_info=True, + ) raise def _start_readers(self) -> None: @@ -1857,6 +2780,33 @@ def _drain( self.rank_ready_events[rank] = event elif event.get("reason") or event.get("error"): self.failure_event = event + # mlx.launch does not emit a structured event when a native + # JACCL watchdog terminates a rank. Worse, its SSH cleanup + # thread can raise after that and leave the launcher itself + # exiting with code zero. Promote the exact native terminal + # lines into the same failure surface used by peer_lost so a + # dead rank can never remain phase=ready. + no_progress = _JACCL_NO_PROGRESS_RE.search(line) + if no_progress is not None: + self.failure_event = { + "type": "collective_stall", + "reason": "JACCL " + no_progress.group("reason").strip(), + } + rank_exit = _LAUNCHER_RANK_EXIT_RE.search(line) + if rank_exit is not None and int(rank_exit.group("code")) != 0: + reason = ( + f"rank {rank_exit.group('rank')} exited with code " + f"{rank_exit.group('code')}" + ) + prior = self._failure_reason() + if prior and prior not in reason: + reason += f" after {prior}" + self.failure_event = { + "type": "rank_exit", + "rank": int(rank_exit.group("rank")), + "returncode": int(rank_exit.group("code")), + "reason": reason, + } self._condition.notify_all() def _wait_for_ready(self) -> dict[str, Any]: @@ -1933,14 +2883,96 @@ def _wait_for_listener(self) -> None: def stop(self) -> None: self._terminate() + def _write_launch_manifest(self) -> None: + process = self.process + if process is None: + return + try: + _write_launch_manifest( + self.state_dir, + self.deployment, + launcher_pid=process.pid, + api_port=self.port, + ) + except OSError as exc: + # The manifest is the crashed-coordinator recovery path; losing + # it must not fail an otherwise healthy launch. + logger.warning("Could not write the launch manifest: %s", exc) + + def _remove_launch_manifest(self) -> None: + with suppress(OSError): + _launch_manifest_path( + self.state_dir, + self.deployment.deployment_id, + ).unlink(missing_ok=True) + + def _sweep_rank_leftovers( + self, + *, + process_group: int | None = None, + kill_grace: float = 3.0, + ) -> list[str]: + """Kill rank processes that outlived the launcher group. + + Returns failure descriptions; empty means nothing resident remains. + """ + + return _sweep_rank_processes( + self.deployment.deployment_id, + [ + {"rank": rank, "node_id": host.node_id, "ssh": host.ssh} + for rank, host in enumerate(self.deployment.hosts) + ], + state_dir=self.state_dir, + plan_hash=self.deployment.plan_hash, + process_group=process_group, + kill_grace=kill_grace, + ) + def _terminate(self) -> None: + """Tear the job down and *prove* the teardown worked. + + ``stop()`` used to report success after a best-effort SIGKILL: the + ``_wait_for_process_group_exit`` result was ignored, so a rank that + survived (unkillable Metal/JACCL kernel wait, D-state, or a + ``PermissionError`` that ``_process_group_alive`` deliberately reads + as alive) kept its unified-memory allocation resident while the + engine pool had already released the model's memory budget (G1). + + Teardown now verifies the final SIGKILL, retries once, then sweeps + leftover rank processes by their runtime-marker pids — including + remote ranks, which killpg can never reach (G2). If anything still + survives, ``DistributedTeardownError`` is raised and the process + reference is kept so a later ``stop()`` retries the kill instead of + dropping all state. The launch manifest is removed only after + verified exit, so a crashed coordinator leaves ``reap_orphaned_ + launches`` enough evidence to finish the job (G8). + """ + process = self.process if process is not None: process_group = process.pid deadline = time.monotonic() + self.stop_timeout + group_signal_denied = False if _process_group_alive(process_group): - with suppress(ProcessLookupError): + try: os.killpg(process_group, signal.SIGTERM) + except ProcessLookupError: + pass + except PermissionError as exc: + # The launcher may already be reaped while macOS has + # recycled its PGID for a foreign process. Never signal a + # group we cannot prove we own. We can still complete a + # safe teardown after waitpid confirms our launcher exited + # and the deployment-marker sweep proves no rank survived. + group_signal_denied = True + logger.warning( + "Could not signal former distributed process group %d " + "(%s); verifying launcher exit and sweeping rank " + "markers instead", + process_group, + exc, + ) if process.poll() is None: with suppress(subprocess.TimeoutExpired): process.wait(timeout=max(0.0, deadline - time.monotonic())) @@ -1950,11 +2982,62 @@ def _terminate(self) -> None: # that rank orphaned (PPID 1) and its unified-memory allocation # resident. Stop is complete only when the entire launch process # group has disappeared. - remaining = max(0.0, deadline - time.monotonic()) - if not _wait_for_process_group_exit(process_group, remaining): - with suppress(ProcessLookupError): - os.killpg(process_group, signal.SIGKILL) - _wait_for_process_group_exit(process_group, 2.0) + if group_signal_denied: + group_gone = process.poll() is not None + else: + remaining = max(0.0, deadline - time.monotonic()) + group_gone = _wait_for_process_group_exit(process_group, remaining) + for attempt in (1, 2): + if group_gone: + break + logger.error( + "Distributed process group %d survived SIGKILL " + "(attempt %d/2); %s", + process_group, + attempt, + "retrying" if attempt == 1 else "sweeping rank markers", + ) + try: + os.killpg(process_group, signal.SIGKILL) + except ProcessLookupError: + pass + except PermissionError as exc: + logger.warning( + "Could not SIGKILL distributed process group %d: %s", + process_group, + exc, + ) + break + group_gone = _wait_for_process_group_exit(process_group, 2.0) + + # A rank that escaped the group (reparented before the kill) + # survives a verified group exit; sweep it by its marker pid. + leftovers = self._sweep_rank_leftovers( + process_group=None if group_signal_denied else process_group + ) + if ( + not group_signal_denied + and not group_gone + and not _process_group_alive(process_group) + ): + group_gone = True + if not group_gone or leftovers: + problems = [] + if not group_gone: + problems.append( + ( + f"launcher {process.pid} did not exit after process-group " + "permission denial" + ) + if group_signal_denied + else f"process group {process_group} survived SIGKILL twice" + ) + problems.extend(leftovers) + raise DistributedTeardownError( + f"distributed teardown of " + f"{self.deployment.deployment_id} could not be verified: " + + "; ".join(problems) + ) if process.poll() is None: with suppress(subprocess.TimeoutExpired): process.wait(timeout=2.0) @@ -1969,10 +3052,15 @@ def _terminate(self) -> None: self.process = None self.port = None self.collective_port = None + self.control_port = None + self.control_token = None self.ready_event = None self.rank_ready_events.clear() self.failure_event = None self._phase = "stopped" + self._remove_launch_manifest() + with suppress(Exception): + _set_serve_release(self.deployment, self.state_dir, None) if self._temporary is not None: self._temporary.cleanup() self._temporary = None @@ -2189,12 +3277,27 @@ def _failure_detail(self) -> str: def status(self) -> DistributedJobStatus: process = self.process + returncode = process.poll() if process is not None else None + phase = self._phase + failure_reason = self._failure_reason() + if phase != "stopped" and (failure_reason or returncode is not None): + phase = "failed" + if failure_reason is None: + failure_reason = self._runtime_failure_reason() + if failure_reason is None: + # A serving launcher ending is terminal even when mlx.launch + # accidentally reports success after a worker's cleanup thread + # failed. Stop/unload clears ``process`` and phase afterwards; + # while it remains registered this is always unexpected. + failure_reason = ( + f"distributed launcher exited unexpectedly with code {returncode}" + ) return DistributedJobStatus( deployment_id=self.deployment.deployment_id, - phase=self._phase, + phase=phase, endpoint=self.endpoint, pid=process.pid if process is not None else None, - returncode=process.poll() if process is not None else None, + returncode=returncode, world_size=self.deployment.world_size, plan_hash=self.deployment.plan_hash, stderr_tail=tuple(self._stderr)[-20:], diff --git a/omlx/cluster/liveness.py b/omlx/cluster/liveness.py index f8c10d0b91..f51776509a 100644 --- a/omlx/cluster/liveness.py +++ b/omlx/cluster/liveness.py @@ -26,6 +26,7 @@ from __future__ import annotations import json +import logging import os import shlex import subprocess @@ -37,6 +38,8 @@ from .ssh_policy import cluster_ssh_options +logger = logging.getLogger(__name__) + # A rank refreshes its marker on every phase change, while serving, and on a # fixed heartbeat interval even when idle (``RuntimeTelemetry``). Three missed # intervals distinguishes "busy with a long prefill" from "gone". @@ -76,7 +79,9 @@ def healthy(self) -> bool: return False if not self.heartbeat_required: return True - return self.seconds_since_heartbeat is not None and self.process_live is not False + return ( + self.seconds_since_heartbeat is not None and self.process_live is not False + ) @property def stale(self) -> bool: @@ -286,7 +291,9 @@ def marker_owner_is_live(marker: dict[str, Any]) -> bool: return _pid_is_live(pid) -def marker_age_seconds(marker: dict[str, Any], *, now: float | None = None) -> float | None: +def marker_age_seconds( + marker: dict[str, Any], *, now: float | None = None +) -> float | None: """Seconds since a rank last refreshed its marker.""" from datetime import UTC, datetime @@ -456,6 +463,8 @@ def __init__( interval: float = 15.0, serving_interval: float | None = None, on_lost: Callable[[str], None] | None = None, + on_abort: Callable[[str], None] | None = None, + abort_grace: float = 5.0, failure_tolerance: int = _DEFAULT_FAILURE_TOLERANCE, ) -> None: self._hosts = hosts_by_rank @@ -473,10 +482,16 @@ def __init__( else max(0.0, float(serving_interval)) ) self._on_lost = on_lost + # Graduated response: once a peer is confirmed lost, fire on_abort + # (request cancellation at a step boundary) and re-probe for up to + # abort_grace seconds before the final on_lost exit, so a recoverable + # flap no longer suicides the healthy rank and in-flight work gets a + # chance to unwind. With on_abort unset or abort_grace=0 the timing + # is exactly the old fire-on-tolerance behavior. + self._on_abort = on_abort + self._abort_grace = max(0.0, float(abort_grace)) self._failure_tolerance = max(1, int(failure_tolerance)) - self._consecutive_failures: dict[int, int] = { - rank: 0 for rank in hosts_by_rank - } + self._consecutive_failures: dict[int, int] = {rank: 0 for rank in hosts_by_rank} self._stop = False def stop(self) -> None: @@ -527,6 +542,43 @@ def run(self, *, sleep: Callable[[float], None] = time.sleep) -> None: if not failed_ranks: continue failed = tuple(item for item in health if item.rank in failed_ranks) + reason = describe_failure(failed) + # Graduated response: request cancellation first, exit last. + if self._on_abort is not None and self._abort_grace > 0: + logger.warning( + "Peer watchdog: %s — aborting in-flight requests and " + "allowing %.1fs of recovery before teardown", + reason, + self._abort_grace, + ) + try: + self._on_abort(reason) + except Exception: + logger.warning("Peer watchdog abort stage failed", exc_info=True) + if self._wait_for_recovery(sleep): + for rank in failed_ranks: + self._consecutive_failures[rank] = 0 + continue if self._on_lost is not None: - self._on_lost(describe_failure(failed)) + self._on_lost(reason) return + + def _wait_for_recovery(self, sleep: Callable[[float], None]) -> bool: + """Re-probe during the abort grace; True if every peer recovered.""" + + deadline = time.monotonic() + self._abort_grace + while not self._stop: + remaining = deadline - time.monotonic() + if remaining <= 0: + return False + sleep(min(0.5, remaining)) + if self._stop: + return False + try: + health = self.run_once() + except Exception: + continue + if health and all(item.healthy for item in health): + logger.warning("Peer watchdog: peer contact recovered") + return True + return False diff --git a/omlx/cluster/performance_worker.py b/omlx/cluster/performance_worker.py index a1c11ba779..355c8dd7df 100644 --- a/omlx/cluster/performance_worker.py +++ b/omlx/cluster/performance_worker.py @@ -5,6 +5,7 @@ import argparse import json +import os import time from datetime import UTC, datetime from typing import Any @@ -59,10 +60,16 @@ def _collective_measurements( return float(latency), float(bandwidth) -def run_probe(args: argparse.Namespace) -> dict[str, Any]: +def _run_probe(args: argparse.Namespace) -> dict[str, Any]: import mlx.core as mx - group = mx.distributed.init() + from .jaccl_side_channel import init_cluster_group + + group = init_cluster_group( + mx, + backend="jaccl" if os.environ.get("MLX_JACCL_COORDINATOR") else None, + strict=bool(os.environ.get("MLX_JACCL_COORDINATOR")), + ) rank = group.rank() barrier = mx.distributed.all_sum(mx.array(1), stream=mx.cpu) _evaluate(mx, barrier) @@ -103,6 +110,22 @@ def run_probe(args: argparse.Namespace) -> dict[str, Any]: } +def run_probe(args: argparse.Namespace) -> dict[str, Any]: + if not os.environ.get("MLX_JACCL_COORDINATOR"): + return _run_probe(args) + + from .jaccl_lease import acquire_jaccl_communicator_lease + + with acquire_jaccl_communicator_lease( + deployment_id="performance-probe", + state_dir=os.environ.get( + "OMLX_CLUSTER_STATE_DIR", + "~/.omlx/cluster/runtime", + ), + ): + return _run_probe(args) + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Internal oMLX performance probe") parser.add_argument("--payload-bytes", type=int, default=1024**2) diff --git a/omlx/cluster/progressive_loading.py b/omlx/cluster/progressive_loading.py index 1ad943481d..5de4ac7f89 100644 --- a/omlx/cluster/progressive_loading.py +++ b/omlx/cluster/progressive_loading.py @@ -236,14 +236,12 @@ def progressive_sharded_load( if progress is not None: progress({"phase": "tensor_ready", "strategy": strategy}) - # CPU synchronization avoids Metal watchdog timeouts while other ranks - # finish their last layer. - mx_module.eval( - mx_module.distributed.all_sum( - mx_module.array(1.0), - stream=mx_module.cpu, - ) - ) + # Do not add a final collective here. Every tensor above has already been + # materialized locally, and the launcher withholds the endpoint until it + # has received ``rank_ready`` from every member. A redundant CPU-stream + # all-reduce at peak wired-memory pressure can lose a JACCL completion and + # tear down an otherwise complete load. Rank markers are the load barrier; + # the first inference request cannot arrive before all of them are ready. if return_config: return model, tokenizer, config return model, tokenizer diff --git a/omlx/cluster/prompt_snapshot_cache.py b/omlx/cluster/prompt_snapshot_cache.py index f08840589d..0fc0686dfa 100644 --- a/omlx/cluster/prompt_snapshot_cache.py +++ b/omlx/cluster/prompt_snapshot_cache.py @@ -29,16 +29,19 @@ and lives in the telemetry integration, which has the collective; this module stays pure and unit-testable. -Snapshots are process-lifetime. The digest filenames cannot be re-indexed -without their token tuples, and a file that is not in the index is invisible to -hits yet still holds disk, so a new store starts by clearing its directory and -the telemetry teardown removes it. A rank that restarts simply begins empty, -which the boundary vote already handles. +When persistence is enabled, a compact atomic manifest records the digest, +boundary and byte size of every chain segment. The digest already commits to +the model identity and exact prefix tokens, so the manifest does not duplicate +the token arrays (which would grow quadratically at long context). Directories +are scoped by plan hash and rank by the worker, preventing a changed tensor +split from ever reading another shard layout. A missing or invalid manifest +fails closed by clearing otherwise-unindexable files. """ from __future__ import annotations import hashlib +import json import logging import os import struct @@ -315,6 +318,7 @@ class _Entry: tokens: tuple[int, ...] filename: str nbytes: int + boundary: int def candidate_boundaries(prompt_len: int, step: int) -> tuple[int, ...]: @@ -377,11 +381,13 @@ def __init__( step: int = 2048, max_entries: int = _MAX_ENTRIES_DEFAULT, max_bytes: int | None = None, + persistent: bool = False, ) -> None: self.directory = Path(directory) self.step = max(1, int(step)) self.max_entries = max(1, int(max_entries)) self.max_bytes = max_bytes + self.persistent = bool(persistent) self._lock = threading.RLock() # Access-ordered: most-recently-used at the end. The order is advanced # only by put/load, both driven by the identical request stream every @@ -396,18 +402,31 @@ def __init__( self._serialisable = True _register_snapshot_classes() self.directory.mkdir(parents=True, exist_ok=True) - # Snapshots are process-lifetime (see the module docstring): whatever a - # dead process left behind is unreachable, so reclaim it up front and - # keep the directory exactly as large as the live index says it is. - for stale in self.directory.iterdir(): - if stale.is_file(): - with suppress(OSError): - stale.unlink() + if self.persistent: + self._load_manifest_or_reset() + else: + self._clear_directory() def __len__(self) -> int: with self._lock: return len(self._index) + def clear(self, timeout: float = 30.0) -> int: + """Atomically forget every live snapshot and reset its manifest. + + This split writes snapshots synchronously, so there is no write-behind + queue to flush. ``timeout`` is accepted for parity with the rank cache + maintenance hook and with the later asynchronous store. + """ + + del timeout + with self._lock: + count = len(self._index) + self._clear_directory() + self._serialisable = True + self._persist_index_locked() + return count + @property def nbytes(self) -> int: with self._lock: @@ -416,6 +435,108 @@ def nbytes(self) -> int: def _path(self, key: str) -> Path: return self.directory / f"{key}.safetensors" + @property + def _manifest_path(self) -> Path: + return self.directory / "index.json" + + def _clear_directory(self) -> None: + self._index.clear() + self._nbytes = 0 + for stale in self.directory.iterdir(): + if stale.is_file(): + with suppress(OSError): + stale.unlink() + + @staticmethod + def _valid_key(value: object) -> bool: + return bool( + isinstance(value, str) + and len(value) == 64 + and all(ch in "0123456789abcdef" for ch in value) + ) + + def _load_manifest_or_reset(self) -> None: + """Restore the durable LRU, or fail closed on any malformed state.""" + + manifest = self._manifest_path + if not manifest.is_file(): + self._clear_directory() + self._persist_index_locked() + return + try: + payload = json.loads(manifest.read_text(encoding="utf-8")) + if payload.get("version") != 1 or int(payload.get("step")) != self.step: + raise ValueError("snapshot manifest contract changed") + rows = payload.get("entries") + if not isinstance(rows, list): + raise ValueError("snapshot manifest entries are invalid") + indexed_files = {manifest.name} + for row in rows: + if not isinstance(row, dict): + raise ValueError("snapshot manifest entry is invalid") + key = row.get("key") + filename = row.get("filename") + boundary = int(row.get("boundary")) + nbytes = int(row.get("nbytes")) + if ( + not self._valid_key(key) + or filename != f"{key}.safetensors" + or boundary <= 0 + or boundary % self.step != 0 + or nbytes <= 0 + ): + raise ValueError("snapshot manifest entry is unsafe") + path = self.directory / filename + if key in self._index: + raise ValueError("snapshot manifest contains a duplicate key") + if not path.is_file() or path.stat().st_size != nbytes: + raise ValueError("snapshot manifest file is missing or changed") + self._index[key] = _Entry((), filename, nbytes, boundary) + self._nbytes += nbytes + indexed_files.add(filename) + for stale in self.directory.iterdir(): + if stale.is_file() and stale.name not in indexed_files: + with suppress(OSError): + stale.unlink() + self._evict_locked() + self._persist_index_locked() + except Exception as error: + logger.warning("resetting invalid prompt snapshot manifest: %s", error) + self._clear_directory() + self._persist_index_locked() + + def _persist_index_locked(self) -> None: + if not self.persistent: + return + payload = { + "version": 1, + "step": self.step, + "entries": [ + { + "key": key, + "filename": entry.filename, + "nbytes": entry.nbytes, + "boundary": entry.boundary, + } + for key, entry in self._index.items() + ], + } + descriptor, temporary = tempfile.mkstemp( + prefix=".index.", suffix=".json", dir=self.directory + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + json.dump(payload, handle, separators=(",", ":"), sort_keys=True) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, self._manifest_path) + except OSError as error: + with suppress(OSError): + os.close(descriptor) + with suppress(OSError): + os.unlink(temporary) + logger.warning("could not persist prompt snapshot manifest: %s", error) + def _chain_keys(self, model: Any, tokens: tuple[int, ...]) -> list[str]: """Digest per chain boundary, shortest first, sharing one hash walk.""" @@ -450,8 +571,12 @@ def put(self, model: Any, tokens: list[int], cache: list[Any]) -> bool: key = self._chain_keys(model, token_tuple)[-1] with self._lock: entry = self._index.get(key) - if entry is not None and entry.tokens == token_tuple: + if entry is not None and ( + entry.tokens == token_tuple + or (not entry.tokens and entry.boundary == boundary) + ): self._index.move_to_end(key) + self._persist_index_locked() return True wrapped = _wrap_for_save( cache, boundary=boundary, segment_start=boundary - self.step @@ -491,10 +616,11 @@ def put(self, model: Any, tokens: list[int], cache: list[Any]) -> bool: previous = self._index.pop(key, None) if previous is not None: self._nbytes -= previous.nbytes - self._index[key] = _Entry(token_tuple, target.name, size) + self._index[key] = _Entry(token_tuple, target.name, size, boundary) self._nbytes += size self._index.move_to_end(key) self._evict_locked() + self._persist_index_locked() return True def present_boundaries(self, model: Any, tokens: list[int]) -> tuple[int, ...]: @@ -512,7 +638,10 @@ def present_boundaries(self, model: Any, tokens: list[int]) -> tuple[int, ...]: entry = self._index.get(key) if ( entry is None - or entry.tokens != token_tuple[:boundary] + or ( + entry.tokens != token_tuple[:boundary] + and not (not entry.tokens and entry.boundary == boundary) + ) or not self._path(key).is_file() ): break @@ -532,11 +661,16 @@ def load(self, model: Any, tokens: list[int], boundary: int) -> list[Any] | None for position, key in enumerate(chain): entry = self._index.get(key) prefix = token_tuple[: (position + 1) * self.step] - if entry is None or entry.tokens != prefix: + expected_boundary = (position + 1) * self.step + if entry is None or ( + entry.tokens != prefix + and not (not entry.tokens and entry.boundary == expected_boundary) + ): return None if not self._path(key).is_file(): self._index.pop(key, None) self._nbytes -= entry.nbytes + self._persist_index_locked() return None try: files = [load_prompt_cache(str(self._path(key))) for key in chain] @@ -549,6 +683,7 @@ def load(self, model: Any, tokens: list[int], boundary: int) -> list[Any] | None for key in chain: if key in self._index: self._index.move_to_end(key) + self._persist_index_locked() return assembled def _evict_locked(self) -> None: diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index c592e95298..da57bf22d6 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -37,6 +37,11 @@ preflight_issues, tp_groups_spanning_slow_links, ) +from .backends import ( + MemberFabric, + members_from_host_records, + select_cluster_backend, +) from .catalogue import ModelFit, assess_model, catalogue_for_cluster from .collective import ( CollectiveSmokeError, @@ -60,11 +65,13 @@ from .launch import ( CudaFabricProbeHost, DistributedLaunchError, + DistributedTeardownError, preflight_remote_hosts, probe_remote_admission_ceiling, probe_remote_host, run_cluster_performance_probe, run_cuda_fabric_probe, + stop_deployment_processes, ) from .liveness import ( PeerLostError, @@ -2626,6 +2633,47 @@ async def cluster_plan(request: ClusterPlanRequest): return _plan_with_signature(plan.to_dict()) +class ClusterBackendMemberRequest(BaseModel): + """One member's observed RDMA capability, from local or peer probes.""" + + node_id: str = Field(min_length=1, max_length=128) + rdma_ctl_enabled: bool = False + rdma_devices: list[str] = Field(default_factory=list, max_length=16) + + +class ClusterBackendSelectionRequest(BaseModel): + """Which collective backend should this exact member set use?""" + + members: list[ClusterBackendMemberRequest] = Field(min_length=2, max_length=64) + + +@router.post("/backend-selection") +async def cluster_backend_selection( + request: ClusterBackendSelectionRequest, +) -> dict[str, Any]: + """jaccl when rdma_ctl is enabled on ALL members, else the TCP ring. + + The plan view renders this decision (including which members block JACCL) + before anyone approves a placement; the replan endpoint makes the same + call when asked for ``backend="auto"``. + """ + + try: + selection = select_cluster_backend( + tuple( + MemberFabric( + node_id=member.node_id.strip(), + rdma_ctl_enabled=member.rdma_ctl_enabled, + rdma_devices=tuple(member.rdma_devices), + ) + for member in request.members + ) + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + return selection.to_dict() + + def _deployment_id(model_path: Path, plan_hash: str) -> str: slug = re.sub(r"[^A-Za-z0-9._-]+", "-", model_path.name).strip("-._") return f"{slug or 'model'}-{plan_hash[:12]}" @@ -3405,7 +3453,13 @@ async def _activate_and_report( ) canary = await engine.generate( "__omlx_cluster_readiness__", - max_tokens=1, + # A one-token GenerationBatch still pipelines and then + # discards a successor graph. That terminal-only boundary can + # leave a peer inside its final JACCL all-reduce even though + # rank zero already produced a valid response. Four tokens + # exercise sustained synchronized decode and make readiness a + # stronger, representative proof. + max_tokens=4, temperature=0.0, top_p=1.0, top_k=0, @@ -3544,7 +3598,7 @@ class ClusterReplanRequest(BaseModel): model_path: str | None = Field(default=None, max_length=4096) model_source: str | None = Field(default=None, max_length=255) model_source_python: str | None = Field(default=None, max_length=4096) - backend: Literal["ring", "jaccl", "jaccl-ring"] | None = None + backend: Literal["auto", "ring", "jaccl", "jaccl-ring"] | None = None nodes: list[ClusterPlanNodeRequest] | None = Field( default=None, min_length=2, max_length=64 ) @@ -3652,6 +3706,25 @@ async def replan_cluster_deployment(request: ClusterReplanRequest): # shared path. Carry them forward unless the caller overrides. path_map = dict(current.path_map) derived["path_map"] = True + if backend == "auto": + # rdma_ctl on every member → jaccl; any member without it pulls the + # whole cluster onto the TCP ring. Derived from the posted host + # records; launch preflight re-verifies the live state. + try: + selection = select_cluster_backend(members_from_host_records(hosts)) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + backend_decision: dict[str, Any] = selection.to_dict() + backend = selection.backend + else: + backend_decision = { + "backend": backend, + "reason": "operator-selected backend", + "blockers": [], + "members": [ + member.to_dict() for member in members_from_host_records(hosts) + ], + } try: _validate_cluster_hosts(hosts) effective = ClusterDeploymentRequest( @@ -3715,6 +3788,7 @@ async def replan_cluster_deployment(request: ClusterReplanRequest): "changes": changes, "deployment_id": deployment.deployment_id, "backend": deployment.backend, + "backend_decision": backend_decision, "plan": signed_plan, } @@ -3735,6 +3809,7 @@ async def replan_cluster_deployment(request: ClusterReplanRequest): "replan": { "steps": list(_REPLAN_STEPS), "derived": derived, + "backend_decision": backend_decision, "previous": ( summarize_deployment(current) if current is not None else None ), @@ -3759,6 +3834,7 @@ async def deactivate_cluster_deployment(deployment_id: str): model_id = None if model_id is not None: await pool.prepare_cluster_reload(model_id) + await asyncio.to_thread(stop_deployment_processes, deployment) removed = await asyncio.to_thread(registry.remove, deployment_id) unregister = getattr(pool, "unregister_cluster_model", None) if model_id is not None and callable(unregister): @@ -3780,3 +3856,110 @@ async def deactivate_cluster_deployment(deployment_id: str): "deployment_id": deployment_id, "stopped": True, } + + +@router.post("/deployments/{deployment_id}/unload") +async def unload_cluster_deployment(deployment_id: str): + """Release resident ranks while keeping the signed deployment configured.""" + + registry = get_cluster_registry() + deployment = await asyncio.to_thread(registry.get, deployment_id) + if deployment is None: + raise HTTPException(status_code=404, detail="cluster deployment not found") + model_id = None + try: + pool = _engine_pool() + model_id = pool.resolve_cluster_model_id(deployment.model) + entry = pool.get_entry(model_id) + if entry is not None and entry.engine is not None: + await pool.prepare_cluster_reload(model_id) + except ModelNotFoundError: + # A configured deployment may legitimately be cold after restart. + # Keeping unload idempotent lets the dashboard recover without + # reconstructing EnginePool's private registration state. + model_id = None + except ModelBusyError as exc: + raise HTTPException( + status_code=409, + detail=( + "The cluster is serving a request. It will not be interrupted; " + "unload it after the request finishes." + ), + ) from exc + except RuntimeError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + try: + teardown = await asyncio.to_thread(stop_deployment_processes, deployment) + except (DistributedTeardownError, DistributedLaunchError, RuntimeError) as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + return { + "ok": True, + "deployment_id": deployment_id, + "model_id": model_id, + "stopped": True, + "configured": True, + "teardown": teardown, + } + + +@router.post("/deployments/{deployment_id}/load") +async def load_cluster_deployment(deployment_id: str): + """Load a configured deployment and prove all ranks with a short canary.""" + + registry = get_cluster_registry() + deployment = await asyncio.to_thread(registry.get, deployment_id) + if deployment is None: + raise HTTPException(status_code=404, detail="cluster deployment not found") + try: + pool = _engine_pool() + try: + model_id = pool.resolve_cluster_model_id(deployment.model) + except ModelNotFoundError: + register = getattr(pool, "register_cluster_model", None) + if not callable(register): + raise + estimated_size = sum( + assignment.planned_weight_bytes + for assignment in deployment.assignments + ) + model_id, _ = register( + deployment.model, + estimated_size=estimated_size, + ) + entry = pool.get_entry(model_id) + resident = getattr(entry, "engine", None) if entry is not None else None + if resident is not None and getattr( + resident, "runtime_failed_reason", None + ): + await pool.prepare_cluster_reload(model_id) + engine = await pool.get_engine(model_id) + if getattr(engine, "deployment", None) != deployment: + raise DistributedLaunchError( + "engine pool did not load the configured distributed plan" + ) + canary = await engine.generate( + "__omlx_cluster_readiness__", + max_tokens=4, + temperature=0.0, + top_p=1.0, + top_k=0, + _request_id="omlx-internal-readiness", + ) + status = engine.cluster_status() + except ModelBusyError as exc: + raise HTTPException( + status_code=409, + detail="The model is already changing state; wait and try again.", + ) from exc + except (DistributedLaunchError, RuntimeError) as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + except ModelNotFoundError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + return { + "ok": True, + "deployment_id": deployment_id, + "model_id": model_id, + "loaded": True, + "canary_completion_tokens": canary.completion_tokens, + "ranks": status.get("ranks", []), + } diff --git a/omlx/cluster/runtime.py b/omlx/cluster/runtime.py index 5ab0c5573c..9203b3ecec 100644 --- a/omlx/cluster/runtime.py +++ b/omlx/cluster/runtime.py @@ -577,7 +577,18 @@ def read_runtime_markers( jobs: list[dict[str, Any]] = [] warnings: list[str] = [] - candidates = [path for path in entries if path.name.endswith(".json")] + # The runtime directory also owns launch manifests and one-shot control + # files. They are JSON by design but are not rank markers; parsing them as + # such produced persistent false warnings in the dashboard after every + # cancellation, unload, or reboot. + control_suffixes = ("-cancel.json", "-cancel-ack.json", "-serve.json") + candidates = [ + path + for path in entries + if path.name.endswith(".json") + and not path.name.startswith("launch-") + and not path.name.endswith(control_suffixes) + ] if len(candidates) > _MAX_MARKERS: warnings.append(f"runtime marker limit exceeded; showing first {_MAX_MARKERS}") for path in candidates[:_MAX_MARKERS]: diff --git a/omlx/cluster/telemetry.py b/omlx/cluster/telemetry.py index 772573b240..29aed34702 100644 --- a/omlx/cluster/telemetry.py +++ b/omlx/cluster/telemetry.py @@ -3,14 +3,18 @@ from __future__ import annotations +import json import logging import math +import os import shutil +import struct import threading import time from collections.abc import Iterator -from contextlib import contextmanager +from contextlib import contextmanager, suppress from dataclasses import dataclass +from pathlib import Path from typing import Any, Protocol from .performance import ExecutionSettings @@ -18,6 +22,9 @@ logger = logging.getLogger(__name__) +# Bounded read for the coordinator's cancel-request file. +_MAX_CANCEL_FILE_BYTES = 64 * 1024 + # How often a rank refreshes its marker with nothing to report. # # Every other publish is request-driven, so an idle deployment's marker simply @@ -30,6 +37,55 @@ # heartbeats can be missed before anything is called stale, and long enough that # it never competes with generation for the lock. _DEFAULT_HEARTBEAT_INTERVAL = 10.0 +_MAX_TRANSPORT_REQUEST_ID_BYTES = 128 +_MAX_TARGETED_CANCEL_REQUESTS = 256 +_CANCEL_VOTE_KIND = "omlx.cancel_vote" +_CANCEL_VOTE_SCHEMA_VERSION = 1 + + +def _transport_request_id(value: Any) -> str | None: + """Validate the private coordinator-to-rank request correlation id.""" + + if not isinstance(value, str) or not value: + return None + try: + encoded = value.encode("ascii") + except UnicodeEncodeError: + return None + if len(encoded) > _MAX_TRANSPORT_REQUEST_ID_BYTES: + return None + allowed = frozenset( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.:" + ) + return value if all(character in allowed for character in value) else None + + +def _python_token_id(value: Any) -> int: + """Normalize a generated token to a Python signed-32-bit index. + + MLX samplers may surface a uint32 scalar (or a one-element nested list + after ``tolist``). Those are valid model values but some MLX releases + reject them as ``array[index]`` objects. The private server indexes the + response logprob row after BatchGenerator.next(), so normalize at that + queue boundary without touching the device-side token graph. + """ + + while isinstance(value, (list, tuple)): + if len(value) != 1: + raise ValueError("generated token must be a scalar") + value = value[0] + item = getattr(value, "item", None) + if callable(item) and not isinstance(value, (int, bool)): + value = item() + if isinstance(value, bool): + raise ValueError("generated token must be an integer") + try: + token = int(value) + except (TypeError, ValueError) as exc: + raise ValueError("generated token must be an integer") from exc + if not 0 <= token <= 2**31 - 1: + raise ValueError("generated token is outside signed int32 range") + return token class MarkerWriter(Protocol): @@ -70,6 +126,10 @@ def __init__( execution: ExecutionSettings | None = None, assignment: PipelineAssignment | None = None, heartbeat_interval: float = _DEFAULT_HEARTBEAT_INTERVAL, + cancel_path: Path | None = None, + cancel_deployment_id: str = "", + cancel_plan_hash: str = "", + cancel_epoch_floor: int = 0, ) -> None: if publish_interval < 0: raise ValueError("publish_interval must be non-negative") @@ -83,6 +143,7 @@ def __init__( self._heartbeat_interval = float(heartbeat_interval) self._heartbeat_stop = threading.Event() self._heartbeat_thread: threading.Thread | None = None + self._maintenance_callback: Any | None = None self._lock = threading.Lock() self._started_at = float(self._clock()) self._last_step_finished_at = self._started_at @@ -90,6 +151,12 @@ def __init__( self._requests: dict[int, _RequestSample] = {} self._uid_to_request: dict[Any, int] = {} self._request_to_uid: dict[int, Any] = {} + self._request_contexts: dict[int, Any] = {} + self._request_queues: dict[int, Any] = {} + self._transport_to_request: dict[str, int] = {} + self._request_to_transport: dict[int, str] = {} + self._pending_transport_cancels: set[str] = set() + self._cancel_requested_requests: set[int] = set() self._pending_uid = threading.local() self._last_completed: dict[str, Any] | None = None self._last_publish_at = float("-inf") @@ -108,6 +175,29 @@ def __init__( self._cache_tokens_reused = 0 self._cache_entries = 0 self._cache_bytes = 0 + # Rank-side force-cancel surface. The coordinator drops a cancel file + # next to the runtime markers; the heartbeat picks it up and removes + # every active uid through BatchGenerator.remove — MLX-LM's own + # cancel path, which lands at a batch step boundary and is shared + # with peer ranks, so cancellation never severs a collective + # mid-request. + self._batch_generator: Any | None = None + self._cancel_path = cancel_path + self._cancel_deployment_id = cancel_deployment_id + self._cancel_plan_hash = cancel_plan_hash + self._cancel_epoch_floor = max(0, int(cancel_epoch_floor)) + self._last_cancel_epoch = max(0, self._cancel_epoch_floor - 1) + self._accepted_cancel_vote_epoch = 0 + self._last_cancel_poll_at = float("-inf") + # A cancel marker is an edge, not durable desired state. Treat a file + # left by an earlier worker lifetime as the startup watermark instead + # of replaying it against the first request this process receives. + existing_cancel = self._read_cancel_request() + if existing_cancel is not None: + self._last_cancel_epoch = max( + self._last_cancel_epoch, + int(existing_cancel["epoch"]), + ) def heartbeat(self) -> None: """Refresh the marker with nothing new to say. @@ -118,9 +208,20 @@ def heartbeat(self) -> None: """ now = float(self._clock()) + # A coordinator cancel request is picked up here even when no + # request event is driving publishes (e.g. a wedged handler). + self.poll_cancel_requests(min_interval=0.0) + maintenance = self._maintenance_callback + if maintenance is not None: + maintenance() with self._lock: self._publish_locked(now, force=True) + def set_maintenance_callback(self, callback: Any | None) -> None: + """Install the rank-local, heartbeat-driven maintenance poll.""" + + self._maintenance_callback = callback + def start_heartbeat(self) -> None: """Begin refreshing the marker on a fixed interval. Idempotent.""" @@ -152,7 +253,7 @@ def _heartbeat_loop(self) -> None: # and reintroduce the self-kill it exists to prevent. logger.debug("Runtime marker heartbeat failed: %s", exc) - def begin_request(self) -> int: + def begin_request(self, transport_request_id: str | None = None) -> int: now = float(self._clock()) with self._lock: self._next_request_id += 1 @@ -162,6 +263,10 @@ def begin_request(self) -> int: started_at=now, updated_at=now, ) + transport_request_id = _transport_request_id(transport_request_id) + if transport_request_id is not None: + self._transport_to_request[transport_request_id] = request_id + self._request_to_transport[request_id] = transport_request_id self._publish_locked(now, force=True) return request_id @@ -227,17 +332,15 @@ def observe_prefill_progress( and now > previous_at and processed > previous_processed ): - sample.prefill_speed = ( - processed - previous_processed - ) / (now - previous_at) + sample.prefill_speed = (processed - previous_processed) / ( + now - previous_at + ) elif ( processed > 0 and now > sample.prefill_started_at and sample.prefill_speed <= 0 ): - sample.prefill_speed = processed / ( - now - sample.prefill_started_at - ) + sample.prefill_speed = processed / (now - sample.prefill_started_at) prefill_elapsed = now - sample.prefill_started_at if processed > 0 and prefill_elapsed > 0: sample.prefill_average_speed = processed / prefill_elapsed @@ -248,6 +351,104 @@ def observe_prefill_progress( sample.updated_at = now self._publish_locked(now, force=True) + def has_active_prefill(self) -> bool: + """Whether a request still has prompt chunks left on this rank.""" + + with self._lock: + return any( + sample.first_token_at is None + and sample.prefill_total_tokens > 0 + and sample.prefill_processed_tokens < sample.prefill_total_tokens + for sample in self._requests.values() + ) + + def active_request_count(self) -> int: + """Current rank-local requests, for quiescence-gated maintenance.""" + + with self._lock: + return len(self._requests) + + def make_cancel_vote(self, uids: Any) -> dict[str, Any]: + """Create the next rank-zero-owned, monotonically ordered cancel vote.""" + + try: + candidates = tuple(uids) + except TypeError as exc: + raise RuntimeError("distributed cancel vote UIDs are not iterable") from exc + normalized: list[int] = [] + for uid in candidates: + if not isinstance(uid, int) or isinstance(uid, bool) or uid < 0: + raise RuntimeError("distributed cancel vote contains an invalid UID") + if uid not in normalized: + normalized.append(uid) + if not normalized or len(normalized) > _MAX_TARGETED_CANCEL_REQUESTS: + raise RuntimeError("distributed cancel vote has an invalid UID count") + with self._lock: + epoch = max( + self._accepted_cancel_vote_epoch + 1, + self._last_cancel_epoch, + 1, + ) + return { + "kind": _CANCEL_VOTE_KIND, + "schema_version": _CANCEL_VOTE_SCHEMA_VERSION, + "epoch": epoch, + "uids": normalized, + } + + def accept_cancel_vote(self, vote: Any) -> tuple[int, list[int]]: + """Validate one shared cancel epoch before any rank mutates its batch.""" + + if ( + not isinstance(vote, dict) + or vote.get("kind") != _CANCEL_VOTE_KIND + or vote.get("schema_version") != _CANCEL_VOTE_SCHEMA_VERSION + ): + raise RuntimeError("distributed cancel vote envelope is invalid") + epoch = vote.get("epoch") + uids = vote.get("uids") + if not isinstance(epoch, int) or isinstance(epoch, bool) or epoch <= 0: + raise RuntimeError("distributed cancel vote epoch is invalid") + if not isinstance(uids, list): + raise RuntimeError("distributed cancel vote UID list is invalid") + normalized: list[int] = [] + for uid in uids: + if not isinstance(uid, int) or isinstance(uid, bool) or uid < 0: + raise RuntimeError("distributed cancel vote contains an invalid UID") + if uid in normalized: + raise RuntimeError("distributed cancel vote contains duplicate UIDs") + normalized.append(uid) + if not normalized or len(normalized) > _MAX_TARGETED_CANCEL_REQUESTS: + raise RuntimeError("distributed cancel vote has an invalid UID count") + with self._lock: + if epoch <= self._accepted_cancel_vote_epoch: + raise RuntimeError( + "distributed cancel vote epoch did not advance: " + f"previous={self._accepted_cancel_vote_epoch}, received={epoch}" + ) + self._accepted_cancel_vote_epoch = epoch + return epoch, normalized + + def drain_cancel_boundary(self, epoch: int, uids: Any) -> None: + """Drain rank-local Metal work for a validated shared cancellation.""" + + with self._lock: + generator = self._batch_generator + drain = getattr(generator, "_omlx_drain_cancel_boundary", None) + if not callable(drain): + raise RuntimeError("distributed cancel vote has no live batch generator") + drain(epoch, uids) + + def arm_cancel_boundary(self, epoch: int, uids: Any) -> None: + """Allow exactly the agreed UID removal after the rank rendezvous.""" + + with self._lock: + generator = self._batch_generator + arm = getattr(generator, "_omlx_arm_cancel_boundary", None) + if not callable(arm): + raise RuntimeError("distributed cancel vote has no live batch generator") + arm(epoch, uids) + def observe_token(self, request_id: int) -> None: now = float(self._clock()) with self._lock: @@ -274,6 +475,31 @@ def mark_pending_uid(self, request_id: int) -> None: self._pending_uid.request_id = request_id + def register_context(self, request_id: int, context: Any) -> None: + """Retain the server context used by its synchronized cancel path.""" + + cancel_immediately = False + with self._lock: + if request_id in self._requests: + self._request_contexts[request_id] = context + transport_request_id = self._request_to_transport.get(request_id) + if transport_request_id in self._pending_transport_cancels: + self._pending_transport_cancels.discard(transport_request_id) + self._cancel_requested_requests.add(request_id) + cancel_immediately = True + if cancel_immediately: + stop = getattr(context, "stop", None) + if callable(stop): + try: + stop() + except Exception as exc: + logger.warning("Rank-side pending context cancel failed: %s", exc) + + def register_response_queue(self, request_id: int, queue: Any) -> None: + with self._lock: + if request_id in self._requests: + self._request_queues[request_id] = queue + def bind_pending_uid(self, uids: Any) -> None: """Bind MLX-LM's generated batch UID to the observed queue request.""" @@ -303,22 +529,242 @@ def cancel_uids(self, uids: Any) -> None: return now = float(self._clock()) changed = False + queues_to_close: list[Any] = [] with self._lock: for uid in uid_values: request_id = self._uid_to_request.pop(uid, None) if request_id is None: continue + self._cancel_requested_requests.discard(request_id) self._request_to_uid.pop(request_id, None) - changed = ( - self._finish_locked( - request_id, - now=now, - status="cancelled", - ) - or changed + queue = self._request_queues.get(request_id) + finished = self._finish_locked( + request_id, + now=now, + status="cancelled", ) + if finished and queue is not None: + queues_to_close.append(queue) + changed = finished or changed if changed: self._publish_locked(now, force=True) + # Wake the HTTP collector only after releasing the telemetry lock. + # Worker dummy queues receive the same terminal sentinel harmlessly. + for queue in queues_to_close: + try: + queue.put(None) + except Exception as exc: + logger.debug("Could not terminate cancelled response queue: %s", exc) + + def register_batch_generator(self, generator: Any) -> None: + """Remember the live BatchGenerator so force-cancel can reach it.""" + + with self._lock: + self._batch_generator = generator + + def merge_requested_cancel_uids(self, uids: Any) -> list[Any]: + """Inject requested UIDs into MLX-LM's rank-zero cancellation vote. + + This runs on the generation thread immediately before its existing + ``_share_object(uids_to_remove)`` broadcast. It is therefore safe for + distributed collectives: rank zero remains the single producer and + every peer receives/removes the same list at the same batch boundary. + The heartbeat thread never calls ``BatchGenerator.remove`` directly. + """ + + try: + merged = list(uids) + except TypeError: + merged = [] + with self._lock: + requested = [ + self._request_to_uid[request_id] + for request_id in self._cancel_requested_requests + if request_id in self._request_to_uid and request_id in self._requests + ] + for uid in requested: + if uid not in merged: + merged.append(uid) + return merged + + def force_cancel_all(self, *, reason: str = "coordinator cancel") -> int: + """Request cancellation through MLX-LM's shared server-loop path. + + The heartbeat must not call ``BatchGenerator.remove`` directly: that + mutates rank zero on the heartbeat thread while peers keep decoding. + Stop the real generation contexts and let the generation thread merge, + broadcast, drain, rendezvous, and remove the same UIDs on every rank. + """ + + with self._lock: + self._cancel_requested_requests.update(self._requests) + contexts = [ + context + for request_id, context in self._request_contexts.items() + if request_id in self._requests + ] + if not contexts: + return 0 + requested = 0 + for context in contexts: + stop = getattr(context, "stop", None) + if not callable(stop): + continue + try: + stop() + except Exception as exc: + logger.warning("Rank-side context cancel failed: %s", exc) + continue + requested += 1 + if not requested: + return 0 + logger.warning( + "Requested synchronized cancellation for %d active request(s): %s", + requested, + reason, + ) + return requested + + def force_cancel_request( + self, + transport_request_id: str, + *, + reason: str = "coordinator cancel", + ) -> int: + """Stop exactly one request identified by the private HTTP transport.""" + + normalized = _transport_request_id(transport_request_id) + if normalized is None: + return 0 + with self._lock: + request_id = self._transport_to_request.get(normalized) + context = self._request_contexts.get(request_id) + active = request_id in self._requests if request_id is not None else False + if active and request_id is not None: + self._cancel_requested_requests.add(request_id) + if not active or context is None: + with self._lock: + if len(self._pending_transport_cancels) < _MAX_TARGETED_CANCEL_REQUESTS: + self._pending_transport_cancels.add(normalized) + return 0 + stop = getattr(context, "stop", None) + if not callable(stop): + return 0 + try: + stop() + except Exception as exc: + logger.warning("Rank-side targeted context cancel failed: %s", exc) + return 0 + logger.warning( + "Requested synchronized cancellation for request %s: %s", + normalized, + reason, + ) + return 1 + + def _read_cancel_request(self) -> dict[str, Any] | None: + path = self._cancel_path + if path is None: + return None + try: + raw = path.read_text(encoding="utf-8") + except OSError: + return None + if len(raw.encode()) > _MAX_CANCEL_FILE_BYTES: + return None + try: + payload = json.loads(raw) + except json.JSONDecodeError: + return None + if not isinstance(payload, dict) or payload.get("schema_version") != 1: + return None + if ( + self._cancel_deployment_id + and payload.get("deployment_id") != self._cancel_deployment_id + ): + return None + if ( + self._cancel_plan_hash + and payload.get("plan_hash") != self._cancel_plan_hash + ): + return None + epoch = payload.get("epoch") + if not isinstance(epoch, int) or isinstance(epoch, bool): + return None + if epoch < self._cancel_epoch_floor: + return None + return payload + + def _write_cancel_ack(self, *, epoch: int, cancelled: int) -> None: + path = self._cancel_path + if path is None: + return + ack = path.with_name(path.stem + "-ack.json") + payload = { + "schema_version": 1, + "deployment_id": self._cancel_deployment_id, + "plan_hash": self._cancel_plan_hash, + "epoch": epoch, + "cancelled": cancelled, + "at": time.time(), + } + try: + temporary = ack.with_name(ack.name + ".tmp") + descriptor = os.open( + temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600 + ) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(payload, stream, sort_keys=True) + os.replace(temporary, ack) + except OSError: + # The ack is advisory; the marker's active_requests count is the + # authoritative drain evidence. + return + + def poll_cancel_requests(self, *, min_interval: float = 1.0) -> int: + """Consume the coordinator's cancel file, at most one read a second. + + Each epoch is consumed once. The ack file lets the coordinator + confirm the cancel reached the rank without guessing. + """ + + now = float(self._clock()) + if now - self._last_cancel_poll_at < max(0.0, min_interval): + return 0 + self._last_cancel_poll_at = now + payload = self._read_cancel_request() + if payload is None: + return 0 + epoch = payload["epoch"] + if epoch <= self._last_cancel_epoch: + return 0 + self._last_cancel_epoch = epoch + reason = str(payload.get("reason") or "coordinator cancel") + if payload.get("scope") == "request": + cancelled = self.force_cancel_request( + payload.get("request_id"), + reason=reason, + ) + elif payload.get("scope") == "requests": + request_ids = payload.get("request_ids") + if not isinstance(request_ids, list): + cancelled = 0 + else: + normalized = [] + for request_id in request_ids[:_MAX_TARGETED_CANCEL_REQUESTS]: + request_id = _transport_request_id(request_id) + if request_id is not None and request_id not in normalized: + normalized.append(request_id) + cancelled = sum( + self.force_cancel_request(request_id, reason=reason) + for request_id in normalized + ) + elif payload.get("scope") == "all": + cancelled = self.force_cancel_all(reason=reason) + else: + cancelled = 0 + self._write_cancel_ack(epoch=epoch, cancelled=cancelled) + return cancelled def observe_batch_step( self, @@ -329,6 +775,9 @@ def observe_batch_step( ) -> None: """Record one coalesced MLX-LM continuous-batching step.""" + # Throttled to one read a second; gives a coordinator cancel ~1 s + # latency while the batch loop is actively stepping. + self.poll_cancel_requests() now = float(self._clock()) elapsed = max(0.0, float(elapsed_seconds)) with self._lock: @@ -384,9 +833,16 @@ def _finish_locked( sample = self._requests.pop(request_id, None) if sample is None: return False + self._cancel_requested_requests.discard(request_id) if getattr(self._pending_uid, "request_id", None) == request_id: self._pending_uid.request_id = None uid = self._request_to_uid.pop(request_id, None) + self._request_contexts.pop(request_id, None) + self._request_queues.pop(request_id, None) + transport_request_id = self._request_to_transport.pop(request_id, None) + if transport_request_id is not None: + self._transport_to_request.pop(transport_request_id, None) + self._pending_transport_cancels.discard(transport_request_id) if uid is not None: self._uid_to_request.pop(uid, None) sample.updated_at = now @@ -594,10 +1050,16 @@ def _finite_metrics(value: Any) -> bool: class _TelemetryQueue: """Observe MLX-LM's rank-local response queue without changing its API.""" - def __init__(self, queue: Any, telemetry: RuntimeTelemetry) -> None: + def __init__( + self, + queue: Any, + telemetry: RuntimeTelemetry, + transport_request_id: str | None = None, + ) -> None: self._queue = queue self._telemetry = telemetry - self._request_id = telemetry.begin_request() + self._request_id = telemetry.begin_request(transport_request_id) + telemetry.register_response_queue(self._request_id, queue) self._finished = False def put(self, item: Any, *args: Any, **kwargs: Any) -> Any: @@ -617,6 +1079,7 @@ def put(self, item: Any, *args: Any, **kwargs: Any) -> Any: cached_tokens=max(0, int(cache_count)), ) self._telemetry.mark_pending_uid(self._request_id) + self._telemetry.register_context(self._request_id, item) elif hasattr(item, "token") and hasattr(item, "finish_reason"): self._telemetry.observe_token(self._request_id) return self._queue.put(item, *args, **kwargs) @@ -631,8 +1094,10 @@ def install_server_telemetry( prefill_guard: Any | None = None, heartbeat_interval: float = _DEFAULT_HEARTBEAT_INTERVAL, ssd_cache_dir: str | None = None, - ssd_max_entries: int = 64, + ssd_max_entries: int = 512, + ssd_cache_persistent: bool = False, prefill_step_size: int = 2048, + control_plane: Any | None = None, ) -> Iterator[RuntimeTelemetry]: """Patch the pinned worker's generator at its rank-local queue boundary. @@ -646,9 +1111,9 @@ def install_server_telemetry( a chained progress callback) and restore from it on an in-memory miss, so a model whose per-layer state cannot be sliced still reuses a long prefix instead of recomputing it. The restore boundary is agreed across ranks so a - disk write that failed on one rank cannot desync the pipeline. The snapshot - directory is process-lifetime: the store starts it clean and this context's - teardown removes it. + disk write that failed on one rank cannot desync the pipeline. With + ``ssd_cache_persistent`` the compact plan-scoped index survives rank + restarts; otherwise this context retains the legacy process-lifetime tier. """ import mlx.core as mx @@ -658,15 +1123,40 @@ def install_server_telemetry( original_batch_generator = mlx_server.BatchGenerator original_prompt_cache = mlx_server.LRUPromptCache original_generation_context = mlx_server.GenerationContext + original_time_budget = mlx_server.TimeBudget + original_handle_completion = mlx_server.APIHandler.handle_completion + original_do_post = mlx_server.APIHandler.do_POST cancellation_state = threading.local() + marker_path = getattr(marker, "path", None) + marker_payload = getattr(marker, "payload", None) + marker_deployment_id = ( + str(marker_payload.get("deployment_id") or "") + if isinstance(marker_payload, dict) + else "" + ) + marker_plan_hash = ( + str(marker_payload.get("plan_hash") or "") + if isinstance(marker_payload, dict) + else "" + ) + worker_cancel_epoch_floor = int(time.time() * 1000) telemetry = RuntimeTelemetry( marker, execution=execution, assignment=assignment, heartbeat_interval=heartbeat_interval, + cancel_path=( + Path(marker_path).parent / f"{marker_deployment_id}-cancel.json" + if marker_path is not None and marker_deployment_id + else None + ), + cancel_deployment_id=marker_deployment_id, + cancel_plan_hash=marker_plan_hash, + cancel_epoch_floor=worker_cancel_epoch_floor, ) snapshot_ctx = threading.local() + prompt_cache_instances: list[Any] = [] snapshot_step = max(1, int(prefill_step_size)) ssd_store = None if ssd_cache_dir: @@ -677,12 +1167,102 @@ def install_server_telemetry( ) ssd_store = SSDPromptSnapshotStore( - ssd_cache_dir, step=snapshot_step, max_entries=ssd_max_entries + ssd_cache_dir, + step=snapshot_step, + max_entries=ssd_max_entries, + persistent=ssd_cache_persistent, ) try: - world_size = int(mx.distributed.init().size()) + group = mx.distributed.init() + world_size = int(group.size()) + rank = int(group.rank()) except Exception: world_size = 1 + rank = 0 + + def prompt_cache_positions(cache: Any) -> tuple[int, ...]: + """Best-effort logical token positions for a rank-local cache copy.""" + + positions: list[int] = [] + for item in cache or (): + nested = getattr(item, "caches", None) + entries = nested if isinstance(nested, (list, tuple)) else (item,) + for entry in entries: + # DS4 PoolingCache.offset counts compressed rows rather than + # source tokens. Reconstruct the logical source position so + # a failed arbitrary trim cannot masquerade as a valid hit. + ratio = getattr(entry, "ratio", None) + remainder = getattr(entry, "remainder", None) + pooled = getattr(entry, "_pool_len", None) + if all(isinstance(value, int) for value in (ratio, remainder, pooled)): + positions.append(int(pooled) * int(ratio) + int(remainder)) + continue + offset = getattr(entry, "offset", None) + if isinstance(offset, int): + positions.append(offset) + return tuple(positions) + + def agree_prompt_cache_plan( + cache: Any, + tokens: list[int], + rest: list[int], + ) -> tuple[Any, list[int]]: + """Use a cache only when every rank will prefill the same suffix. + + Pipeline stages can have different cache types. In particular, one + DS4 stage may be able to trim a longer cached conversation to a common + prefix while another stage containing a recurrent cache cannot. The + stock rank-local lookup then gives the stages different input lengths; + JACCL reports ``IBV_WC_LOC_LEN_ERR`` when the activation send reaches a + receive posted for the other length. + + Exchange both the reused-prefix and suffix lengths before the first + model call. Any disagreement makes every rank discard its local copy + and perform the same full prefill. The reliable TCP control plane is + preferred because these are owned scalar values, not tensor + reductions; the fixed-shape reduction is retained for older launchers. + """ + + if world_size <= 1: + return cache, rest + + reused = len(tokens) - len(rest) if cache is not None else 0 + suffix = len(rest) if cache is not None else len(tokens) + positions = prompt_cache_positions(cache) + incoherent = int(any(position != reused for position in positions)) + local = (reused, suffix, incoherent) + plans: list[tuple[int, int, int]] = [] + if control_plane is not None: + for source in range(world_size): + payload = struct.pack("!QQQ", *local) if rank == source else None + packet = control_plane.broadcast_owned_bytes( + payload, + source_rank=source, + expected_size=24, + ) + plans.append(struct.unpack("!QQQ", packet)) + else: + fields = [0] * (3 * world_size) + fields[3 * rank : 3 * rank + 3] = local + agreed = mx.distributed.all_sum(mx.array(fields, dtype=mx.int32)) + mx.eval(agreed) + values = [int(value) for value in agreed.tolist()] + plans = [ + tuple(values[3 * source : 3 * source + 3]) + for source in range(world_size) + ] + + if not any(plan[2] for plan in plans) and all( + plan == plans[0] for plan in plans[1:] + ): + return cache, rest + + logger.warning( + "Prompt-cache plan diverged across ranks (%s); rebuilding the " + "request with a full synchronized prefill", + plans, + ) + return None, list(tokens) def agree_ssd_boundary(model: Any, tokens: list[int]) -> int: """Longest prefix boundary every rank can restore for ``tokens``, or 0. @@ -731,6 +1311,25 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: # Full token sequence per in-flight uid, so a boundary snapshot can # be keyed while the batched prefill is still running. self._omlx_tokens: dict[Any, list[int]] = {} + self._omlx_prepared_cancel_vote: tuple[int, tuple[int, ...]] | None = None + telemetry.register_batch_generator(self) + + def _omlx_drain_cancel_boundary(self, epoch: int, uids: Any) -> None: + """Finish scheduled Metal work before the cancel rendezvous.""" + + if self._omlx_prepared_cancel_vote is not None: + raise RuntimeError("a distributed cancel vote is already armed") + stream = getattr(self, "stream", None) + if stream is None: + mx.synchronize() + else: + mx.synchronize(stream) + + def _omlx_arm_cancel_boundary(self, epoch: int, uids: Any) -> None: + normalized = tuple(int(uid) for uid in uids) + if self._omlx_prepared_cancel_vote is not None: + raise RuntimeError("a distributed cancel vote is already armed") + self._omlx_prepared_cancel_vote = (int(epoch), normalized) def insert_segments(self, *args: Any, **kwargs: Any) -> Any: uids = super().insert_segments(*args, **kwargs) @@ -754,10 +1353,23 @@ def insert_segments(self, *args: Any, **kwargs: Any) -> Any: return uids def remove(self, uids: Any) -> Any: - telemetry.cancel_uids(uids) - for uid in uids: + uid_values = list(uids) + if world_size > 1: + prepared = self._omlx_prepared_cancel_vote + if prepared is None or prepared[1] != tuple(uid_values): + raise RuntimeError( + "distributed UID removal was not armed by the shared " + "cancel epoch" + ) + self._omlx_prepared_cancel_vote = None + # Mutate the MLX-LM batch first. Only then publish cancellation and + # wake the HTTP collector; an exception during cache filtering must + # not advertise a request as safely removed when its graph remains. + result = super().remove(uid_values) + for uid in uid_values: self._omlx_tokens.pop(uid, None) - return super().remove(uids) + telemetry.cancel_uids(uid_values) + return result def _omlx_snapshot_boundary(self, response: Any) -> None: """Save the batched prompt cache when prefill crosses a boundary. @@ -794,6 +1406,8 @@ def next(self) -> Any: started = time.perf_counter() prompt_responses, generation_responses = super().next() elapsed = time.perf_counter() - started + for response in generation_responses: + response.token = _python_token_id(response.token) for response in prompt_responses: progress = getattr(response, "progress", None) uid = getattr(response, "uid", None) @@ -818,15 +1432,19 @@ def next(self) -> Any: return prompt_responses, generation_responses class TelemetryPromptCache(original_prompt_cache): + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + prompt_cache_instances.append(self) + + def _omlx_cache_inventory(self) -> tuple[int, int]: + """Combined volatile LRU and durable rank-local snapshot tiers.""" + + disk_entries = len(ssd_store) if ssd_store is not None else 0 + disk_bytes = ssd_store.nbytes if ssd_store is not None else 0 + return len(self) + disk_entries, self.nbytes + disk_bytes + def _fetch_observed(self, model: Any, tokens: list[int]) -> Any: - cache, rest = super().fetch_nearest_cache(model, tokens) - telemetry.observe_cache_lookup( - prompt_tokens=len(tokens), - remaining_tokens=len(rest), - entries=len(self), - nbytes=self.nbytes, - ) - return cache, rest + return super().fetch_nearest_cache(model, tokens) def _lookup(self, model: Any, tokens: list[int]) -> Any: cache, rest = self._fetch_observed(model, tokens) @@ -863,6 +1481,14 @@ def _lookup(self, model: Any, tokens: list[int]) -> Any: loaded = ssd_store.load(model, tokens, boundary) if loaded is not None: cache, rest = loaded, list(tokens[boundary:]) + cache, rest = agree_prompt_cache_plan(cache, tokens, rest) + entries, nbytes = self._omlx_cache_inventory() + telemetry.observe_cache_lookup( + prompt_tokens=len(tokens), + remaining_tokens=len(rest) if cache is not None else len(tokens), + entries=entries, + nbytes=nbytes, + ) return cache, rest def prefetch_nearest_cache(self, model: Any, tokens: list[int]) -> Any: @@ -890,7 +1516,8 @@ def fetch_nearest_cache(self, model: Any, tokens: list[int]) -> Any: def insert_cache(self, *args: Any, **kwargs: Any) -> Any: result = super().insert_cache(*args, **kwargs) - telemetry.observe_cache_state(entries=len(self), nbytes=self.nbytes) + entries, nbytes = self._omlx_cache_inventory() + telemetry.observe_cache_state(entries=entries, nbytes=nbytes) return result class CoordinatedGenerationContext(original_generation_context): @@ -915,13 +1542,82 @@ def _should_stop(self) -> bool: def _should_stop(self, value: Any) -> None: self.__dict__["_omlx_local_should_stop"] = bool(value) + class PrefillCancellationTimeBudget(original_time_budget): + """Expose one synchronized cancel/admission boundary per prompt chunk. + + MLX-LM's distributed TimeBudget normally batches 25 ``next()`` calls + before sharing ``uids_to_remove``. With 2,048-token prompt chunks that + deferred a disconnect by 51,200 tokens. Every rank observes the same + prompt lifecycle, so limiting only active-prefill slices to one step is + symmetric and lets the existing rank-zero cancellation vote run after + at most the in-progress chunk. Decode keeps the amortized 25-step slice. + """ + + def __next__(self) -> Any: + if ( + telemetry.has_active_prefill() + and getattr(self, "_current_iterations", 0) >= 1 + ): + raise StopIteration() + return super().__next__() + class TelemetryResponseGenerator(original): + @staticmethod + def _finish_shared_cancel_vote(shared: Any) -> Any: + if not ( + isinstance(shared, dict) and shared.get("kind") == _CANCEL_VOTE_KIND + ): + return shared + epoch, uids = telemetry.accept_cancel_vote(shared) + telemetry.drain_cancel_boundary(epoch, uids) + if control_plane is not None: + # TCP sendall is not a rendezvous: rank zero can otherwise + # filter its caches while the worker is still draining an + # indexer gather from the just-finished prompt chunk. + control_plane.barrier() + # ``remove`` is fail-closed in TP mode and accepts only this exact + # epoch/list after every peer completed the rendezvous. + telemetry.arm_cancel_boundary(epoch, uids) + return uids + + def _share_object(self, obj: Any) -> Any: + if not bool(getattr(self, "_is_distributed", False)): + return super()._share_object(obj) + # MLX-LM calls this with the rank-zero-owned ``uids_to_remove`` + # list once per batch-loop slice. Merge heartbeat/transport aborts + # here, on the generation thread, so cancellation cannot depend on + # cross-thread mutation of GenerationContext and cannot remove a + # UID on only one rank. + if int(getattr(self, "_rank", 0)) == 0 and isinstance(obj, list): + obj = telemetry.merge_requested_cancel_uids(obj) + if obj: + obj = telemetry.make_cancel_vote(obj) + if control_plane is not None: + shared = control_plane.broadcast_object(obj) + else: + shared = super()._share_object(obj) + return self._finish_shared_cancel_vote(shared) + def _share_request(self, request: Any) -> Any: shared = super()._share_request(request) if shared is None: return None response_queue, *rest = shared - return _TelemetryQueue(response_queue, telemetry), *rest + transport_request_id = ( + _transport_request_id( + getattr(rest[0], "_omlx_transport_request_id", None) + ) + if rest + else None + ) + return ( + _TelemetryQueue( + response_queue, + telemetry, + transport_request_id=transport_request_id, + ), + *rest, + ) def _tokenize(self, tokenizer: Any, request: Any, args: Any) -> Any: tokenized = super()._tokenize(tokenizer, request, args) @@ -965,6 +1661,153 @@ def _serve_single(self, request: Any) -> Any: original_stream_generate = mlx_server.stream_generate + def request_correlated_handle_completion( + handler: Any, + request: Any, + stop_words: Any, + ) -> Any: + """Attach the private coordinator id before ranks share the request.""" + + request_id = _transport_request_id(handler.headers.get("X-oMLX-Request-ID")) + if request_id is not None: + request._omlx_transport_request_id = request_id + return original_handle_completion(handler, request, stop_words) + + def clear_rank_caches(*, clear_ssd: bool, clear_hot: bool) -> dict[str, Any]: + active = telemetry.active_request_count() + if active: + raise RuntimeError(f"requests are active ({active})") + deleted = 0 + cleared = 0 + if clear_ssd and ssd_store is not None: + deleted = ssd_store.clear(timeout=30.0) + if clear_hot: + for cache in tuple(prompt_cache_instances): + before = len(cache) + cache.trim_to(n_sequences=0, n_bytes=0) + cleared += before + memory_entries = sum(len(cache) for cache in prompt_cache_instances) + memory_bytes = sum(cache.nbytes for cache in prompt_cache_instances) + disk_entries = len(ssd_store) if ssd_store is not None else 0 + disk_bytes = ssd_store.nbytes if ssd_store is not None else 0 + telemetry.observe_cache_state( + entries=memory_entries + disk_entries, + nbytes=memory_bytes + disk_bytes, + ) + return { + "status": "ok", + "rank": rank, + "ssd_deleted": deleted, + "hot_cleared": cleared, + } + + def write_maintenance_ack(path: Path, payload: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(path.name + ".tmp") + descriptor = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_TRUNC, + 0o600, + ) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(payload, stream, separators=(",", ":"), sort_keys=True) + os.replace(temporary, path) + + maintenance_epoch_floor = time.time_ns() + maintenance_last_epoch = maintenance_epoch_floor + maintenance_request_path = ( + Path(marker_path).parent / f"{marker_deployment_id}-cache-clear.json" + if marker_path is not None and marker_deployment_id + else None + ) + maintenance_ack_path = ( + Path(marker_path).parent + / f"{marker_deployment_id}-cache-clear-rank-{rank}.json" + if marker_path is not None and marker_deployment_id + else None + ) + + def poll_cache_maintenance() -> None: + nonlocal maintenance_last_epoch + path = maintenance_request_path + ack_path = maintenance_ack_path + if path is None or ack_path is None or not path.is_file(): + return + try: + if path.stat().st_size > _MAX_CANCEL_FILE_BYTES: + return + request = json.loads(path.read_text(encoding="utf-8")) + epoch = int(request.get("epoch", 0)) + except (OSError, TypeError, ValueError, json.JSONDecodeError): + return + if ( + epoch <= maintenance_last_epoch + or epoch < maintenance_epoch_floor + or request.get("deployment_id") != marker_deployment_id + or request.get("plan_hash") != marker_plan_hash + ): + return + maintenance_last_epoch = epoch + try: + result = clear_rank_caches( + clear_ssd=bool(request.get("ssd")), + clear_hot=bool(request.get("hot")), + ) + ack = result | {"epoch": epoch} + except Exception as exc: + ack = { + "status": "error", + "rank": rank, + "epoch": epoch, + "error": f"{type(exc).__name__}: {exc}"[:500], + } + write_maintenance_ack(ack_path, ack) + with suppress(OSError): + path.unlink() + + telemetry.set_maintenance_callback(poll_cache_maintenance) + + def maintenance_do_post(handler: Any) -> Any: + """Private rank-local cache maintenance endpoint. + + The public coordinator invokes this on every rank. It is bound to + loopback by the worker, authenticated with the signed plan hash, and + refuses to race a live request. Keeping the store clear in-process is + essential: deleting only coordinator files leaves peer manifests and + write-behind queues able to resurrect stale snapshots. + """ + + modes = { + "/omlx/internal/cache/ssd/clear": (True, False), + "/omlx/internal/cache/hot/clear": (False, True), + "/omlx/internal/cache/all/clear": (True, True), + } + selected = modes.get(handler.path) + if selected is None: + return original_do_post(handler) + if handler.headers.get("X-oMLX-Plan-Hash") != marker_plan_hash: + handler._set_completion_headers(403) + handler.end_headers() + handler.wfile.write(b'{"error":"invalid maintenance token"}') + return None + clear_ssd, clear_hot = selected + try: + result = clear_rank_caches( + clear_ssd=clear_ssd, + clear_hot=clear_hot, + ) + except (RuntimeError, TimeoutError) as exc: + status = 409 if "requests are active" in str(exc) else 503 + handler._set_completion_headers(status) + handler.end_headers() + handler.wfile.write(json.dumps({"error": str(exc)}).encode()) + return None + body = json.dumps(result, separators=(",", ":")).encode() + handler._set_completion_headers(200) + handler.end_headers() + handler.wfile.write(body) + return None + def snapshotting_stream_generate(*args: Any, **kwargs: Any) -> Any: """Deposit a snapshot at each prefill boundary before it is overwritten. @@ -1008,6 +1851,9 @@ def _snapshot(processed: int, total: int) -> None: mlx_server.ResponseGenerator = TelemetryResponseGenerator mlx_server.LRUPromptCache = TelemetryPromptCache mlx_server.GenerationContext = CoordinatedGenerationContext + mlx_server.TimeBudget = PrefillCancellationTimeBudget + mlx_server.APIHandler.handle_completion = request_correlated_handle_completion + mlx_server.APIHandler.do_POST = maintenance_do_post if ssd_store is not None: mlx_server.stream_generate = snapshotting_stream_generate # Started here rather than by the caller: this block is exactly the span @@ -1022,8 +1868,11 @@ def _snapshot(processed: int, total: int) -> None: mlx_server.BatchGenerator = original_batch_generator mlx_server.LRUPromptCache = original_prompt_cache mlx_server.GenerationContext = original_generation_context + mlx_server.TimeBudget = original_time_budget + mlx_server.APIHandler.handle_completion = original_handle_completion + mlx_server.APIHandler.do_POST = original_do_post mlx_server.stream_generate = original_stream_generate - if ssd_store is not None: - # Snapshots are process-lifetime; a hard crash skips this and the - # next store on the same directory reclaims the leftovers instead. + if ssd_store is not None and not ssd_cache_persistent: + # Legacy process-lifetime mode: a hard crash skips this and the + # next nonpersistent store reclaims the leftovers instead. shutil.rmtree(ssd_store.directory, ignore_errors=True) diff --git a/omlx/engine/base.py b/omlx/engine/base.py index f8564ad022..ba180b2af4 100644 --- a/omlx/engine/base.py +++ b/omlx/engine/base.py @@ -205,6 +205,18 @@ class BaseEngine(ABC): allowing the server to use either without code changes. """ + @property + def supports_early_tool_call_streaming(self) -> bool: + """Whether Chat may parse raw tool envelopes before engine finish. + + Default-false by design. An engine may opt in only when its underlying + producer cannot also return authoritative structured ``tool_calls`` for + the same stream; otherwise the API layer cannot safely emit before the + terminal output arrives. + """ + + return False + @property @abstractmethod def model_name(self) -> str: diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index 4fc7bfbd1a..b3e5af777c 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -110,6 +110,21 @@ def tokenizer(self) -> Any: """Get the tokenizer.""" return self._tokenizer + @property + def supports_early_tool_call_streaming(self) -> bool: + """Opt in only when the local scheduler has no structured parser.""" + + scheduler = getattr( + getattr(getattr(self, "_engine", None), "engine", None), + "scheduler", + None, + ) + return bool( + scheduler is not None + and hasattr(scheduler, "_output_parser_factory") + and scheduler._output_parser_factory is None + ) + @property def model_type(self) -> str | None: """Get the model type from config (e.g., 'gpt_oss', 'llama', 'qwen2').""" @@ -1009,6 +1024,7 @@ async def stream_generate( cached_tokens=output.cached_tokens, generated_at=getattr(output, "generated_at", None), generated_until=getattr(output, "generated_until", None), + first_token_at=getattr(output, "first_token_at", None), benchmark_prefill_chunks=( list(chunks) if (chunks := getattr(output, "benchmark_prefill_chunks", [])) diff --git a/omlx/engine/distributed.py b/omlx/engine/distributed.py index 60818ce568..40d8b4be3c 100644 --- a/omlx/engine/distributed.py +++ b/omlx/engine/distributed.py @@ -8,6 +8,8 @@ import logging import math import os +import shlex +import subprocess import time from collections.abc import AsyncIterator from contextlib import suppress @@ -17,19 +19,41 @@ import httpx from ..cluster.deployment import ClusterDeployment -from ..cluster.launch import DistributedJobSupervisor, DistributedLaunchError -from ..cluster.liveness import check_peers, describe_failure +from ..cluster.launch import ( + DistributedJobSupervisor, + DistributedLaunchError, + _run_cluster_ssh, +) +from ..cluster.liveness import check_peers, describe_failure, read_marker from ..reasoning_effort import _fallback_candidate, _normalized_input from .base import GenerationOutput from .batched import BatchedEngine logger = logging.getLogger(__name__) +_request_clock = time.monotonic # How long one per-rank marker health read stays authoritative. Every request # preflights the cluster, so this bounds both the added latency (one SSH read # per peer, paid once per window) and how long a half-dead cluster can keep # answering 200s before requests start failing cleanly (#2708). _PEER_HEALTH_TTL = 10.0 +_MAX_TARGETED_CANCEL_REQUESTS = 256 +_MAX_TRANSPORT_REQUEST_ID_BYTES = 128 + + +def _valid_transport_request_id(value: Any) -> bool: + if not isinstance(value, str) or not value: + return False + try: + encoded = value.encode("ascii") + except UnicodeEncodeError: + return False + if len(encoded) > _MAX_TRANSPORT_REQUEST_ID_BYTES: + return False + allowed = frozenset( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.:" + ) + return all(character in allowed for character in value) def _reasoning_effort_retry_payloads( @@ -81,13 +105,9 @@ def _variant(effort: Any) -> dict[str, Any]: if candidate is not None and candidate != normalized: variants.append(_variant(candidate)) logger.info( - "rank-zero rejected reasoning_effort=%r; retrying with %s, then " - "without it", + "rank-zero rejected reasoning_effort=%r; retrying with %s, then without it", value, - [ - var["chat_template_kwargs"]["reasoning_effort"] - for var in variants - ], + [var["chat_template_kwargs"]["reasoning_effort"] for var in variants], ) dropped_kwargs = { @@ -108,9 +128,37 @@ class DistributedInferenceError(RuntimeError): """A bounded error surfaced when the private rank-zero backend fails.""" +class DistributedRequestAborted(DistributedInferenceError): # noqa: N818 + """Raised into a proxied request the coordinator has aborted.""" + + +class _DistributedRequestState: + """Coordinator-side tracking for one proxied request. + + The local engine path has per-request abort and an orphan-collector + reaper through AsyncEngineCore; the distributed path had neither (G3/G4). + This record is the handle ``abort_request`` acts on and the evidence the + orphan reaper sweeps: ``finished_at`` stamps the moment the *backend* + finished, so a consumer that abandoned the generator instead of closing + it can be reaped after a grace period — pop-only, mirroring + ``AsyncEngineCore._reap_orphaned_collectors``. + """ + + __slots__ = ("request_id", "started_at", "finished_at", "response", "aborted") + + def __init__(self, request_id: str, started_at: float) -> None: + self.request_id = request_id + self.started_at = started_at + self.finished_at: float | None = None + self.response: Any | None = None + self.aborted = False + + class DistributedBatchedEngine(BatchedEngine): """Keep oMLX's API/tokenizer layer while proxying model work to MLX ranks.""" + supports_request_scoped_abort = True + # The coordinator does not own a local Scheduler: each rank process # creates and enforces its own prefill guard from the signed deployment. # This marker prevents ProcessMemoryEnforcer from reporting that expected @@ -128,6 +176,8 @@ def __init__( cwd: Path | None = None, load_timeout: float = 1800.0, request_read_timeout: float | None = None, + abort_drain_timeout: float = 15.0, + orphan_reap_grace: float = 5.0, ) -> None: if request_read_timeout is None: raw = os.environ.get("OMLX_DISTRIBUTED_REQUEST_READ_TIMEOUT", "300.0") @@ -143,6 +193,8 @@ def __init__( "distributed request read timeout must be a finite positive " f"number, got {request_read_timeout!r}" ) + if abort_drain_timeout < 0 or orphan_reap_grace < 0: + raise ValueError("distributed abort timeouts must be non-negative") super().__init__( model_name=deployment.model, trust_remote_code=deployment.trust_remote_code, @@ -168,6 +220,35 @@ def __init__( self._active_lock = asyncio.Lock() self._peer_health: tuple[float, bool, str] | None = None self._peer_health_lock = asyncio.Lock() + self._abort_drain_timeout = float(abort_drain_timeout) + self._orphan_reap_grace = float(orphan_reap_grace) + self._request_states: dict[str, _DistributedRequestState] = {} + self._next_request_seq = 0 + self._last_cancel_epoch = 0 + self._runtime_failed_reason: str | None = None + + @property + def runtime_failed_reason(self) -> str | None: + """Terminal worker failure observed by the coordinator, if any.""" + + if self._runtime_failed_reason is None and self._loaded: + status = self._supervisor.status() + reason = status.failure_reason + if reason is None and status.returncode is not None: + reason = f"distributed job exited with code {status.returncode}" + if reason: + self._mark_runtime_failed(reason) + return self._runtime_failed_reason + + def _mark_runtime_failed(self, reason: str) -> None: + reason = str(reason).strip()[:2000] or "distributed worker stopped" + if self._runtime_failed_reason is None: + self._runtime_failed_reason = reason + logger.error( + "Distributed runtime is no longer serviceable (%s): %s", + self.deployment.deployment_id, + reason, + ) def _new_client(self, endpoint: str) -> httpx.AsyncClient: return httpx.AsyncClient( @@ -203,10 +284,137 @@ def cluster_status(self) -> dict[str, Any]: return self._supervisor.status().to_dict() + async def clear_prompt_caches( + self, + *, + ssd: bool = False, + hot: bool = False, + ) -> dict[str, Any]: + """Quiescence-gated cache clear executed on every inference rank.""" + + if not ssd and not hot: + return {"status": "ok", "ranks": [], "ssd_deleted": 0, "hot_cleared": 0} + if not self._loaded or self._client is None or self._supervisor.port is None: + raise DistributedInferenceError("distributed engine is not loaded") + async with self._active_lock: + if self._active_requests: + raise DistributedInferenceError( + "distributed cache clear refused while requests are active" + ) + mode = "all" if ssd and hot else "ssd" if ssd else "hot" + path = f"/omlx/internal/cache/{mode}/clear" + headers = {"X-oMLX-Plan-Hash": self.deployment.plan_hash} + maintenance_epoch = time.time_ns() + + async def clear_rank_zero() -> dict[str, Any]: + response = await self._client.post(path, headers=headers) + if response.status_code >= 400: + raise DistributedInferenceError( + "rank 0 cache clear failed: " + f"HTTP {response.status_code} {response.text[:300]}" + ) + payload = response.json() + if not isinstance(payload, dict) or payload.get("status") != "ok": + raise DistributedInferenceError( + "rank 0 returned invalid cache-clear JSON" + ) + return payload + + def clear_remote(rank: int, ssh_target: str) -> dict[str, Any]: + state_root = str(self._supervisor.state_dir).rstrip("/") or "." + request_path = ( + f"{state_root}/{self.deployment.deployment_id}-cache-clear.json" + ) + ack_path = ( + f"{state_root}/{self.deployment.deployment_id}" + f"-cache-clear-rank-{rank}.json" + ) + request_payload = json.dumps( + { + "epoch": maintenance_epoch, + "deployment_id": self.deployment.deployment_id, + "plan_hash": self.deployment.plan_hash, + "ssd": bool(ssd), + "hot": bool(hot), + }, + separators=(",", ":"), + sort_keys=True, + ) + script = r""" +import json, os, sys, time +from pathlib import Path +request_path = Path(sys.argv[1]).expanduser() +ack_path = Path(sys.argv[2]).expanduser() +payload = json.loads(sys.argv[3]) +request_path.parent.mkdir(parents=True, exist_ok=True) +temporary = request_path.with_name(request_path.name + '.tmp') +descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) +with os.fdopen(descriptor, 'w', encoding='utf-8') as stream: + json.dump(payload, stream, separators=(',', ':'), sort_keys=True) +os.replace(temporary, request_path) +deadline = time.monotonic() + 40.0 +while time.monotonic() < deadline: + try: + if ack_path.is_file() and ack_path.stat().st_size <= 65536: + ack = json.loads(ack_path.read_text(encoding='utf-8')) + if int(ack.get('epoch', 0)) == int(payload['epoch']): + print(json.dumps(ack, separators=(',', ':'), sort_keys=True)) + raise SystemExit(0) + except (OSError, ValueError, TypeError, json.JSONDecodeError): + pass + time.sleep(0.1) +print('rank cache-clear acknowledgement timed out', file=sys.stderr) +raise SystemExit(2) +""".strip() + command = shlex.join( + [ + "python3", + "-c", + script, + request_path, + ack_path, + request_payload, + ] + ) + completed = _run_cluster_ssh( + ssh_target, + command, + timeout=45.0, + runner=subprocess.run, + ) + if completed.returncode != 0: + detail = completed.stderr.strip() or completed.stdout.strip() + raise DistributedInferenceError( + f"rank {rank} cache clear failed over SSH: {detail[:300]}" + ) + try: + payload = json.loads(completed.stdout) + except json.JSONDecodeError as exc: + raise DistributedInferenceError( + f"rank {rank} returned invalid cache-clear JSON" + ) from exc + if not isinstance(payload, dict) or payload.get("status") != "ok": + raise DistributedInferenceError( + f"rank {rank} returned an invalid cache-clear result" + ) + return payload + + tasks = [clear_rank_zero()] + for rank, host in enumerate(self.deployment.hosts[1:], start=1): + tasks.append(asyncio.to_thread(clear_remote, rank, host.ssh)) + reports = await asyncio.gather(*tasks) + return { + "status": "ok", + "ranks": reports, + "ssd_deleted": sum(int(item.get("ssd_deleted", 0)) for item in reports), + "hot_cleared": sum(int(item.get("hot_cleared", 0)) for item in reports), + } + async def start(self) -> None: if self._loaded: return self._validate_model_settings() + self._runtime_failed_reason = None # Tokenizer/config metadata stays in the oMLX process. No model weights # are loaded here. @@ -303,9 +511,17 @@ def _ensure_available(self) -> httpx.AsyncClient: if tail and tail not in detail: detail = f"{detail} · Worker log: {tail}" if detail else tail suffix = f": {detail}" if detail else "" + self._mark_runtime_failed( + detail or f"distributed job exited with code {status.returncode}" + ) raise DistributedInferenceError( f"distributed job exited with code {status.returncode}{suffix}" ) + if status.failure_reason: + self._mark_runtime_failed(status.failure_reason) + raise DistributedInferenceError( + f"distributed cluster failure: {status.failure_reason}" + ) return client def _read_timeout_error(self, *, stream: bool) -> DistributedInferenceError: @@ -599,13 +815,269 @@ def _join_reasoning_and_content(reasoning: Any, content: Any) -> str: return f"{reasoning_text}{content_text}" return content_text - async def _enter_request(self) -> None: + async def _enter_request(self, request_id: str | None = None) -> str: async with self._active_lock: self._active_requests += 1 + self._next_request_seq += 1 + if ( + not _valid_transport_request_id(request_id) + or request_id in self._request_states + ): + request_id = f"{self.deployment.deployment_id}-{self._next_request_seq}" + self._request_states[request_id] = _DistributedRequestState( + request_id, + _request_clock(), + ) + return request_id - async def _leave_request(self) -> None: + @staticmethod + def _backend_request_headers(request_id: str) -> dict[str, str]: + return {"X-oMLX-Request-ID": request_id} + + async def _leave_request(self, request_id: str | None = None) -> None: async with self._active_lock: self._active_requests = max(0, self._active_requests - 1) + if request_id is not None: + self._request_states.pop(request_id, None) + + def _request_state(self, request_id: str) -> _DistributedRequestState | None: + return self._request_states.get(request_id) + + def _raise_if_aborted(self, request_id: str) -> None: + state = self._request_states.get(request_id) + if state is not None and state.aborted: + raise DistributedRequestAborted( + f"distributed request {request_id} aborted by the coordinator" + ) + + def _mark_backend_finished(self, request_id: str) -> None: + """Stamp backend completion so the orphan reaper can sweep strays.""" + + state = self._request_states.get(request_id) + if state is not None and state.finished_at is None: + state.finished_at = _request_clock() + + def reap_orphaned_generators( + self, + *, + now: float | None = None, + grace: float | None = None, + ) -> int: + """Drop requests whose backend finished but whose consumer vanished. + + Parallel to ``AsyncEngineCore._reap_orphaned_collectors``: when the + SSE generator chain is abandoned rather than closed, the ``finally`` + that calls ``_leave_request`` only runs at GC time, so + ``_active_requests`` leaks and quiescence-gated unload blocks (G4) — + or worse, unblocks spuriously. Pop-only: any request whose backend + finished more than ``grace`` ago but is still tracked is reaped. A + live consumer drains in the same event-loop turn the backend + finishes, so the grace period cannot race it. + """ + + if not self._request_states: + return 0 + current = _request_clock() if now is None else now + limit = self._orphan_reap_grace if grace is None else grace + stale = [ + request_id + for request_id, state in self._request_states.items() + if state.finished_at is not None and current - state.finished_at >= limit + ] + for request_id in stale: + self._request_states.pop(request_id, None) + self._active_requests = max(0, self._active_requests - 1) + if stale: + logger.warning( + "Reaped %d orphaned distributed request(s) after consumer " + "abandonment: %s", + len(stale), + stale, + ) + return len(stale) + + def rank_side_active_requests(self) -> int | None: + """Active requests as rank zero's telemetry reports them, if known. + + The coordinator's own counter only proves the httpx side closed; + the rank-0 marker's ``metrics.active_requests`` is the rank-side + quiescence evidence an abort or unload should wait for (G5). + """ + + marker = read_marker( + Path(self._supervisor.state_dir).expanduser() + / f"{self.deployment.deployment_id}-rank-0.json" + ) + if not isinstance(marker, dict): + return None + metrics = marker.get("metrics") + if not isinstance(metrics, dict): + return None + active = metrics.get("active_requests") + if isinstance(active, int) and not isinstance(active, bool) and active >= 0: + return active + return None + + async def abort_request( + self, + request_id: str, + *, + reason: str | None = None, + error_code: str | None = None, + ) -> bool: + """Abort one proxied request and close only its backend connection. + + The abort flag ends the local generator at the next yield boundary; + closing the request's own connection makes the rank-0 handler reach + its ``finally`` and cancel the generation context through MLX-LM's + batch-loop removal — a step boundary every rank reaches, never a + mid-collective sever. Other in-flight requests keep their + connections (the old whole-client close in abort_all_requests is + retained there only as the nuclear option). + """ + + state = self._request_states.get(request_id) + if state is None: + return False + state.aborted = True + self._write_rank_cancel_request( + reason=reason or error_code, + request_id=request_id, + ) + response = state.response + if response is not None: + with suppress(Exception): + await response.aclose() + logger.info( + "Aborted distributed request %s (%s)", + request_id, + reason or error_code or "no reason given", + ) + return True + + def _write_rank_cancel_request( + self, + *, + reason: str | None, + request_id: str | None = None, + ) -> Path | None: + """Ask rank zero to cancel request(s) at a shared step boundary. + + The rank's telemetry heartbeat consumes this file and cancels through + ``BatchGenerator.remove`` — MLX-LM's own cancel path, which the batch + loop applies at a step boundary and shares with peer ranks. This is + the backstop for a handler wedged in a collective that never reaches + its disconnect ``finally`` (G3). + """ + + root = Path(self._supervisor.state_dir).expanduser() + path = root / f"{self.deployment.deployment_id}-cancel.json" + if request_id is not None and not _valid_transport_request_id(request_id): + logger.warning("Refusing malformed targeted cancel id") + return None + + pending_request_ids: set[str] = set() + scope = "all" if request_id is None else "requests" + if request_id is not None: + pending_request_ids.add(request_id) + try: + existing = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + existing = None + ack_path = path.with_name(path.stem + "-ack.json") + try: + ack = json.loads(ack_path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + ack = None + ack_epoch = ( + int(ack.get("epoch", -1)) + if isinstance(ack, dict) + and ack.get("deployment_id") == self.deployment.deployment_id + and ack.get("plan_hash") == self.deployment.plan_hash + and isinstance(ack.get("epoch"), int) + and not isinstance(ack.get("epoch"), bool) + else -1 + ) + if ( + isinstance(existing, dict) + and existing.get("deployment_id") == self.deployment.deployment_id + and existing.get("plan_hash") == self.deployment.plan_hash + and isinstance(existing.get("epoch"), int) + and not isinstance(existing.get("epoch"), bool) + # Only merge a marker written by this engine lifetime. A stale + # pre-restart `scope=all` file is a startup watermark, not pending + # work, and must never widen a new targeted disconnect. + and int(existing["epoch"]) == self._last_cancel_epoch + and int(existing["epoch"]) > ack_epoch + ): + if existing.get("scope") == "all": + scope = "all" + elif scope != "all": + candidates = existing.get("request_ids") + if existing.get("scope") == "request": + candidates = [existing.get("request_id")] + if isinstance(candidates, list): + pending_request_ids.update( + candidate + for candidate in candidates + if _valid_transport_request_id(candidate) + ) + + self._last_cancel_epoch = max( + int(time.time() * 1000), + self._last_cancel_epoch + 1, + ) + payload = { + "schema_version": 1, + "deployment_id": self.deployment.deployment_id, + "plan_hash": self.deployment.plan_hash, + "epoch": self._last_cancel_epoch, + "scope": scope, + "reason": reason or "coordinator abort_all_requests", + } + if scope == "requests": + newest = [request_id] if request_id in pending_request_ids else [] + older = sorted(pending_request_ids.difference(newest)) + payload["request_ids"] = (newest + older)[:_MAX_TARGETED_CANCEL_REQUESTS] + try: + root.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(path.name + ".tmp") + descriptor = os.open( + temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600 + ) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(payload, stream, sort_keys=True) + os.replace(temporary, path) + except OSError as exc: + logger.warning("Could not write the rank cancel request: %s", exc) + return None + return path + + async def _wait_for_backend_drain(self, *, timeout: float) -> bool: + """Wait for local generators AND rank-side telemetry to reach zero. + + Client close alone never proved the ranks stopped generating (G5). + Drain is confirmed only when the coordinator counter is zero and the + rank-0 marker reports no active requests. + """ + + deadline = time.monotonic() + max(0.0, timeout) + while True: + self.reap_orphaned_generators() + local_active = self._active_requests + rank_active = self.rank_side_active_requests() + if local_active == 0 and rank_active == 0: + return True + if time.monotonic() >= deadline: + logger.warning( + "Distributed backend drain unconfirmed after %.1fs " + "(local active=%d, rank-zero active=%s)", + timeout, + local_active, + "unknown" if rank_active is None else rank_active, + ) + return False + await asyncio.sleep(0.1) async def chat( self, @@ -640,6 +1112,7 @@ async def chat( if not self._loaded: await self.start() client = self._ensure_available() + requested_id = kwargs.pop("_request_id", None) payload = self._chat_payload( messages=messages, tools=tools, @@ -654,23 +1127,31 @@ async def chat( stream=False, kwargs=kwargs, ) - await self._enter_request() + request_id = await self._enter_request(requested_id) + headers = self._backend_request_headers(request_id) started_at = time.monotonic() try: - response = await client.post("/v1/chat/completions", json=payload) + response = await client.post( + "/v1/chat/completions", json=payload, headers=headers + ) if response.status_code >= 400: detail = self._backend_error_detail(response) for retry_payload in _reasoning_effort_retry_payloads(payload, detail): response = await client.post( - "/v1/chat/completions", json=retry_payload + "/v1/chat/completions", + json=retry_payload, + headers=headers, ) if response.status_code < 400: break self._raise_for_backend(response) + self._raise_if_aborted(request_id) body = response.json() except httpx.ReadTimeout as exc: + self._cancel_backend_after_timeout(request_id) raise self._read_timeout_error(stream=False) from exc except httpx.HTTPError as exc: + self._raise_if_aborted(request_id) raise await self._transport_failure_error( exc, stream=False, @@ -680,7 +1161,8 @@ async def chat( "rank-zero backend returned invalid chat JSON" ) from exc finally: - await self._leave_request() + self._mark_backend_finished(request_id) + await self._leave_request(request_id) try: choice = body["choices"][0] @@ -745,6 +1227,7 @@ async def stream_chat( if not self._loaded: await self.start() client = self._ensure_available() + requested_id = kwargs.pop("_request_id", None) payload = self._chat_payload( messages=messages, tools=tools, @@ -769,7 +1252,8 @@ async def stream_chat( reasoning_open = False backend_tool_calls: dict[int, dict[str, Any]] = {} - await self._enter_request() + request_id = await self._enter_request(requested_id) + headers = self._backend_request_headers(request_id) try: # A client that always sends an unsupported reasoning_effort must # never turn this into an unbounded retry loop: `attempts` is @@ -780,8 +1264,14 @@ async def stream_chat( while True: attempt_payload = attempts[attempt_index] async with client.stream( - "POST", "/v1/chat/completions", json=attempt_payload + "POST", + "/v1/chat/completions", + json=attempt_payload, + headers=headers, ) as response: + state = self._request_state(request_id) + if state is not None: + state.response = response if response.status_code >= 400: await response.aread() if attempt_index == 0: @@ -796,6 +1286,7 @@ async def stream_chat( continue self._raise_for_backend(response) async for line in response.aiter_lines(): + self._raise_if_aborted(request_id) if not line.startswith("data:"): continue data = line.removeprefix("data:").strip() @@ -874,9 +1365,9 @@ async def stream_chat( if isinstance(function.get("name"), str): target["function"]["name"] += function["name"] if isinstance(function.get("arguments"), str): - target["function"]["arguments"] += ( - function["arguments"] - ) + target["function"]["arguments"] += function[ + "arguments" + ] new_text = "" reasoning = delta.get("reasoning") or delta.get( @@ -924,14 +1415,17 @@ async def stream_chat( "rank-zero backend emitted invalid chat token counts" ) from exc except httpx.ReadTimeout as exc: + self._cancel_backend_after_timeout(request_id) raise self._read_timeout_error(stream=True) from exc except httpx.HTTPError as exc: + self._raise_if_aborted(request_id) raise await self._transport_failure_error( exc, stream=True, ) from exc finally: - await self._leave_request() + self._mark_backend_finished(request_id) + await self._leave_request(request_id) pending_final_text = "" if reasoning_open: @@ -979,6 +1473,7 @@ async def generate( if not self._loaded: await self.start() client = self._ensure_available() + requested_id = kwargs.pop("_request_id", None) payload = self._completion_payload( prompt=prompt, max_tokens=max_tokens, @@ -992,23 +1487,31 @@ async def generate( stream=False, kwargs=kwargs, ) - await self._enter_request() + request_id = await self._enter_request(requested_id) + headers = self._backend_request_headers(request_id) started_at = time.monotonic() try: - response = await client.post("/v1/completions", json=payload) + response = await client.post( + "/v1/completions", json=payload, headers=headers + ) if response.status_code >= 400: detail = self._backend_error_detail(response) for retry_payload in _reasoning_effort_retry_payloads(payload, detail): response = await client.post( - "/v1/completions", json=retry_payload + "/v1/completions", + json=retry_payload, + headers=headers, ) if response.status_code < 400: break self._raise_for_backend(response) + self._raise_if_aborted(request_id) body = response.json() except httpx.ReadTimeout as exc: + self._cancel_backend_after_timeout(request_id) raise self._read_timeout_error(stream=False) from exc except httpx.HTTPError as exc: + self._raise_if_aborted(request_id) raise await self._transport_failure_error( exc, stream=False, @@ -1018,7 +1521,8 @@ async def generate( "rank-zero backend returned invalid completion JSON" ) from exc finally: - await self._leave_request() + self._mark_backend_finished(request_id) + await self._leave_request(request_id) try: choice = body["choices"][0] @@ -1056,6 +1560,7 @@ async def stream_generate( if not self._loaded: await self.start() client = self._ensure_available() + requested_id = kwargs.pop("_request_id", None) payload = self._completion_payload( prompt=prompt, max_tokens=max_tokens, @@ -1078,7 +1583,8 @@ async def stream_generate( first_token_at: float | None = None request_started_at = time.monotonic() - await self._enter_request() + request_id = await self._enter_request(requested_id) + headers = self._backend_request_headers(request_id) try: # See stream_chat for the retry-bound rationale. attempts = [payload] @@ -1086,8 +1592,14 @@ async def stream_generate( while True: attempt_payload = attempts[attempt_index] async with client.stream( - "POST", "/v1/completions", json=attempt_payload + "POST", + "/v1/completions", + json=attempt_payload, + headers=headers, ) as response: + state = self._request_state(request_id) + if state is not None: + state.response = response if response.status_code >= 400: await response.aread() if attempt_index == 0: @@ -1102,6 +1614,7 @@ async def stream_generate( continue self._raise_for_backend(response) async for line in response.aiter_lines(): + self._raise_if_aborted(request_id) if not line.startswith("data:"): continue data = line.removeprefix("data:").strip() @@ -1181,14 +1694,17 @@ async def stream_generate( "rank-zero backend emitted invalid token counts" ) from exc except httpx.ReadTimeout as exc: + self._cancel_backend_after_timeout(request_id) raise self._read_timeout_error(stream=True) from exc except httpx.HTTPError as exc: + self._raise_if_aborted(request_id) raise await self._transport_failure_error( exc, stream=True, ) from exc finally: - await self._leave_request() + self._mark_backend_finished(request_id) + await self._leave_request(request_id) finished_at = time.monotonic() await self._record_strategy_benchmark( @@ -1311,9 +1827,7 @@ async def _require_healthy_cluster(self) -> None: if cached is None or time.monotonic() - cached[0] >= _PEER_HEALTH_TTL: async with self._peer_health_lock: cached = self._peer_health - if cached is None or ( - time.monotonic() - cached[0] >= _PEER_HEALTH_TTL - ): + if cached is None or (time.monotonic() - cached[0] >= _PEER_HEALTH_TTL): hosts_by_rank = { rank: (host.node_id, host.ssh) for rank, host in enumerate(self.deployment.hosts) @@ -1340,9 +1854,7 @@ async def _require_healthy_cluster(self) -> None: ) self._peer_health = cached if not cached[1]: - raise DistributedInferenceError( - f"cluster is not serving: {cached[2]}" - ) + raise DistributedInferenceError(f"cluster is not serving: {cached[2]}") async def preflight_chat(self, *args: Any, **kwargs: Any) -> None: self._validate_request_features(kwargs) @@ -1355,8 +1867,29 @@ async def preflight_completion(self, *args: Any, **kwargs: Any) -> None: return None def has_active_requests(self) -> bool: + # Sweep finished-but-abandoned requests first so a leaked generator + # cannot hold quiescence-gated unload open forever (G4). + self.reap_orphaned_generators() return self._active_requests > 0 + def _cancel_backend_after_timeout(self, request_id: str) -> None: + """Follow a read timeout with a rank-side cancel (G5). + + httpx closing its side never proved the rank stopped generating; a + stalled rank keeps the request alive (KV growth, prompt-cache churn) + with nobody reading. A 300 s inactivity bound means the rank is + stalled, not merely slow — keepalive frames rule that out — so the + coordinator-level cancel file is the proportionate follow-up. + """ + + state = self._request_states.get(request_id) + if state is not None: + state.aborted = True + self._write_rank_cancel_request( + reason=f"read timeout on {request_id}; possible rank stall", + request_id=request_id, + ) + def get_stats(self) -> dict[str, Any]: return { "engine_type": "distributed_batched", @@ -1376,13 +1909,30 @@ async def abort_all_requests( reason: str | None = None, error_code: str | None = None, ) -> int: - # Closing the private client disconnects all rank-zero handlers. The - # MLX-LM handler cancels their generation contexts in ``finally``. + """Abort everything in flight and confirm the backend drained. + + Three layers, in order: (1) flag every tracked request so its local + generator stops at the next yield boundary; (2) drop the rank-side + cancel file so rank 0 force-cancels through ``BatchGenerator.remove`` + at a batch step boundary even if a handler is wedged in a collective + and never reaches its disconnect ``finally``; (3) close the shared + client, disconnecting every rank-zero handler. Then wait — bounded — + for both the coordinator counter and rank-side telemetry to report + zero active requests instead of trusting the client close (G5). + """ + + self.reap_orphaned_generators() active = self._active_requests + for state in self._request_states.values(): + state.aborted = True + self._write_rank_cancel_request(reason=reason or error_code) client, self._client = self._client, None if client is not None: await client.aclose() endpoint = self._supervisor.endpoint if endpoint is not None and self._loaded: self._client = self._new_client(endpoint) + rank_active = self.rank_side_active_requests() + if active or (rank_active or 0) > 0: + await self._wait_for_backend_drain(timeout=self._abort_drain_timeout) return active diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index bfda9f6288..5f408fb255 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -1499,6 +1499,21 @@ def model_name(self) -> str: def tokenizer(self) -> Any: return self._tokenizer + @property + def supports_early_tool_call_streaming(self) -> bool: + """Opt in only when the local scheduler has no structured parser.""" + + scheduler = getattr( + getattr(getattr(self, "_engine", None), "engine", None), + "scheduler", + None, + ) + return bool( + scheduler is not None + and hasattr(scheduler, "_output_parser_factory") + and scheduler._output_parser_factory is None + ) + @property def model_type(self) -> str | None: vlm_model = getattr(self, "_vlm_model", None) @@ -3705,6 +3720,7 @@ async def stream_generate( cached_tokens=output.cached_tokens, generated_at=getattr(output, "generated_at", None), generated_until=getattr(output, "generated_until", None), + first_token_at=getattr(output, "first_token_at", None), benchmark_prefill_chunks=( list(chunks) if (chunks := getattr(output, "benchmark_prefill_chunks", [])) diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index 9f46a0935c..5a5fe04a56 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -881,7 +881,7 @@ def _entry_is_diffusion_model(entry: EngineEntry) -> bool: return model_type == "diffusion_gemma" def apply_settings_overrides( - self, settings_manager: "ModelSettingsManager" + self, settings_manager: ModelSettingsManager ) -> None: """Apply model_type_override from persisted settings to discovered entries.""" for model_id, entry in self._entries.items(): @@ -1223,9 +1223,22 @@ def _entry_has_active_requests(entry: EngineEntry) -> bool: if not callable(has_active_requests): return False try: - return has_active_requests() is True + if has_active_requests() is True: + return True except Exception: return True + # Do not use instance getattr here: test doubles and dynamic proxies + # can manufacture a truthy method for any name. Only engines whose + # class explicitly implements rank-side telemetry participate. + rank_side = getattr(type(engine), "rank_side_active_requests", None) + if callable(rank_side): + try: + remaining = rank_side(engine) + except Exception: + remaining = None + if remaining: + return True + return False def _entry_is_busy(self, entry: EngineEntry) -> bool: return entry.in_use > 0 or self._entry_has_active_requests(entry) @@ -2333,10 +2346,13 @@ async def _unload_engine(self, model_id: str) -> None: await entry.engine.stop() except Exception as e: if distributed: - # Keep the supervisor reachable and the planned memory - # accounted so a later unload can retry process teardown. + # The supervisor raises (DistributedTeardownError) when the + # final SIGKILL cannot be verified, so this path is now + # reachable: keep the supervisor reachable and the planned + # memory accounted so a later unload can retry process + # teardown instead of releasing the budget over a live rank. logger.error( - f"Distributed teardown failed for {model_id}; " + f"Distributed teardown failed for {model_id} ({e}); " "keeping the engine registered for retry", exc_info=True, ) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index d22b6af312..a4ab7a5762 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -2298,6 +2298,14 @@ def _phase_timer(self, phase: str): Tracks total ms and invocation count per named phase. Intended for boundary capture / store_cache / hot cache eviction hot paths. """ + # Focused cache-contract tests and third-party embedders sometimes + # construct Scheduler via __new__ to avoid loading a model. Keep + # diagnostics backward-compatible with those constructor-bypassing + # callers; production instances initialize both maps in __init__. + if not hasattr(self, "_phase_total_ms"): + self._phase_total_ms = defaultdict(float) + if not hasattr(self, "_phase_count"): + self._phase_count = defaultdict(int) t0 = time.perf_counter() try: yield @@ -8496,13 +8504,18 @@ def _prepare_prefix_cache_for_request(self, request: Request) -> None: and not self._model_has_unreconstructible_cache() ): # Use paged cache - block_table, remaining = self.block_aware_cache.fetch_cache( - request.request_id, - request.prompt_token_ids, - extra_keys=request.vlm_extra_keys_for_cache, - extra_key_token_start=request.vlm_extra_key_token_start_for_cache, - extra_key_ranges=request.vlm_extra_key_ranges_for_cache, - ) + fetch_started = time.perf_counter() + with self._phase_timer("prefix_cache_lookup"): + block_table, remaining = self.block_aware_cache.fetch_cache( + request.request_id, + request.prompt_token_ids, + extra_keys=request.vlm_extra_keys_for_cache, + extra_key_token_start=( + request.vlm_extra_key_token_start_for_cache + ), + extra_key_ranges=request.vlm_extra_key_ranges_for_cache, + ) + fetch_ms = (time.perf_counter() - fetch_started) * 1000.0 # A split GDN sidecar represents state at a full block boundary. # Exact-hit generation needs N-1 state, which Arrays/GDN cannot # produce by trimming one token. Re-prefill only the final block. @@ -8530,24 +8543,33 @@ def _prepare_prefix_cache_for_request(self, request: Request) -> None: bypass_hot_cache = self._bypass_hot_cache_under_pressure() if bypass_hot_cache: logger.info( - "Skipping hot-cache preload for %s under memory pressure", + "Skipping hot-cache promotion for %s under memory pressure", request.request_id, ) - else: - self.block_aware_cache.preload_blocks(block_table) + # ``preload_blocks`` used to load blocks in parallel. It is + # now intentionally serialized on the inference thread for + # Metal safety, so calling it immediately before + # reconstruct_cache loads and deserializes the same chain + # twice. Direct reconstruction already promotes each SSD + # block as it is consumed. # Reconstruct actual KVCache objects from stored tensor data # Note: reconstruct_cache may modify block_table in-place if # partial reconstruction occurs (some blocks invalid) original_tokens = block_table.num_tokens - if bypass_hot_cache: - reconstructed = self.block_aware_cache.reconstruct_cache( - block_table, - promote_to_hot_cache=False, - ) - else: - reconstructed = self.block_aware_cache.reconstruct_cache( - block_table - ) + reconstruct_started = time.perf_counter() + with self._phase_timer("prefix_cache_reconstruct"): + if bypass_hot_cache: + reconstructed = self.block_aware_cache.reconstruct_cache( + block_table, + promote_to_hot_cache=False, + ) + else: + reconstructed = self.block_aware_cache.reconstruct_cache( + block_table + ) + reconstruct_ms = ( + time.perf_counter() - reconstruct_started + ) * 1000.0 if reconstructed: request.prompt_cache = reconstructed request.block_table = block_table @@ -8629,6 +8651,18 @@ def _prepare_prefix_cache_for_request(self, request: Request) -> None: f"{request.cached_tokens} tokens in {request.shared_prefix_blocks} blocks, " f"{len(request.remaining_tokens)} tokens remaining, cache reconstructed" ) + logger.info( + "Prefix cache restore for %s: source=paged cached=%d " + "suffix=%d blocks=%d lookup=%.3fms reconstruct=%.3fms " + "promote=%s", + request.request_id, + request.cached_tokens, + len(request.remaining_tokens), + request.shared_prefix_blocks, + fetch_ms, + reconstruct_ms, + not bypass_hot_cache, + ) else: # Reconstruction failed, treat as cache miss if self.paged_cache_manager is not None: diff --git a/omlx/server.py b/omlx/server.py index f994498c6c..79e0db13a9 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -46,7 +46,7 @@ import os import time import uuid -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Awaitable, Callable from contextlib import asynccontextmanager, suppress from dataclasses import dataclass, field from enum import Enum @@ -156,11 +156,13 @@ ) from .api.thinking import ThinkingParser, extract_thinking, prompt_opens_thinking from .api.tool_calling import ( + ToolCallStreamSegment, ToolCallStreamFilter, build_json_system_prompt, convert_tools_for_template, enrich_tool_params_for_gemma4, extract_tool_calls_with_thinking, + parse_tool_calls, parse_json_output, restore_gemma4_param_names, sanitize_tool_call_markup, @@ -422,6 +424,24 @@ async def lifespan(app: FastAPI): _reset_boundary_snapshots_for_server() + # Reap distributed ranks orphaned by a crashed previous coordinator + # (G8): all teardown used to live in-process, so a SIGKILL/panic of + # omlx-server stranded loaded ranks with no owner. The launch manifest + # written at spawn lets this new coordinator finish the teardown. + # Best effort: a reaping failure must never block server startup. + try: + from .cluster.launch import reap_orphaned_launches + + orphan_report = await asyncio.to_thread(reap_orphaned_launches) + if orphan_report["reaped"] or orphan_report["failures"]: + logger.warning( + "Reaped orphaned distributed launches from a previous " + "coordinator: %s", + orphan_report, + ) + except Exception as exc: # pragma: no cover - defensive + logger.warning("Orphaned-launch reaper failed at startup: %s", exc) + # Publish the interpreter another Mac's coordinator discovers over SSH. # Without it a packaged-app peer fails every discovery candidate and gets # reported as "worker runtime is not installed" (#2680). Best effort: a @@ -1151,6 +1171,93 @@ async def cached_receive(): await self.app(scope, cached_receive, send) +_DISCONNECT_SIGNAL_SCOPE_KEY = "omlx.client_disconnect_signal" +_disconnect_callback_tasks: set[asyncio.Task] = set() + + +class _ClientDisconnectSignal: + """Fan one ASGI disconnect message out to request-owned cleanup hooks. + + Starlette's ``StreamingResponse`` and ``Request.is_disconnected()`` both + consume the same one-shot ``http.disconnect`` receive message. Whichever + one wins used to hide it from the other. In particular, a real Uvicorn + socket could close while a long distributed prefill kept running because + the response generator never reached its nested ``aclose()`` chain. + + The outer ASGI middleware records the message before either consumer sees + it, then schedules request-scoped callbacks outside Starlette's response + cancellation scope. A callback is keyed by the inference request id, so + cancelling one client can never fall back to aborting every active request. + """ + + def __init__(self) -> None: + self._disconnected = False + self._next_token = 0 + self._callbacks: dict[int, Callable[[], Awaitable[None]]] = {} + + def register(self, callback: Callable[[], Awaitable[None]]) -> int: + self._next_token += 1 + token = self._next_token + if self._disconnected: + self._spawn(callback) + else: + self._callbacks[token] = callback + return token + + def unregister(self, token: int) -> None: + self._callbacks.pop(token, None) + + def disconnect(self) -> None: + if self._disconnected: + return + self._disconnected = True + callbacks = tuple(self._callbacks.values()) + self._callbacks.clear() + for callback in callbacks: + self._spawn(callback) + + @staticmethod + def _spawn(callback: Callable[[], Awaitable[None]]) -> None: + async def run_callback() -> None: + try: + await callback() + except Exception: + logger.exception("Request-scoped disconnect callback failed") + + task = asyncio.create_task(run_callback()) + # asyncio only holds weak task references. Retain the detached abort + # until it completes; Starlette may already be cancelling the response + # task that observed the disconnect. + _disconnect_callback_tasks.add(task) + task.add_done_callback(_disconnect_callback_tasks.discard) + + +class ClientDisconnectTrackingMiddleware: + """Record ``http.disconnect`` before competing ASGI consumers receive it.""" + + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + signal = _ClientDisconnectSignal() + scope[_DISCONNECT_SIGNAL_SCOPE_KEY] = signal + + async def tracked_receive(): + message = await receive() + if message.get("type") == "http.disconnect": + signal.disconnect() + return message + + await self.app(scope, tracked_receive, send) + + +# Keep this outside response middleware so every consumer of ASGI ``receive`` +# passes through the same one-shot disconnect fan-out. +app.add_middleware(ClientDisconnectTrackingMiddleware) app.add_middleware(DebugRequestLoggingMiddleware) @@ -2316,6 +2423,56 @@ async def _safe_anext(ait): return _KEEPALIVE_SENTINEL +async def _aclose_async_iterator(iterator: object) -> None: + """Close an async generator when the response transport ends.""" + + close = getattr(iterator, "aclose", None) + if callable(close): + await close() + + +def _request_abort_id(engine: BaseEngine) -> str | None: + """Mint an opaque id only for engines with targeted abort semantics.""" + + if not getattr(engine, "supports_request_scoped_abort", False): + return None + abort = getattr(engine, "abort_request", None) + if not callable(abort): + return None + return f"transport-{uuid.uuid4().hex}" + + +async def _with_request_disconnect_abort( + generator: AsyncIterator[str], + http_request: FastAPIRequest, + engine: BaseEngine, + request_id: str | None, +) -> AsyncIterator[str]: + """Bind one public response transport to one inference request.""" + + signal = http_request.scope.get(_DISCONNECT_SIGNAL_SCOPE_KEY) + token: int | None = None + if request_id is not None and isinstance(signal, _ClientDisconnectSignal): + abort = getattr(engine, "abort_request") + + async def abort_disconnected_request() -> None: + await abort( + request_id, + reason="public client transport disconnected", + error_code="client_disconnected", + ) + + token = signal.register(abort_disconnected_request) + + try: + async for chunk in generator: + yield chunk + finally: + if token is not None: + signal.unregister(token) + await _aclose_async_iterator(generator) + + async def _with_sse_keepalive( generator: AsyncIterator[str], http_request: Optional["FastAPIRequest"] = None, @@ -3491,6 +3648,7 @@ async def create_completion( for prompt in prompts: await engine.preflight_completion(prompt, request_id=upstream_request_id) await _raise_if_llm_lease_abort_requested(lease) + inference_request_id = _request_abort_id(engine) if request.stream: response_id = f"cmpl-{uuid.uuid4().hex[:8]}" @@ -3499,18 +3657,24 @@ async def create_completion( keepalive = _completion_keepalive_chunk(response_id) return StreamingResponse( _release_after_stream( - _with_sse_keepalive( - stream_completion( - engine, - prompts[0], - request, - model_load_duration=model_load_duration, - prompt_token_ids=prompt_token_ids_by_prompt[0], - resolved_model=resolved_model, - response_id=response_id, + _with_request_disconnect_abort( + _with_sse_keepalive( + stream_completion( + engine, + prompts[0], + request, + model_load_duration=model_load_duration, + prompt_token_ids=prompt_token_ids_by_prompt[0], + resolved_model=resolved_model, + response_id=response_id, + inference_request_id=inference_request_id, + ), + http_request=http_request, + keepalive_chunk=keepalive, ), - http_request=http_request, - keepalive_chunk=keepalive, + http_request, + engine, + inference_request_id, ), lease, ), @@ -3556,6 +3720,8 @@ async def _build_completion(): thinking_budget = _resolve_thinking_budget(request, request.model) if thinking_budget is not None: gen_kwargs["thinking_budget"] = thinking_budget + if inference_request_id is not None: + gen_kwargs["_request_id"] = inference_request_id # Widen the repetition-penalty look-back window when the client # asks for it (mlx-lm default window is 20 tokens). repetition_context_size = getattr( @@ -4026,6 +4192,9 @@ async def create_chat_completion( ) await _raise_if_llm_lease_abort_requested(lease) + inference_request_id = _request_abort_id(engine) + if inference_request_id is not None: + chat_kwargs["_request_id"] = inference_request_id if request.stream: # Pre-mint the completion id so the keepalive frame (emitted before the @@ -4039,18 +4208,23 @@ async def create_chat_completion( sse_headers["Warning"] = response_format_warning return StreamingResponse( _release_after_stream( - _with_sse_keepalive( - stream_chat_completion( - engine, - messages, - request, - model_load_duration=model_load_duration, - resolved_model=resolved_model, - response_id=response_id, - **chat_kwargs, + _with_request_disconnect_abort( + _with_sse_keepalive( + stream_chat_completion( + engine, + messages, + request, + model_load_duration=model_load_duration, + resolved_model=resolved_model, + response_id=response_id, + **chat_kwargs, + ), + http_request=http_request, + keepalive_chunk=keepalive, ), - http_request=http_request, - keepalive_chunk=keepalive, + http_request, + engine, + inference_request_id, ), lease, ), @@ -4605,6 +4779,7 @@ async def stream_completion( prompt_token_ids: list[int] | None = None, resolved_model: str | None = None, response_id: str | None = None, + inference_request_id: str | None = None, ) -> AsyncIterator[str]: """Stream completion response.""" response_id = response_id or f"cmpl-{uuid.uuid4().hex[:8]}" @@ -4646,6 +4821,8 @@ async def stream_completion( thinking_budget = _resolve_thinking_budget(request, request.model) if thinking_budget is not None: gen_kwargs["thinking_budget"] = thinking_budget + if inference_request_id is not None: + gen_kwargs["_request_id"] = inference_request_id # Widen the repetition-penalty look-back window when the client # asks for it (mlx-lm default window is 20 tokens). repetition_context_size = getattr( @@ -4853,6 +5030,96 @@ def _render_chat_prompt_for_thinking_detection( return str(prompt), None +def _registered_tool_names(tools: object) -> set[str]: + """Return nonempty function names explicitly registered by the request.""" + + names: set[str] = set() + for tool in tools or []: + function = ( + tool.get("function") + if isinstance(tool, dict) + else getattr(tool, "function", None) + ) + name = ( + function.get("name") + if isinstance(function, dict) + else getattr(function, "name", None) + ) + if isinstance(name, str) and name: + names.add(name) + return names + + +def _tool_call_semantic_key(tool_call: object) -> tuple[str, str] | None: + """Canonical name/JSON-object identity, or ``None`` when malformed. + + This is syntactic validation plus the separate registered-name check at the + call site; it is deliberately not full JSON Schema argument validation. + """ + + function = getattr(tool_call, "function", None) + name = getattr(function, "name", None) + arguments = getattr(function, "arguments", None) + if not isinstance(name, str) or not name or not isinstance(arguments, str): + return None + try: + parsed = json.loads(arguments) + except (TypeError, ValueError): + return None + if not isinstance(parsed, dict): + return None + canonical = json.dumps( + parsed, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ) + return name, canonical + + +def _chat_can_stream_qwen_tool_envelopes(engine: BaseEngine) -> bool: + """Narrow Chat-only early-tool gate. + + The engine capability is authoritative and defaults false. The tokenizer + must independently expose mlx-lm's qwen3_coder parser; all other APIs and + parser families remain terminal-buffered. + """ + + if getattr(engine, "supports_early_tool_call_streaming", False) is not True: + return False + tokenizer = getattr(engine, "tokenizer", None) + parser = getattr(tokenizer, "tool_parser", None) + try: + from mlx_lm.tool_parsers.qwen3_coder import ( + parse_tool_call as expected_parser, + ) + except ImportError: + return False + return bool( + parser is expected_parser + and getattr(parser, "__name__", None) == "parse_tool_call" + and getattr(parser, "__module__", None) + == "mlx_lm.tool_parsers.qwen3_coder" + ) + + +def _merge_streamed_tool_call_prefix(streamed: list, terminal: list | None) -> list: + """Keep validated early calls as an occurrence-aware semantic prefix.""" + + remaining = list(terminal or []) + merged = list(streamed) + for early in streamed: + key = _tool_call_semantic_key(early) + if key is None: + continue + for index, candidate in enumerate(remaining): + if _tool_call_semantic_key(candidate) == key: + remaining.pop(index) + break + merged.extend(remaining) + return merged + + async def stream_chat_completion( engine: BaseEngine, messages: list, @@ -4870,6 +5137,7 @@ async def stream_chat_completion( """ start_time = time.perf_counter() first_token_time = None + first_visible_time = None last_output = None accumulated_text = "" has_tools = bool(kwargs.get("tools")) @@ -4887,6 +5155,11 @@ async def stream_chat_completion( logger.debug("Could not detect chat stream thinking state: %s", exc) thinking_parser = ThinkingParser(start_in_thinking=start_in_thinking) + def mark_visible_delta() -> None: + nonlocal first_visible_time + if first_visible_time is None: + first_visible_time = time.perf_counter() + # Reuse the id pre-minted by the caller (so the keepalive frame can share # it); otherwise mint one for direct/non-streaming callers. response_id = response_id or f"chatcmpl-{uuid.uuid4().hex[:8]}" @@ -4908,9 +5181,22 @@ async def stream_chat_completion( # clients do not see raw envelopes/tags in assistant content deltas. tool_filter = None thinking_filter = None + streamed_tool_calls = [] + stream_tool_sequence_safe = True + stream_completed_qwen_tools = False + qwen_tool_envelope_streaming_capable = False + registered_tool_names: set[str] = set() stream_content = True if has_tools: - _content_filter = ToolCallStreamFilter(engine.tokenizer) + registered_tool_names = _registered_tool_names(kwargs.get("tools")) + qwen_tool_envelope_streaming_capable = bool( + registered_tool_names and _chat_can_stream_qwen_tool_envelopes(engine) + ) + stream_completed_qwen_tools = qwen_tool_envelope_streaming_capable + _content_filter = ToolCallStreamFilter( + engine.tokenizer, + capture_ordered_segments=stream_completed_qwen_tools, + ) # The thinking channel never contains a separator-prefixed DSML # block; holding trailing newlines would flush them as a late # reasoning delta after the channel closed. @@ -4922,11 +5208,26 @@ async def stream_chat_completion( thinking_filter = _thinking_filter else: stream_content = False + engine_stream = engine.stream_chat(messages=messages, **kwargs) try: - async for output in engine.stream_chat(messages=messages, **kwargs): - if first_token_time is None and output.new_text: - first_token_time = time.perf_counter() + async for output in engine_stream: + if first_token_time is None: + produced_at = getattr(output, "first_token_at", None) + if produced_at is None: + produced_at = getattr(output, "generated_at", None) + if produced_at is not None: + first_token_time = float(produced_at) + elif getattr(output, "completion_tokens", 0) > 0 or output.new_text: + # Engines without producer timestamps can only expose the + # exact API-observation time. Never substitute end-of-turn. + first_token_time = time.perf_counter() last_output = output + if output.tool_calls: + # A structured producer is authoritative. Correct engines keep + # the explicit capability false; this guard also prevents a + # same-output raw envelope from racing its structured result. + stream_completed_qwen_tools = False + stream_tool_sequence_safe = False if output.new_text: accumulated_text += output.new_text @@ -4937,6 +5238,10 @@ async def stream_chat_completion( if thinking_delta: if thinking_filter: thinking_delta = thinking_filter.feed(thinking_delta) + # Thinking-channel calls are terminal fallback only: + # content-channel calls take precedence, so they cannot + # be streamed safely before the turn finishes. + thinking_filter.take_completed_envelopes() chunk = ChatCompletionChunk( id=response_id, model=request.model, @@ -4950,27 +5255,125 @@ async def stream_chat_completion( ], ) if thinking_delta: - yield f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + event = ( + f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + ) + mark_visible_delta() + yield event # Emit content delta — filter out tool-call markup when # tools are present so clients see clean streamed text. if content_delta: + ordered_segments: list[ToolCallStreamSegment] = [] if tool_filter: content_delta = tool_filter.feed(content_delta) - if content_delta: - chunk = ChatCompletionChunk( - id=response_id, - model=request.model, - choices=[ - ChatCompletionChunkChoice( - delta=ChatCompletionChunkDelta( - content=content_delta - ), - finish_reason=None, + if stream_completed_qwen_tools: + ordered_segments = tool_filter.take_ordered_segments() + # The legacy completed queue shares the same string + # objects; drain it so ordered capture adds no + # retained duplicate state. + tool_filter.take_completed_envelopes() + if tool_filter.completed_envelope_overflowed: + logger.warning( + "Early qwen tool streaming disabled for this " + "Chat turn: completed-envelope queue exceeded " + "its count or byte bound" ) - ], + stream_completed_qwen_tools = False + stream_tool_sequence_safe = False + ordered_segments = [ + segment + for segment in ordered_segments + if segment.kind == "content" + ] + else: + tool_filter.take_ordered_segments() + tool_filter.take_completed_envelopes() + if not ordered_segments and content_delta: + ordered_segments = [ + ToolCallStreamSegment("content", content_delta) + ] + + for segment in ordered_segments: + if segment.kind == "content": + chunk = ChatCompletionChunk( + id=response_id, + model=request.model, + choices=[ + ChatCompletionChunkChoice( + delta=ChatCompletionChunkDelta( + content=segment.text + ), + finish_reason=None, + ) + ], + ) + event = ( + f"data: {chunk.model_dump_json(exclude_none=True)}" + "\n\n" + ) + mark_visible_delta() + yield event + continue + + if segment.kind != "envelope": + stream_tool_sequence_safe = False + continue + _cleaned, completed_calls = parse_tool_calls( + segment.text, + engine.tokenizer, + kwargs.get("tools"), ) - yield f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + completed_calls = completed_calls or [] + completed_keys = [ + _tool_call_semantic_key(tc) for tc in completed_calls + ] + if ( + not completed_calls + or any(key is None for key in completed_keys) + or any( + key[0] not in registered_tool_names + for key in completed_keys + if key is not None + ) + ): + stream_tool_sequence_safe = False + continue + if not stream_tool_sequence_safe: + continue + for tc in completed_calls: + index = len(streamed_tool_calls) + streamed_tool_calls.append(tc) + tc_chunk = ChatCompletionChunk( + id=response_id, + model=request.model, + choices=[ + ChatCompletionChunkChoice( + delta=ChatCompletionChunkDelta( + tool_calls=[ + { + "index": index, + "id": tc.id, + "type": "function", + "function": { + "name": tc.function.name, + "arguments": ( + tc.function.arguments + ), + }, + } + ] + ), + finish_reason=None, + ) + ], + ) + event = ( + f"data: {tc_chunk.model_dump_json(exclude_none=True)}" + "\n\n" + ) + mark_visible_delta() + yield event except Exception as e: error_data = _streaming_error_payload(e, "chat streaming") yield f"data: {json.dumps(error_data)}\n\n" @@ -4996,7 +5399,9 @@ async def stream_chat_completion( ) ], ) - yield f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + event = f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + mark_visible_delta() + yield event if thinking_filter: remaining_thinking = thinking_filter.finish() if remaining_thinking: @@ -5012,7 +5417,9 @@ async def stream_chat_completion( ) ], ) - yield f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + event = f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + mark_visible_delta() + yield event if content_delta: if tool_filter: content_delta = tool_filter.feed(content_delta) @@ -5027,7 +5434,9 @@ async def stream_chat_completion( ) ], ) - yield f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + event = f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + mark_visible_delta() + yield event if tool_filter: remaining = tool_filter.finish() @@ -5042,11 +5451,14 @@ async def stream_chat_completion( ) ], ) - yield f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + event = f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + mark_visible_delta() + yield event # Parse tool calls from accumulated text tool_calls = None cleaned_text = accumulated_text + terminal_tool_calls_authoritative = bool(last_output and last_output.tool_calls) if last_output and last_output.tool_calls: # Protocol parser already extracted structured tool calls. tool_calls = _convert_parser_tool_calls(last_output.tool_calls) @@ -5064,6 +5476,20 @@ async def stream_chat_completion( cleaned_text = extraction.cleaned_text tool_calls = extraction.tool_calls cleaned_thinking = extraction.cleaned_thinking + if tool_calls and qwen_tool_envelope_streaming_capable: + # Raw-text parsing is never allowed to promote malformed or + # unregistered functions on the explicitly capability-gated qwen + # early-stream path. Other parser families retain their existing + # terminal semantics; engine-native structured calls above are + # authoritative and intentionally bypass this API-layer filter. + tool_calls = [ + tool_call + for tool_call in tool_calls + if ( + (key := _tool_call_semantic_key(tool_call)) is not None + and key[0] in registered_tool_names + ) + ] # Process response_format if specified if request.response_format and not tool_calls: @@ -5090,7 +5516,9 @@ async def stream_chat_completion( ) ], ) - yield f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + event = f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + mark_visible_delta() + yield event if cleaned_text: chunk = ChatCompletionChunk( id=response_id, @@ -5102,7 +5530,9 @@ async def stream_chat_completion( ) ], ) - yield f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + event = f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + mark_visible_delta() + yield event # Surface an unterminated paired envelope only when final parsing could not # recover a structured tool call. The candidate begins at the opening marker, @@ -5125,7 +5555,9 @@ async def stream_chat_completion( ) ], ) - yield f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + event = f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + mark_visible_delta() + yield event if recovered_content: chunk = ChatCompletionChunk( id=response_id, @@ -5137,7 +5569,40 @@ async def stream_chat_completion( ) ], ) - yield f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + event = f"data: {chunk.model_dump_json(exclude_none=True)}\n\n" + mark_visible_delta() + yield event + + # A qwen3_coder raw-envelope stream has no engine-side structured parser, + # so preserve each already-emitted validated occurrence even if malformed + # later markup makes terminal extraction partial. Structured engine output + # is authoritative and, by capability contract, can never race this path. + if streamed_tool_calls and not terminal_tool_calls_authoritative: + tool_calls = _merge_streamed_tool_call_prefix( + streamed_tool_calls, + tool_calls, + ) + + # Reconcile by canonical JSON semantics plus occurrence—not raw argument + # formatting or list position. Repeated identical calls remain distinct. + streamed_by_fingerprint: dict[tuple[str, str], list] = {} + reconcilable_streamed = ( + [] if terminal_tool_calls_authoritative else streamed_tool_calls + ) + for streamed in reconcilable_streamed: + fingerprint = _tool_call_semantic_key(streamed) + if fingerprint is not None: + streamed_by_fingerprint.setdefault(fingerprint, []).append(streamed) + streamed_tool_call_ids: set[str] = set() + for final in tool_calls or []: + fingerprint = _tool_call_semantic_key(final) + if fingerprint is None: + continue + candidates = streamed_by_fingerprint.get(fingerprint) or [] + if candidates: + streamed = candidates.pop(0) + final.id = streamed.id + streamed_tool_call_ids.add(streamed.id) # Reverse Gemma 4 parameter renaming for streaming path if tool_calls and "gemma" in (resolved_model or request.model or "").lower(): @@ -5153,6 +5618,8 @@ async def stream_chat_completion( # Emit tool call chunks if found if tool_calls: for i, tc in enumerate(tool_calls): + if tc.id in streamed_tool_call_ids: + continue tc_chunk = ChatCompletionChunk( id=response_id, model=request.model, @@ -5174,7 +5641,9 @@ async def stream_chat_completion( ) ], ) - yield f"data: {tc_chunk.model_dump_json(exclude_none=True)}\n\n" + event = f"data: {tc_chunk.model_dump_json(exclude_none=True)}\n\n" + mark_visible_delta() + yield event # Final chunk with finish_reason finish_reason = ( @@ -5198,16 +5667,35 @@ async def stream_chat_completion( if last_output and last_output.finished: end_time = time.perf_counter() total_duration = end_time - start_time - ttft = (first_token_time - start_time) if first_token_time else total_duration + model_ttft = ( + max(0.0, first_token_time - start_time) + if first_token_time is not None + else None + ) + visible_ttft = ( + max(0.0, first_visible_time - start_time) + if first_visible_time is not None + else None + ) is_diffusion = getattr(engine, "is_diffusion_model", False) if is_diffusion: gen_duration = total_duration else: - gen_duration = end_time - (first_token_time or start_time) + gen_duration = max( + 0.0, + end_time + - ( + first_token_time + if first_token_time is not None + else start_time + ), + ) metric_prefill_duration, metric_gen_duration = _resolve_metric_durations( last_output, is_diffusion=is_diffusion, - prefill_duration=ttft, + prefill_duration=( + model_ttft if model_ttft is not None else total_duration + ), generation_duration=gen_duration, ) get_server_metrics().record_request_complete( @@ -5227,13 +5715,21 @@ async def stream_chat_completion( tokens_per_sec, is_diffusion=is_diffusion, ) + model_ttft_text = ( + f"{model_ttft:.2f}s" if model_ttft is not None else "unavailable" + ) + visible_ttft_text = ( + f"{visible_ttft:.2f}s" if visible_ttft is not None else "unavailable" + ) logger.info( f"Chat completion: model={resolved_model or request.model}, " f"{last_output.completion_tokens} tokens in " f"{total_duration:.2f}s ({speed_text}), " f"prompt: {last_output.prompt_tokens}, finish_reason={finish_reason}, " f"max_tokens={kwargs.get('max_tokens')}, " - f"request_max_tokens={request.max_tokens}" + f"request_max_tokens={request.max_tokens}, " + f"stream_model_ttft={model_ttft_text}, " + f"stream_visible_ttft={visible_ttft_text}" ) # Emit usage chunk if requested @@ -5257,7 +5753,14 @@ async def stream_chat_completion( if model_load_duration > 1.0 else None ), - time_to_first_token=round(ttft, 2), + time_to_first_token=( + round(model_ttft, 2) if model_ttft is not None else None + ), + time_to_first_visible_token=( + round(visible_ttft, 2) + if visible_ttft is not None + else None + ), total_time=round(total_time, 2), prompt_eval_duration=round(metric_prefill_duration, 2), generation_duration=round(metric_gen_duration, 2), @@ -5974,20 +6477,28 @@ async def create_anthropic_message( **chat_kwargs, ) await _raise_if_llm_lease_abort_requested(lease) + inference_request_id = _request_abort_id(engine) + if inference_request_id is not None: + chat_kwargs["_request_id"] = inference_request_id if request.stream: return StreamingResponse( _release_after_stream( - _with_sse_keepalive( - stream_anthropic_messages( - engine, - messages, - request, - resolved_model=resolved_model, - **chat_kwargs, + _with_request_disconnect_abort( + _with_sse_keepalive( + stream_anthropic_messages( + engine, + messages, + request, + resolved_model=resolved_model, + **chat_kwargs, + ), + http_request=http_request, + keepalive_chunk=_resolve_keepalive("anthropic"), ), - http_request=http_request, - keepalive_chunk=_resolve_keepalive("anthropic"), + http_request, + engine, + inference_request_id, ), lease, ), @@ -6486,6 +6997,9 @@ async def create_response( **chat_kwargs, ) await _raise_if_llm_lease_abort_requested(lease) + inference_request_id = _request_abort_id(engine) + if inference_request_id is not None: + chat_kwargs["_request_id"] = inference_request_id if request.stream: sse_headers = {"X-Accel-Buffering": "no", "Cache-Control": "no-cache"} @@ -6493,21 +7007,26 @@ async def create_response( sse_headers["Warning"] = response_format_warning return StreamingResponse( _release_after_stream( - _with_sse_keepalive( - stream_responses_api( - engine, - messages, - request, - input_messages=current_input_messages, - store_response=_should_store_response(request.store), - model_load_duration=model_load_duration, - resolved_model=resolved_model, - response_format=response_format, - native_reasoning=native_reasoning, - **chat_kwargs, + _with_request_disconnect_abort( + _with_sse_keepalive( + stream_responses_api( + engine, + messages, + request, + input_messages=current_input_messages, + store_response=_should_store_response(request.store), + model_load_duration=model_load_duration, + resolved_model=resolved_model, + response_format=response_format, + native_reasoning=native_reasoning, + **chat_kwargs, + ), + http_request=http_request, + keepalive_chunk=_resolve_keepalive("openai_responses"), ), - http_request=http_request, - keepalive_chunk=_resolve_keepalive("openai_responses"), + http_request, + engine, + inference_request_id, ), lease, ), diff --git a/tests/integration/test_e2e_streaming.py b/tests/integration/test_e2e_streaming.py index 8b3dea25e7..b628e318ec 100644 --- a/tests/integration/test_e2e_streaming.py +++ b/tests/integration/test_e2e_streaming.py @@ -29,6 +29,8 @@ class MockGenerationOutput: finished: bool = False tool_calls: Optional[List[Dict[str, Any]]] = None cached_tokens: int = 0 + generated_at: Optional[float] = None + first_token_at: Optional[float] = None class MockTokenizer: @@ -61,6 +63,8 @@ def __init__(self, model_name: str = "test-model"): self._model_name = model_name self._tokenizer = MockTokenizer() self._model_type = "llama" + self._supports_early_tool_call_streaming = False + self.last_stream_output_finished = False # Configurable streaming responses self._stream_outputs: List[MockGenerationOutput] = [] @@ -72,6 +76,10 @@ def model_name(self) -> str: def tokenizer(self): return self._tokenizer + @property + def supports_early_tool_call_streaming(self) -> bool: + return self._supports_early_tool_call_streaming + @property def model_type(self) -> Optional[str]: return self._model_type @@ -101,6 +109,7 @@ async def generate(self, prompt: str, **kwargs) -> MockGenerationOutput: async def stream_generate(self, prompt: str, **kwargs) -> AsyncIterator[MockGenerationOutput]: if self._stream_outputs: for output in self._stream_outputs: + self.last_stream_output_finished = output.finished yield output else: yield MockGenerationOutput( @@ -134,6 +143,7 @@ async def chat(self, messages: List[Dict], **kwargs) -> MockGenerationOutput: async def stream_chat(self, messages: List[Dict], **kwargs) -> AsyncIterator[MockGenerationOutput]: if self._stream_outputs: for output in self._stream_outputs: + self.last_stream_output_finished = output.finished yield output else: yield MockGenerationOutput( @@ -1709,6 +1719,708 @@ async def test_stream_chat_completion_with_tools_parsed_from_split_text_does_not assert max(content_event_indexes) < min(tool_call_event_indexes) assert "tool_calls" in finish_reasons + @pytest.mark.asyncio + async def test_complete_qwen_tool_envelope_streams_once_before_engine_finish(self): + """A validated XML call need not wait for a later terminal output.""" + from mlx_lm.tool_parsers.qwen3_coder import parse_tool_call + + from omlx.api.openai_models import ChatCompletionRequest, Message + from omlx.server import stream_chat_completion + + engine = MockBaseEngine() + engine._supports_early_tool_call_streaming = True + engine.tokenizer.has_tool_calling = True + engine.tokenizer.tool_call_start = "" + engine.tokenizer.tool_call_end = "" + engine.tokenizer.tool_parser = parse_tool_call + engine.set_stream_outputs( + [ + MockGenerationOutput( + text="" + "Sea" + ), + new_text=( + "call>Sea" + ), + completion_tokens=2, + finished=False, + ), + MockGenerationOutput( + text=( + "" + "Seattle" + "" + ), + new_text="ttle", + completion_tokens=3, + finished=False, + ), + # A later empty engine output proves the structured call was + # emitted at envelope close rather than terminal finalization. + MockGenerationOutput( + text=( + "" + "Seattle" + "" + ), + new_text="", + completion_tokens=3, + finished=True, + finish_reason="stop", + ), + ] + ) + tools = [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get weather", + "parameters": { + "type": "object", + "properties": {"city": {"type": "string"}}, + "required": ["city"], + }, + }, + } + ] + request = ChatCompletionRequest( + model="test-model", + messages=[Message(role="user", content="weather")], + stream=True, + stream_options={"include_usage": True}, + tools=tools, + ) + + events = [] + call_seen_before_engine_finish = False + async for event in stream_chat_completion( + engine, + [{"role": "user", "content": "weather"}], + request, + max_tokens=256, + temperature=0, + top_p=1, + top_k=0, + tools=tools, + ): + events.append(event) + if '"tool_calls"' in event and not engine.last_stream_output_finished: + call_seen_before_engine_finish = True + + payloads = [ + json.loads(event[6:-2]) + for event in events + if event.startswith("data: {") + ] + calls = [] + call_event_indexes = [] + finish_index = None + usage = None + for event_index, payload in enumerate(payloads): + if payload.get("usage"): + usage = payload["usage"] + choices = payload.get("choices") or [] + if not choices: + continue + choice = choices[0] + chunk_calls = choice.get("delta", {}).get("tool_calls") or [] + if chunk_calls: + calls.extend(chunk_calls) + call_event_indexes.append(event_index) + if choice.get("finish_reason"): + finish_index = event_index + + assert len(calls) == 1 + assert call_seen_before_engine_finish + assert calls[0]["function"]["name"] == "get_weather" + assert json.loads(calls[0]["function"]["arguments"]) == { + "city": "Seattle" + } + assert call_event_indexes[0] < finish_index + assert usage is not None + assert "time_to_first_token" in usage + assert "time_to_first_visible_token" in usage + streamed_content = "".join( + choice.get("delta", {}).get("content") or "" + for payload in payloads + for choice in payload.get("choices") or [] + ) + assert "" + "Oslo" + ) + full = "before " + envelope + " after" + engine.set_stream_outputs( + [ + MockGenerationOutput( + text=full, + new_text=full, + completion_tokens=1, + finished=False, + ), + MockGenerationOutput( + text=full, + new_text="", + completion_tokens=1, + finished=True, + finish_reason="stop", + ), + ] + ) + tools = [{"type": "function", "function": {"name": "get_weather"}}] + request = ChatCompletionRequest( + model="test-model", + messages=[Message(role="user", content="weather")], + stream=True, + tools=tools, + ) + + ordered = [] + async for event in stream_chat_completion( + engine, + [{"role": "user", "content": "weather"}], + request, + tools=tools, + ): + if not event.startswith("data: {"): + continue + payload = json.loads(event[6:-2]) + choices = payload.get("choices") or [] + if not choices: + continue + delta = choices[0].get("delta") or {} + if delta.get("content"): + ordered.append(("content", delta["content"])) + if delta.get("tool_calls"): + ordered.append( + ("tool", delta["tool_calls"][0]["function"]["name"]) + ) + + assert ordered == [ + ("content", "before "), + ("tool", "get_weather"), + ("content", " after"), + ] + + @pytest.mark.asyncio + async def test_seventeen_call_overflow_keeps_eighteenth_terminal_ordered(self): + from mlx_lm.tool_parsers.qwen3_coder import parse_tool_call + + from omlx.api.openai_models import ChatCompletionRequest, Message + from omlx.server import stream_chat_completion + + engine = MockBaseEngine() + engine._supports_early_tool_call_streaming = True + engine.tokenizer.has_tool_calling = True + engine.tokenizer.tool_call_start = "" + engine.tokenizer.tool_call_end = "" + engine.tokenizer.tool_parser = parse_tool_call + + def envelope(index): + return ( + "" + f"{index}" + ) + + first = "".join(envelope(index) for index in range(17)) + eighteenth = envelope(17) + engine.set_stream_outputs( + [ + MockGenerationOutput( + text=first, + new_text=first, + completion_tokens=17, + finished=False, + ), + MockGenerationOutput( + text=first + eighteenth, + new_text=eighteenth, + completion_tokens=18, + finished=False, + ), + MockGenerationOutput( + text=first + eighteenth, + new_text="", + completion_tokens=18, + finished=True, + finish_reason="stop", + ), + ] + ) + tools = [{"type": "function", "function": {"name": "record"}}] + request = ChatCompletionRequest( + model="test-model", + messages=[Message(role="user", content="record")], + stream=True, + tools=tools, + ) + + calls = [] + seen_before_finish = False + async for event in stream_chat_completion( + engine, + [{"role": "user", "content": "record"}], + request, + tools=tools, + ): + if not event.startswith("data: {"): + continue + payload = json.loads(event[6:-2]) + choices = payload.get("choices") or [] + chunk_calls = ( + choices[0].get("delta", {}).get("tool_calls") if choices else None + ) + if chunk_calls: + calls.extend(chunk_calls) + seen_before_finish |= not engine.last_stream_output_finished + + assert not seen_before_finish + assert len(calls) == 18 + assert [ + int(json.loads(call["function"]["arguments"])["i"]) + for call in calls + ] == list(range(18)) + + @pytest.mark.asyncio + async def test_same_output_structured_call_beats_enabled_raw_candidate(self): + from mlx_lm.tool_parsers.qwen3_coder import parse_tool_call + + from omlx.api.openai_models import ChatCompletionRequest, Message + from omlx.server import stream_chat_completion + + engine = MockBaseEngine() + engine._supports_early_tool_call_streaming = True + engine.tokenizer.has_tool_calling = True + engine.tokenizer.tool_call_start = "" + engine.tokenizer.tool_call_end = "" + engine.tokenizer.tool_parser = parse_tool_call + raw = ( + "" + "Raw" + ) + engine.set_stream_outputs( + [ + MockGenerationOutput( + text=raw, + new_text=raw, + completion_tokens=1, + finished=True, + finish_reason="tool_calls", + tool_calls=[ + { + "id": "call_authoritative", + "name": "lookup_weather", + "arguments": '{"city":"Paris"}', + } + ], + ) + ] + ) + tools = [ + {"type": "function", "function": {"name": "get_weather"}}, + {"type": "function", "function": {"name": "lookup_weather"}}, + ] + request = ChatCompletionRequest( + model="test-model", + messages=[Message(role="user", content="weather")], + stream=True, + tools=tools, + ) + + calls = [] + async for event in stream_chat_completion( + engine, + [{"role": "user", "content": "weather"}], + request, + tools=tools, + ): + if event.startswith("data: {"): + payload = json.loads(event[6:-2]) + choices = payload.get("choices") or [] + if choices: + calls.extend( + choices[0].get("delta", {}).get("tool_calls") or [] + ) + + assert [call["function"]["name"] for call in calls] == [ + "lookup_weather" + ] + assert calls[0]["id"] == "call_authoritative" + + @pytest.mark.asyncio + async def test_scheduler_structured_tool_call_disables_raw_early_candidate(self): + """Default-false capability keeps scheduler structure authoritative.""" + from mlx_lm.tool_parsers.qwen3_coder import parse_tool_call + + from omlx.api.openai_models import ChatCompletionRequest, Message + from omlx.server import stream_chat_completion + + engine = MockBaseEngine() # explicit capability remains false + engine.tokenizer.has_tool_calling = True + engine.tokenizer.tool_call_start = "" + engine.tokenizer.tool_call_end = "" + engine.tokenizer.tool_parser = parse_tool_call + raw = ( + "" + "Raw" + ) + engine.set_stream_outputs( + [ + MockGenerationOutput( + text=raw, + new_text=raw, + completion_tokens=1, + finished=False, + ), + MockGenerationOutput( + text=raw, + new_text="", + completion_tokens=1, + finished=True, + finish_reason="tool_calls", + tool_calls=[ + { + "id": "call_scheduler", + "name": "lookup_weather", + "arguments": '{"city":"Paris"}', + } + ], + ), + ] + ) + tools = [ + {"type": "function", "function": {"name": "get_weather"}}, + {"type": "function", "function": {"name": "lookup_weather"}}, + ] + request = ChatCompletionRequest( + model="test-model", + messages=[Message(role="user", content="weather")], + stream=True, + tools=tools, + ) + + calls = [] + seen_before_finish = False + async for event in stream_chat_completion( + engine, + [{"role": "user", "content": "weather"}], + request, + tools=tools, + ): + if not event.startswith("data: {"): + continue + payload = json.loads(event[6:-2]) + choices = payload.get("choices") or [] + chunk_calls = ( + choices[0].get("delta", {}).get("tool_calls") if choices else None + ) + if chunk_calls: + calls.extend(chunk_calls) + seen_before_finish |= not engine.last_stream_output_finished + + assert not seen_before_finish + assert [call["function"]["name"] for call in calls] == [ + "lookup_weather" + ] + assert calls[0]["id"] == "call_scheduler" + + @pytest.mark.asyncio + async def test_disabled_early_capability_preserves_terminal_parser_semantics(self): + """The Qwen early gate must not tighten unrelated terminal parsing.""" + from mlx_lm.tool_parsers.qwen3_coder import parse_tool_call + + from omlx.api.openai_models import ChatCompletionRequest, Message + from omlx.server import stream_chat_completion + + engine = MockBaseEngine() # explicit early-stream capability is false + engine.tokenizer.has_tool_calling = True + engine.tokenizer.tool_call_start = "" + engine.tokenizer.tool_call_end = "" + engine.tokenizer.tool_parser = parse_tool_call + raw = ( + "" + "1" + ) + engine.set_stream_outputs( + [ + MockGenerationOutput( + text=raw, + new_text=raw, + completion_tokens=1, + finished=False, + ), + MockGenerationOutput( + text=raw, + new_text="", + completion_tokens=1, + finished=True, + finish_reason="stop", + ), + ] + ) + tools = [{"type": "function", "function": {"name": "registered_name"}}] + request = ChatCompletionRequest( + model="test-model", + messages=[Message(role="user", content="run")], + stream=True, + tools=tools, + ) + + calls = [] + seen_before_finish = False + async for event in stream_chat_completion( + engine, + [{"role": "user", "content": "run"}], + request, + tools=tools, + ): + if not event.startswith("data: {"): + continue + payload = json.loads(event[6:-2]) + choices = payload.get("choices") or [] + chunk_calls = ( + choices[0].get("delta", {}).get("tool_calls") if choices else None + ) + if chunk_calls: + calls.extend(chunk_calls) + seen_before_finish |= not engine.last_stream_output_finished + + assert not seen_before_finish + assert [call["function"]["name"] for call in calls] == [ + "legacy_terminal_name" + ] + + @pytest.mark.asyncio + async def test_unknown_envelope_makes_later_early_sequence_terminal_only(self): + """Unknown/malformed siblings cannot create a partial early sequence.""" + from mlx_lm.tool_parsers.qwen3_coder import parse_tool_call + + from omlx.api.openai_models import ChatCompletionRequest, Message + from omlx.server import stream_chat_completion + + engine = MockBaseEngine() + engine._supports_early_tool_call_streaming = True + engine.tokenizer.has_tool_calling = True + engine.tokenizer.tool_call_start = "" + engine.tokenizer.tool_call_end = "" + engine.tokenizer.tool_parser = parse_tool_call + unknown = ( + "" + "1" + ) + valid = ( + "" + "Oslo" + ) + engine.set_stream_outputs( + [ + MockGenerationOutput( + text=unknown, + new_text=unknown, + completion_tokens=1, + finished=False, + ), + MockGenerationOutput( + text=unknown + valid, + new_text=valid, + completion_tokens=2, + finished=False, + ), + MockGenerationOutput( + text=unknown + valid, + new_text="", + completion_tokens=2, + finished=True, + finish_reason="stop", + ), + ] + ) + tools = [{"type": "function", "function": {"name": "get_weather"}}] + request = ChatCompletionRequest( + model="test-model", + messages=[Message(role="user", content="weather")], + stream=True, + tools=tools, + ) + + calls = [] + seen_before_finish = False + async for event in stream_chat_completion( + engine, + [{"role": "user", "content": "weather"}], + request, + tools=tools, + ): + if not event.startswith("data: {"): + continue + payload = json.loads(event[6:-2]) + choices = payload.get("choices") or [] + chunk_calls = ( + choices[0].get("delta", {}).get("tool_calls") if choices else None + ) + if chunk_calls: + calls.extend(chunk_calls) + seen_before_finish |= not engine.last_stream_output_finished + + assert not seen_before_finish + assert [call["function"]["name"] for call in calls] == ["get_weather"] + + def test_semantic_tool_dedupe_preserves_duplicate_occurrences(self): + from omlx.api.openai_models import FunctionCall, ToolCall + from omlx.server import _merge_streamed_tool_call_prefix + + early = ToolCall( + id="call_early", + function=FunctionCall(name="f", arguments='{"b":2,"a":1}'), + ) + same_semantics = ToolCall( + id="call_terminal_1", + function=FunctionCall(name="f", arguments='{ "a": 1, "b": 2 }'), + ) + repeated = ToolCall( + id="call_terminal_2", + function=FunctionCall(name="f", arguments='{"a":1,"b":2}'), + ) + + merged = _merge_streamed_tool_call_prefix( + [early], + [same_semantics, repeated], + ) + assert [call.id for call in merged] == ["call_early", "call_terminal_2"] + + @pytest.mark.asyncio + async def test_chat_usage_separates_model_and_visible_ttft_exactly( + self, + monkeypatch, + ): + from omlx.api.openai_models import ( + ChatCompletionChunk, + ChatCompletionRequest, + Message, + ) + from omlx.server import stream_chat_completion + + visible_serialized = False + original_dump = ChatCompletionChunk.model_dump_json + + def tracked_dump(chunk, *args, **kwargs): + nonlocal visible_serialized + result = original_dump(chunk, *args, **kwargs) + if any( + getattr(choice.delta, "content", None) + for choice in chunk.choices + ): + visible_serialized = True + return result + + monkeypatch.setattr(ChatCompletionChunk, "model_dump_json", tracked_dump) + ticks = iter([100.0, 102.5, 110.0]) + + def perf_counter(): + value = next(ticks) + if value == 102.5: + assert visible_serialized + return value + + monkeypatch.setattr("omlx.server.time.perf_counter", perf_counter) + engine = MockBaseEngine() + engine.set_stream_outputs( + [ + MockGenerationOutput( + text="hello", + new_text="hello", + completion_tokens=1, + first_token_at=101.25, + generated_at=101.75, + finished=True, + finish_reason="stop", + ) + ] + ) + request = ChatCompletionRequest( + model="test-model", + messages=[Message(role="user", content="hello")], + stream=True, + stream_options={"include_usage": True}, + ) + + usage = None + async for event in stream_chat_completion( + engine, + [{"role": "user", "content": "hello"}], + request, + ): + if event.startswith("data: {"): + payload = json.loads(event[6:-2]) + usage = payload.get("usage") or usage + + assert usage["time_to_first_token"] == 1.25 + assert usage["time_to_first_visible_token"] == 2.5 + assert "tool_envelope_buffer_duration" not in usage + + def test_local_engine_capability_requires_explicit_parser_absence(self): + from types import SimpleNamespace + + from omlx.engine.batched import BatchedEngine + from omlx.engine.vlm import VLMBatchedEngine + + for engine_type in (BatchedEngine, VLMBatchedEngine): + engine = engine_type.__new__(engine_type) + engine._engine = None + assert not engine.supports_early_tool_call_streaming + scheduler = SimpleNamespace(_output_parser_factory=object()) + engine._engine = SimpleNamespace( + engine=SimpleNamespace(scheduler=scheduler) + ) + assert not engine.supports_early_tool_call_streaming + scheduler._output_parser_factory = None + assert engine.supports_early_tool_call_streaming + + def test_early_tool_gate_requires_exact_qwen3_coder_parser(self): + from mlx_lm.tool_parsers.qwen3_coder import parse_tool_call + + from omlx.server import _chat_can_stream_qwen_tool_envelopes + + engine = MockBaseEngine() + engine._supports_early_tool_call_streaming = True + engine.tokenizer.tool_parser = parse_tool_call + assert _chat_can_stream_qwen_tool_envelopes(engine) + + def lookalike(*_args, **_kwargs): + return None + + lookalike.__module__ = "third_party.qwen3_coder" + engine.tokenizer.tool_parser = lookalike + assert not _chat_can_stream_qwen_tool_envelopes(engine) + + lookalike.__module__ = "mlx_lm.tool_parsers.qwen3_coder" + lookalike.__name__ = "parse_tool_call" + assert not _chat_can_stream_qwen_tool_envelopes(engine) + @pytest.mark.asyncio async def test_stream_chat_completion_with_tools_parsed_from_namespaced_text_does_not_leak_markup(self): """Supported namespaced tags must not leak into streamed content deltas.""" diff --git a/tests/test_admin_distributed_cache_clear.py b/tests/test_admin_distributed_cache_clear.py new file mode 100644 index 0000000000..12e25755d5 --- /dev/null +++ b/tests/test_admin_distributed_cache_clear.py @@ -0,0 +1,128 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Admin cache maintenance must reach every rank of a loaded cluster.""" + +import subprocess +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from fastapi import HTTPException + +import omlx.admin.routes as admin_routes + + +def _pool(clear): + core = SimpleNamespace(scheduler=None, clear_prompt_caches=clear) + entry = SimpleNamespace(engine=core) + pool = SimpleNamespace() + pool.get_status = MagicMock( + return_value={"models": [{"id": "cluster-model", "loaded": True}]} + ) + pool._entries = {"cluster-model": entry} + return pool + + +@pytest.mark.asyncio +async def test_ssd_clear_aggregates_distributed_rank_results(): + clear = AsyncMock( + return_value={ + "status": "ok", + "ssd_deleted": 9, + "hot_cleared": 0, + "ranks": [{"rank": 0}, {"rank": 1}], + } + ) + with ( + patch.object(admin_routes, "_get_engine_pool", return_value=_pool(clear)), + patch.object(admin_routes, "_get_global_settings", return_value=None), + ): + result = await admin_routes.clear_ssd_cache(is_admin=True) + + clear.assert_awaited_once_with(ssd=True) + assert result == { + "status": "ok", + "total_deleted": 9, + "distributed_ranks": 2, + } + + +@pytest.mark.asyncio +async def test_ssd_clear_surfaces_partial_cluster_failure(): + clear = AsyncMock(side_effect=RuntimeError("rank 1 unreachable")) + with ( + patch.object(admin_routes, "_get_engine_pool", return_value=_pool(clear)), + patch.object(admin_routes, "_get_global_settings", return_value=None), + pytest.raises(HTTPException) as raised, + ): + await admin_routes.clear_ssd_cache(is_admin=True) + + assert raised.value.status_code == 503 + assert "rank 1 unreachable" in raised.value.detail + + +@pytest.mark.asyncio +async def test_ssd_clear_removes_unloaded_local_cluster_roots(tmp_path): + cache_dir = tmp_path / "cache" + cluster_root = cache_dir / "cluster-prompt-snapshots" + legacy_root = tmp_path / "cluster/runtime/prompt-cache-ssd" + for root in (cluster_root, legacy_root): + root.mkdir(parents=True) + (root / "entry.safetensors").write_text("cached", encoding="utf-8") + pool = SimpleNamespace( + get_status=lambda: {"models": []}, + _entries={}, + ) + settings = SimpleNamespace( + base_path=tmp_path, + cache=SimpleNamespace(get_ssd_cache_dir=lambda _base: cache_dir), + ) + + with ( + patch.object(admin_routes, "_get_engine_pool", return_value=pool), + patch.object(admin_routes, "_get_global_settings", return_value=settings), + patch.object( + admin_routes, + "_clear_cold_remote_cluster_cache_roots", + return_value=(0, 0), + ), + ): + result = await admin_routes.clear_ssd_cache(is_admin=True) + + assert result["total_deleted"] == 2 + assert not cluster_root.exists() + assert not legacy_root.exists() + + +def test_cold_ssd_clear_resolves_cache_paths_on_each_peer(tmp_path, monkeypatch): + from omlx.cluster.deployment import ClusterHost + + roots = ( + tmp_path / "cache/cluster-prompt-snapshots", + tmp_path / "cluster/runtime/prompt-cache-ssd", + ) + hosts = ( + ClusterHost("local", "127.0.0.1", ("10.0.0.1",)), + ClusterHost("peer", "peer.local", ("10.0.0.2",)), + ) + registry = SimpleNamespace(list=lambda: (SimpleNamespace(hosts=hosts),)) + calls = [] + + def run(argv, **kwargs): + calls.append((argv, kwargs)) + return subprocess.CompletedProcess(argv, 0, "7\n", "") + + monkeypatch.setattr( + "omlx.cluster.registry.get_cluster_registry", + lambda: registry, + ) + deleted, ranks = admin_routes._clear_cold_remote_cluster_cache_roots( + roots, + runner=run, + ) + + assert (deleted, ranks) == (7, 2) + assert len(calls) == 1 + command = calls[0][0][-1] + assert calls[0][0][-2] == "peer.local" + assert "GlobalSettings.load" in command + assert str(tmp_path) not in command diff --git a/tests/test_admin_hot_cache_clear.py b/tests/test_admin_hot_cache_clear.py index b95c158bc7..48d344d84f 100644 --- a/tests/test_admin_hot_cache_clear.py +++ b/tests/test_admin_hot_cache_clear.py @@ -13,9 +13,8 @@ import pytest -import omlx.server # noqa: F401 — triggers set_admin_getters import omlx.admin.routes as admin_routes - +import omlx.server # noqa: F401 — triggers set_admin_getters MODEL_ID = "test-model" @@ -121,7 +120,12 @@ def test_response_shape(self): ): result = _run_clear() - assert set(result.keys()) == {"status", "total_cleared", "bytes_reclaimed"} + assert set(result.keys()) == { + "status", + "total_cleared", + "bytes_reclaimed", + "distributed_ranks", + } assert result["status"] == "ok" @@ -188,9 +192,8 @@ def test_non_matching_runtime_error_propagates(self): ) with _reclaim_env() as env, patch.object( admin_routes, "_get_engine_pool", return_value=pool - ): - with pytest.raises(RuntimeError, match="boom"): - _run_clear() + ), pytest.raises(RuntimeError, match="boom"): + _run_clear() assert not env.get_mlx_executor.called, "must not fall back on a non-shutdown error" def test_mixed_loaded_and_orphan_no_double_count(self): diff --git a/tests/test_cluster_control_plane.py b/tests/test_cluster_control_plane.py new file mode 100644 index 0000000000..0a50ee51ea --- /dev/null +++ b/tests/test_cluster_control_plane.py @@ -0,0 +1,249 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Reliable TCP control plane kept independent of MLX/JACCL collectives.""" + +import pickle +import socket +import struct +import threading +import zlib + +import pytest + +from omlx.cluster.control_plane import RankControlPlane + + +def _free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as stream: + stream.bind(("127.0.0.1", 0)) + return int(stream.getsockname()[1]) + + +def test_rank_control_plane_broadcasts_objects_in_sequence(): + port = _free_port() + token = "a" * 64 + expected = [None, ("request", {"max_tokens": 7}), [], [3, 9]] + received = [] + failures = [] + + def coordinator(): + try: + with RankControlPlane( + rank=0, + world_size=2, + host="127.0.0.1", + port=port, + token=token, + connect_timeout=5, + io_timeout=5, + ) as control: + for value in expected: + assert control.broadcast_object(value) is value + except Exception as exc: # pragma: no cover - relayed to main thread + failures.append(exc) + + thread = threading.Thread(target=coordinator) + thread.start() + try: + with RankControlPlane( + rank=1, + world_size=2, + host="127.0.0.1", + port=port, + token=token, + connect_timeout=5, + io_timeout=5, + ) as control: + for _ in expected: + received.append(control.broadcast_object(None)) + finally: + thread.join(timeout=5) + + assert not thread.is_alive() + assert failures == [] + assert received == expected + + +def test_rank_control_plane_supports_barrier_and_nonzero_owned_bytes(): + port = _free_port() + token = "c" * 64 + worker_owned = b"worker-one-cache-plan" + coordinator_owned = b"rank-zero-follow-up" + received = {} + failures = [] + + def participant(rank): + try: + with RankControlPlane( + rank=rank, + world_size=3, + host="127.0.0.1", + port=port, + token=token, + connect_timeout=5, + io_timeout=5, + ) as control: + obj = control.broadcast_object( + {"kind": "request"} if rank == 0 else None + ) + control.barrier() + from_worker = control.broadcast_owned_bytes( + worker_owned if rank == 1 else None, + source_rank=1, + expected_size=len(worker_owned), + ) + from_coordinator = control.broadcast_owned_bytes( + coordinator_owned if rank == 0 else None, + source_rank=0, + expected_size=len(coordinator_owned), + ) + received[rank] = (obj, from_worker, from_coordinator) + except Exception as exc: # pragma: no cover - relayed below + failures.append(exc) + + threads = [threading.Thread(target=participant, args=(rank,)) for rank in range(3)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=8) + + assert all(not thread.is_alive() for thread in threads) + assert failures == [] + assert received == { + rank: ({"kind": "request"}, worker_owned, coordinator_owned) + for rank in range(3) + } + + +def test_rank_control_plane_rejects_invalid_identity(): + try: + RankControlPlane( + rank=2, + world_size=2, + host="127.0.0.1", + port=12345, + token="x", + ) + except ValueError as exc: + assert "identity" in str(exc) + else: # pragma: no cover + raise AssertionError("invalid rank identity was accepted") + + +def test_invalid_handshake_is_dropped_without_blocking_a_valid_rank(): + port = _free_port() + token = "b" * 64 + failures = [] + + def coordinator(): + try: + with RankControlPlane( + rank=0, + world_size=2, + host="127.0.0.1", + port=port, + token=token, + connect_timeout=3, + io_timeout=3, + ) as control: + control.broadcast_object({"ready": True}) + except Exception as exc: # pragma: no cover - relayed below + failures.append(exc) + + thread = threading.Thread(target=coordinator) + thread.start() + for _attempt in range(100): + rogue = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + rogue.connect(("127.0.0.1", port)) + break + except ConnectionRefusedError: + rogue.close() + threading.Event().wait(0.01) + else: # pragma: no cover - diagnostics for a wedged test host + pytest.fail("coordinator listener did not start") + rogue.sendall(b"x" * struct.calcsize("!4sII64s")) + rogue.close() + + with RankControlPlane( + rank=1, + world_size=2, + host="127.0.0.1", + port=port, + token=token, + connect_timeout=3, + io_timeout=3, + ) as control: + assert control.broadcast_object(None) == {"ready": True} + thread.join(3) + + assert not thread.is_alive() + assert failures == [] + + +def test_worker_requires_a_valid_coordinator_acknowledgement(): + port = _free_port() + ready = threading.Event() + + def fake_coordinator(): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind(("127.0.0.1", port)) + listener.listen(1) + ready.set() + stream, _ = listener.accept() + with stream: + challenge = b"q" * 32 + stream.sendall(struct.pack("!4sI32s", b"OC2C", 1, challenge)) + handshake = stream.recv(struct.calcsize("!4sII32s")) + assert b"c" * 64 not in handshake + stream.sendall(struct.pack("!4sI32s", b"NOPE", 1, b"\0" * 32)) + + thread = threading.Thread(target=fake_coordinator) + thread.start() + assert ready.wait(2) + with ( + pytest.raises(RuntimeError, match="not acknowledged"), + RankControlPlane( + rank=1, + world_size=2, + host="127.0.0.1", + port=port, + token="c" * 64, + connect_timeout=2, + io_timeout=2, + ), + ): + pass + thread.join(2) + assert not thread.is_alive() + + +def test_worker_authenticates_payload_before_unpickling(): + sender, receiver = socket.socketpair() + control = RankControlPlane( + rank=1, + world_size=2, + host="127.0.0.1", + port=12345, + token="d" * 64, + ) + control._stream = receiver + payload = pickle.dumps({"unsafe": "payload"}) + sender.sendall( + struct.pack( + "!4sIIII32s", + b"OC2M", + 1, + 1, + len(payload), + zlib.crc32(payload), + b"\0" * 32, + ) + + payload + ) + try: + with pytest.raises(RuntimeError, match="authentication"): + control.broadcast_object(None) + finally: + sender.close() + control.close() diff --git a/tests/test_cluster_deployment.py b/tests/test_cluster_deployment.py index 58d739c32f..8ce6357b16 100644 --- a/tests/test_cluster_deployment.py +++ b/tests/test_cluster_deployment.py @@ -83,10 +83,46 @@ def test_deployment_round_trip_and_worker_plan_are_json_only(): assert restored == deployment assert plan_hash == deployment.plan_hash assert assignments == deployment.assignments - assert deployment.hostfile_dict()["envs"] == ["MLX_METAL_FAST_SYNCH=1"] + assert "MLX_METAL_FAST_SYNCH=1" in deployment.hostfile_dict()["envs"] assert deployment.distributed_init_backend == "jaccl" +def test_hostfile_envs_carry_stability_defaults(monkeypatch): + for name in ( + "MLX_MAX_OPS_PER_BUFFER", + "MLX_MAX_MB_PER_BUFFER", + "JACCL_PROGRESS_TIMEOUT_MS", + "JACCL_TIMEOUT_ACTION", + ): + monkeypatch.delenv(name, raising=False) + deployment = _deployment() + + envs = deployment.hostfile_dict()["envs"] + + # Metal command-buffer caps: an unbounded buffer overruns the GPU + # driver's ~10 s timeout, which answers with SIGABRT and orphaned wired + # memory. JACCL knobs pin the wheel's ProgressGuard/teardown-exit posture. + assert "MLX_MAX_OPS_PER_BUFFER=16" in envs + assert "MLX_MAX_MB_PER_BUFFER=512" in envs + assert "JACCL_PROGRESS_TIMEOUT_MS=30000" in envs + assert "JACCL_TIMEOUT_ACTION=teardown-exit" in envs + + +def test_hostfile_envs_respect_operator_overrides(monkeypatch): + monkeypatch.setenv("MLX_MAX_OPS_PER_BUFFER", "32") + monkeypatch.setenv("JACCL_PROGRESS_TIMEOUT_MS", "60000") + deployment = _deployment() + + envs = deployment.hostfile_dict()["envs"] + + assert "MLX_MAX_OPS_PER_BUFFER=32" in envs + assert "MLX_MAX_OPS_PER_BUFFER=16" not in envs + assert "JACCL_PROGRESS_TIMEOUT_MS=60000" in envs + # Untouched knobs keep their tuned defaults. + assert "MLX_MAX_MB_PER_BUFFER=512" in envs + assert "JACCL_TIMEOUT_ACTION=teardown-exit" in envs + + def test_deployment_round_trip_preserves_the_selected_context(): deployment = _deployment() deployment = ClusterDeployment( diff --git a/tests/test_cluster_inference_worker.py b/tests/test_cluster_inference_worker.py index 116d424118..221083d473 100644 --- a/tests/test_cluster_inference_worker.py +++ b/tests/test_cluster_inference_worker.py @@ -3,7 +3,11 @@ import contextlib import json +import os +import signal +import sys import threading +import time from types import SimpleNamespace from typing import Any @@ -18,7 +22,9 @@ _server_arguments, _validate_loaded_stage, _validate_measured_weight_bytes, + _wait_for_serve_release, _watch_launcher_parent, + _write_cancel_request, build_parser, ) from omlx.cluster.planner import PipelineAssignment @@ -26,6 +32,84 @@ GiB = 1024**3 +def test_worker_waits_for_matching_supervisor_serve_release(tmp_path): + deployment_id = "cluster-test" + plan_hash = "a" * 64 + marker = tmp_path / f"{deployment_id}-serve.json" + marker.write_text( + json.dumps( + { + "schema_version": 1, + "deployment_id": deployment_id, + "plan_hash": plan_hash, + "world_size": 2, + } + ) + ) + + _wait_for_serve_release(tmp_path, deployment_id, plan_hash, 2, timeout=0) + + +@pytest.mark.parametrize("timeout", [None, 300.0, 60.0]) +def test_worker_wait_budget_allows_slow_peer_loading(tmp_path, timeout): + elapsed = 0.0 + + def advance(seconds): + nonlocal elapsed + elapsed += seconds + if elapsed >= 121.0: + (tmp_path / "cluster-test-serve.json").write_text( + json.dumps( + { + "schema_version": 1, + "deployment_id": "cluster-test", + "plan_hash": "a" * 64, + "world_size": 2, + } + ) + ) + + kwargs = {} if timeout is None else {"timeout": timeout} + outcome = ( + pytest.raises(TimeoutError) if timeout == 60.0 else contextlib.nullcontext() + ) + with outcome: + _wait_for_serve_release( + tmp_path, + "cluster-test", + "a" * 64, + 2, + clock=lambda: elapsed, + sleep=advance, + **kwargs, + ) + assert elapsed == 60.0 if timeout == 60.0 else elapsed >= 121.0 + + +def test_worker_rejects_stale_supervisor_serve_release(tmp_path): + deployment_id = "cluster-test" + marker = tmp_path / f"{deployment_id}-serve.json" + marker.write_text( + json.dumps( + { + "schema_version": 1, + "deployment_id": deployment_id, + "plan_hash": "old", + "world_size": 2, + } + ) + ) + + with pytest.raises(TimeoutError, match="did not release"): + _wait_for_serve_release( + tmp_path, + deployment_id, + "new", + 2, + timeout=0, + ) + + def test_distributed_minimax_protocol_replaces_generic_tool_and_thinking_markers( tmp_path, ): @@ -199,6 +283,7 @@ def test_launcher_watchdog_records_reason_and_exits_reparented_rank(): updates: list[tuple[str, dict]] = [] events: list[dict] = [] exit_codes: list[int] = [] + releases: list[str] = [] marker = SimpleNamespace( update=lambda phase, **extra: updates.append((phase, extra)) ) @@ -210,6 +295,7 @@ def test_launcher_watchdog_records_reason_and_exits_reparented_rank(): wait=lambda _seconds: None, exit_process=exit_codes.append, emit_event=events.append, + release_memory=releases.append, ) assert updates == [ @@ -224,6 +310,9 @@ def test_launcher_watchdog_records_reason_and_exits_reparented_rank(): ) ] assert events[0]["type"] == "launcher_lost" + # The Metal release runs before the exit: os._exit skips every + # finally/atexit handler, so a skipped release orphans wired memory. + assert len(releases) == 1 assert exit_codes == [1] @@ -595,7 +684,12 @@ def _run_rank( ) monkeypatch.setattr(inference_worker, "_install_signal_handlers", lambda: None) monkeypatch.setattr( - inference_worker, "_start_launcher_watchdog", lambda _m, _pid: None + inference_worker, + "_wait_for_serve_release", + lambda *_args, **_kwargs: None, + ) + monkeypatch.setattr( + inference_worker, "_start_launcher_watchdog", lambda _m, _pid, **_kw: None ) def fake_wired(desired): @@ -1119,6 +1213,275 @@ def test_the_marker_is_removed_when_the_rank_exits_cleanly(monkeypatch, tmp_path assert list(tmp_path.glob("*.json")) == [] +def test_launcher_watchdog_fires_on_a_stale_launcher_lease(tmp_path): + updates: list[tuple[str, dict]] = [] + events: list[dict] = [] + exit_codes: list[int] = [] + aborts: list[str] = [] + releases: list[str] = [] + marker = SimpleNamespace( + update=lambda phase, **extra: updates.append((phase, extra)) + ) + lease = tmp_path / "launcher-lease.json" + lease.write_text("{}", encoding="utf-8") + stale = time.time() - 120.0 + os.utime(lease, (stale, stale)) + + _watch_launcher_parent( + 42, + marker, + watched_marker_path=lease, + marker_stale_after=45.0, + get_parent_pid=lambda: 42, + wait=lambda _seconds: None, + exit_process=exit_codes.append, + emit_event=events.append, + on_abort=aborts.append, + release_memory=releases.append, + ) + + assert updates[0][0] == "launcher_lost" + assert "stale" in updates[0][1]["error"] + # The abort stage ran before the exit stage. + assert len(aborts) == 1 + assert events[0]["type"] == "launcher_lost" + assert len(releases) == 1 + assert exit_codes == [1] + + +def test_launcher_watchdog_ignores_a_fresh_lease(tmp_path): + exit_codes: list[int] = [] + marker = SimpleNamespace(update=lambda phase, **extra: None) + lease = tmp_path / "launcher-lease.json" + lease.write_text("{}", encoding="utf-8") + + polls = [0] + + class StopLoopError(Exception): + pass + + def wait(_seconds): + polls[0] += 1 + if polls[0] >= 3: + raise StopLoopError + + with pytest.raises(StopLoopError): + _watch_launcher_parent( + 42, + marker, + watched_marker_path=lease, + marker_stale_after=45.0, + get_parent_pid=lambda: 42, + wait=wait, + exit_process=exit_codes.append, + emit_event=lambda _event: None, + ) + + assert exit_codes == [] + + +def test_launcher_watchdog_ignores_a_lease_that_never_appeared(tmp_path): + exit_codes: list[int] = [] + marker = SimpleNamespace(update=lambda phase, **extra: None) + missing = tmp_path / "not-yet-created-lease.json" + + polls = [0] + + class StopLoopError(Exception): + pass + + def wait(_seconds): + polls[0] += 1 + if polls[0] >= 3: + raise StopLoopError + + with pytest.raises(StopLoopError): + _watch_launcher_parent( + 42, + marker, + watched_marker_path=missing, + marker_stale_after=45.0, + get_parent_pid=lambda: 42, + wait=wait, + exit_process=exit_codes.append, + emit_event=lambda _event: None, + ) + + assert exit_codes == [] + + +def test_cancel_request_file_matches_the_telemetry_contract(tmp_path): + _write_cancel_request( + str(tmp_path), "dep-9", "peer watchdog test", plan_hash="e" * 64 + ) + + payload = json.loads((tmp_path / "dep-9-cancel.json").read_text(encoding="utf-8")) + assert payload["schema_version"] == 1 + assert payload["deployment_id"] == "dep-9" + assert payload["plan_hash"] == "e" * 64 + assert payload["scope"] == "all" + assert isinstance(payload["epoch"], int) and payload["epoch"] > 0 + assert payload["reason"] == "peer watchdog test" + + +def test_cancel_request_epoch_advances_past_an_existing_clock_jump(tmp_path): + path = tmp_path / "dep-9-cancel.json" + path.write_text(json.dumps({"epoch": 9_999_999_999_999}), encoding="utf-8") + + _write_cancel_request( + str(tmp_path), "dep-9", "new event", plan_hash="f" * 64 + ) + + payload = json.loads(path.read_text(encoding="utf-8")) + assert payload["epoch"] == 10_000_000_000_000 + + +def _fake_mlx_core(calls: list[str], *, with_metal: bool = True) -> SimpleNamespace: + metal = ( + SimpleNamespace(clear_cache=lambda: calls.append("metal.clear_cache")) + if with_metal + else None + ) + fake = SimpleNamespace( + set_wired_limit=lambda limit: calls.append(f"set_wired_limit({limit})"), + clear_cache=lambda: calls.append("clear_cache"), + ) + if with_metal: + fake.metal = metal + return fake + + +def _install_fake_mlx_core(monkeypatch, fake_core: SimpleNamespace) -> None: + """Make ``import mlx.core as mx`` bind to the fake without real Metal. + + ``import a.b as x`` resolves ``b`` as an attribute of package ``a``, so + the fake package must expose ``core`` — a bare sys.modules entry is not + enough. + """ + monkeypatch.setitem(sys.modules, "mlx", SimpleNamespace(core=fake_core)) + monkeypatch.setitem(sys.modules, "mlx.core", fake_core) + + +def test_release_metal_memory_unwires_before_clearing(monkeypatch): + calls: list[str] = [] + _install_fake_mlx_core(monkeypatch, _fake_mlx_core(calls)) + + inference_worker._release_metal_memory("test") + + # Unwiring is the load-bearing call — the cache flush alone leaves the + # wired model weights stranded when os._exit skips every cleanup handler. + assert calls == [ + "set_wired_limit(0)", + "clear_cache", + "metal.clear_cache", + ] + + +def test_release_metal_memory_tolerates_a_missing_metal_module(monkeypatch): + calls: list[str] = [] + _install_fake_mlx_core(monkeypatch, _fake_mlx_core(calls, with_metal=False)) + + inference_worker._release_metal_memory("test") + + assert calls == ["set_wired_limit(0)", "clear_cache"] + + +def test_release_metal_memory_survives_failures(monkeypatch): + def fail(*_args): + raise RuntimeError("wedged") + + fake = SimpleNamespace( + set_wired_limit=fail, + clear_cache=fail, + metal=SimpleNamespace(clear_cache=fail), + ) + _install_fake_mlx_core(monkeypatch, fake) + + # Must not raise: the force-exit behind this hook has to happen regardless. + inference_worker._release_metal_memory("test") + + +def test_release_metal_memory_without_mlx_is_a_noop(monkeypatch): + monkeypatch.setitem(sys.modules, "mlx", None) + monkeypatch.setitem(sys.modules, "mlx.core", None) + + inference_worker._release_metal_memory("test") + + +def test_sigterm_handler_releases_metal_before_interrupt(monkeypatch): + releases: list[str] = [] + monkeypatch.setattr(inference_worker, "_release_metal_memory", releases.append) + previous_term = signal.getsignal(signal.SIGTERM) + previous_int = signal.getsignal(signal.SIGINT) + previous_alrm = signal.getsignal(signal.SIGALRM) + try: + inference_worker._install_signal_handlers() + handler = signal.getsignal(signal.SIGTERM) + with pytest.raises(KeyboardInterrupt): + handler(signal.SIGTERM, None) + finally: + signal.alarm(0) + signal.signal(signal.SIGTERM, previous_term) + signal.signal(signal.SIGINT, previous_int) + signal.signal(signal.SIGALRM, previous_alrm) + + # The rank releases its own wired memory on SIGTERM, while it still can — + # the coordinator's SIGKILL escalation behind it cannot unwire anything. + assert len(releases) == 1 + assert "SIGTERM" in releases[0] + + +def test_peer_watchdog_on_lost_releases_metal_before_exit(monkeypatch, tmp_path): + captured: dict[str, Any] = {} + + class FakePeerWatchdog: + def __init__(self, _hosts, **kwargs): + captured.update(kwargs) + + def run(self): + pass + + monkeypatch.setattr(inference_worker, "PeerWatchdog", FakePeerWatchdog) + monkeypatch.setattr(inference_worker, "_emit_event", lambda _event: None) + order: list[str] = [] + monkeypatch.setattr( + inference_worker, + "_release_metal_memory", + lambda _reason: order.append("release"), + ) + monkeypatch.setattr(os, "_exit", lambda code: order.append(f"exit:{code}")) + assignments = [ + PipelineAssignment( + node_id=node, + rank=rank, + start_layer=0, + end_layer=1, + layer_weight_bytes=10, + fixed_weight_bytes=10, + reserve_bytes=10, + capacity_bytes=100, + ) + for rank, node in enumerate(("local", "studio")) + ] + marker = SimpleNamespace( + update=lambda phase, **extra: None, + payload={"deployment_id": "dep-9", "plan_hash": "e" * 64}, + ) + + watchdog = inference_worker._start_peer_watchdog( + marker, + assignments, + ["127.0.0.1", "user@studio.local"], + "dep-9", + str(tmp_path), + rank=0, + ) + + assert isinstance(watchdog, FakePeerWatchdog) + captured["on_lost"]("peer vanished") + assert order == ["release", "exit:1"] + + class _ThinkTokenizer: think_end_id = 55 think_start_id = 54 diff --git a/tests/test_cluster_jaccl_lease.py b/tests/test_cluster_jaccl_lease.py new file mode 100644 index 0000000000..5e10959db0 --- /dev/null +++ b/tests/test_cluster_jaccl_lease.py @@ -0,0 +1,47 @@ +# SPDX-License-Identifier: Apache-2.0 + +import json +import os + +import pytest + +from omlx.cluster.jaccl_lease import ( + JacclCommunicatorBusyError, + acquire_jaccl_communicator_lease, +) + + +def test_jaccl_lease_is_exclusive_and_recoverable(tmp_path): + first = acquire_jaccl_communicator_lease( + deployment_id="first", + state_dir=tmp_path, + ) + try: + with pytest.raises(JacclCommunicatorBusyError, match="deployment first"): + acquire_jaccl_communicator_lease( + deployment_id="second", + state_dir=tmp_path, + ) + finally: + first.close() + + second = acquire_jaccl_communicator_lease( + deployment_id="second", + state_dir=tmp_path, + ) + second.close() + + +def test_jaccl_lease_writes_bounded_private_diagnostics(tmp_path): + lease = acquire_jaccl_communicator_lease( + deployment_id="diagnostic", + state_dir=tmp_path, + ) + try: + payload = json.loads(lease.path.read_text()) + assert payload["deployment_id"] == "diagnostic" + assert payload["pid"] == os.getpid() + assert lease.path.stat().st_mode & 0o777 == 0o600 + assert lease.path.stat().st_size < 4096 + finally: + lease.close() diff --git a/tests/test_cluster_launch.py b/tests/test_cluster_launch.py index 95d994bfaf..c9ea8fffc9 100644 --- a/tests/test_cluster_launch.py +++ b/tests/test_cluster_launch.py @@ -22,6 +22,7 @@ _install_cluster_ssh_wrapper, _local_probe_versions, _local_runtime_versions, + _set_serve_release, build_mlx_launch_argv, discover_remote_python_executable, discover_remote_system_python, @@ -52,6 +53,75 @@ def _deployment(model: str = "org/model") -> ClusterDeployment: ) +def test_stop_deployment_processes_sweeps_even_without_a_live_supervisor( + tmp_path, monkeypatch +): + deployment = _deployment() + calls = [] + + def sweep(deployment_id, hosts, **kwargs): + calls.append((deployment_id, hosts, kwargs)) + return [] + + monkeypatch.setattr(launch, "_sweep_rank_processes", sweep) + + report = launch.stop_deployment_processes(deployment, state_dir=tmp_path) + + assert report == { + "verified": True, + "deployment_id": deployment.deployment_id, + "ranks_checked": 2, + "manifest_retired": False, + } + assert calls[0][0] == deployment.deployment_id + assert calls[0][1] == [ + {"rank": 0, "node_id": "local", "ssh": "127.0.0.1"}, + {"rank": 1, "node_id": "studio", "ssh": "user@studio.local"}, + ] + assert calls[0][2]["plan_hash"] == deployment.plan_hash + + +def test_stop_deployment_processes_refuses_unverified_rank_exit(tmp_path, monkeypatch): + deployment = _deployment() + monkeypatch.setattr( + launch, + "_sweep_rank_processes", + lambda *_args, **_kwargs: ["rank 1 is still resident"], + ) + + with pytest.raises(launch.DistributedTeardownError, match="still resident"): + launch.stop_deployment_processes(deployment, state_dir=tmp_path) + + +def test_serve_release_is_atomic_and_mirrored_to_remote(tmp_path): + calls = [] + + def runner(argv, **kwargs): + calls.append((argv, kwargs)) + return subprocess.CompletedProcess(argv, 0, stdout="", stderr="") + + deployment = _deployment() + payload = { + "schema_version": 1, + "deployment_id": deployment.deployment_id, + "plan_hash": deployment.plan_hash, + "world_size": deployment.world_size, + } + + _set_serve_release(deployment, tmp_path, payload, runner=runner) + + marker = tmp_path / f"{deployment.deployment_id}-serve.json" + assert json.loads(marker.read_text()) == payload + assert stat.S_IMODE(marker.stat().st_mode) == 0o600 + assert len(calls) == 1 + assert "user@studio.local" in calls[0][0] + + _set_serve_release(deployment, tmp_path, None, runner=runner) + + assert not marker.exists() + assert len(calls) == 2 + + def test_launcher_argv_keeps_model_as_one_argument(tmp_path): model = "org/model with spaces;$(touch nope)" deployment = _deployment(model) @@ -64,6 +134,10 @@ def test_launcher_argv_keeps_model_as_one_argument(tmp_path): collective_port=32120, python_executable="/opt/omlx/bin/python", cwd=Path("/opt/omlx"), + control_host="10.0.0.1", + control_port=32140, + control_token="e" * 64, + load_timeout=2400.0, ) assert argv[0] == "/opt/omlx/bin/python" @@ -71,6 +145,11 @@ def test_launcher_argv_keeps_model_as_one_argument(tmp_path): assert argv[argv.index("--backend") + 1] == "ring" assert argv[argv.index("--starting-port") + 1] == "32120" assert argv[argv.index("--port") + 1] == "32100" + assert argv[argv.index("--load-timeout") + 1] == "2400.0" + assert argv[argv.index("--control-host") + 1] == "10.0.0.1" + assert argv[argv.index("--control-port") + 1] == "32140" + assert argv[argv.index("--control-token") + 1] == "e" * 64 + assert argv[argv.index("--control-token") + 1] != deployment.plan_hash assert argv[argv.index("--plan-hash") + 1] == deployment.plan_hash assert argv[argv.index("--connections-per-ip") + 1] == "2" assert argv[argv.index("--execution-profile") + 1] == "balanced" @@ -91,6 +170,25 @@ def test_launcher_rejects_overlapping_api_and_collective_ports(tmp_path): ) +def test_launcher_requires_an_explicit_random_control_token(tmp_path): + kwargs = { + "hostfile": (tmp_path / "hosts.json").resolve(), + "api_port": 32100, + "collective_port": 32120, + "python_executable": "/opt/omlx/bin/python", + "control_host": "10.0.0.1", + "control_port": 32140, + } + with pytest.raises(ValueError, match="host, port, and token"): + build_mlx_launch_argv(_deployment(), **kwargs) + with pytest.raises(ValueError, match="64 ASCII bytes"): + build_mlx_launch_argv( + _deployment(), + **kwargs, + control_token="public-plan-hash-is-not-a-secret", + ) + + def test_cuda_fabric_probe_launches_a_real_two_rank_nccl_job(): captured = {} @@ -180,7 +278,7 @@ def test_launcher_selects_the_probed_python_path_for_each_rank(tmp_path): worker = argv[argv.index("--") + 1 :] assert worker[:2] == ["/bin/sh", "-c"] - assert '${MLX_RANK:-}' in worker[2] + assert "${MLX_RANK:-}" in worker[2] assert "/Applications/oMLX/python" in worker[2] assert "/opt/omlx/bin/python" in worker[2] assert worker[3:6] == [ @@ -312,6 +410,13 @@ def wait(self, timeout): "killpg", lambda pgid, sig: signals.append((pgid, sig)), ) + # The marker-pid sweep has its own tests below; here it would attempt + # real SSH to the fake "studio" host. + monkeypatch.setattr( + launch.DistributedJobSupervisor, + "_sweep_rank_leftovers", + lambda self, **_kw: [], + ) supervisor.stop() @@ -352,6 +457,11 @@ def poll(self): "killpg", lambda pgid, sig: signals.append((pgid, sig)), ) + monkeypatch.setattr( + launch.DistributedJobSupervisor, + "_sweep_rank_leftovers", + lambda self, **_kw: [], + ) supervisor.stop() @@ -359,6 +469,44 @@ def poll(self): assert supervisor.process is None +def test_supervisor_stop_handles_reused_group_permission_error(monkeypatch): + class Launcher: + pid = 43212 + stdout = None + stderr = None + returncode = 0 + + def poll(self): + return self.returncode + + supervisor = launch.DistributedJobSupervisor( + _deployment(), + preflight=False, + stop_timeout=0.1, + ) + supervisor.process = Launcher() + swept = [] + monkeypatch.setattr(launch, "_process_group_alive", lambda _pgid: True) + monkeypatch.setattr( + launch.os, + "killpg", + lambda _pgid, _sig: (_ for _ in ()).throw( + PermissionError("Operation not permitted") + ), + ) + monkeypatch.setattr( + launch.DistributedJobSupervisor, + "_sweep_rank_leftovers", + lambda self, **kwargs: swept.append(kwargs) or [], + ) + + supervisor.stop() + + assert swept == [{"process_group": None}] + assert supervisor.process is None + assert supervisor.status().phase == "stopped" + + def test_remote_preflight_uses_prompt_free_noninteractive_ssh(): calls = [] versions = _local_runtime_versions() @@ -729,9 +877,7 @@ def runner(argv, **_kwargs): assert result["runtime_compatible"] is True assert commands[-1].startswith("/opt/omlx/bin/python") - assert result["status"]["runtime"]["python_executable"] == ( - "/opt/omlx/bin/python" - ) + assert result["status"]["runtime"]["python_executable"] == ("/opt/omlx/bin/python") def test_peer_probe_preserves_packaged_cluster_wrapper_path(): @@ -751,9 +897,10 @@ def test_peer_probe_preserves_packaged_cluster_wrapper_path(): def runner(argv, **_kwargs): command = argv[-1] - if command.startswith( - "~/.omlx/bin/omlx-cluster-python" - ) and "import os,omlx" in command: + if ( + command.startswith("~/.omlx/bin/omlx-cluster-python") + and "import os,omlx" in command + ): return subprocess.CompletedProcess( argv, 0, @@ -824,8 +971,7 @@ def runner(argv, **_kwargs): assert discovered == "/Users/test/.omlx/bin/omlx-source-python" assert any( - command.startswith("~/.omlx/bin/omlx-source-python") - for command in commands + command.startswith("~/.omlx/bin/omlx-source-python") for command in commands ) @@ -1201,9 +1347,7 @@ def test_preinstall_inventory_will_not_claim_missing_when_omlx_is_installed(): assert result["bootstrap_required"] is True assert result["runtime_compatible"] is False - assert result["runtime_mismatches"] == [ - "oMLX worker runtime could not be verified" - ] + assert result["runtime_mismatches"] == ["oMLX worker runtime could not be verified"] assert result["worker_runtime_evidence"] == ["/Applications/oMLX.app"] assert result["status"]["warnings"] == [ "oMLX is installed on this node but its worker runtime could not be run." @@ -1352,8 +1496,8 @@ def test_prompt_cache_ssd_reaches_the_rank_and_scopes_its_directory(tmp_path): rank0 = _prompt_cache_ssd_dir(args, rank=0) rank1 = _prompt_cache_ssd_dir(args, rank=1) assert rank0 is not None and rank1 is not None - assert rank0.endswith(f"{args.deployment_id}-rank-0") - assert rank1.endswith(f"{args.deployment_id}-rank-1") + assert rank0.endswith(f"{args.deployment_id}/{args.plan_hash}/rank-0") + assert rank1.endswith(f"{args.deployment_id}/{args.plan_hash}/rank-1") assert rank0 != rank1 @@ -1621,7 +1765,9 @@ def fake_ssh(ssh_target, command, **kwargs): assert result.returncode == 0, result.stderr victim.wait(timeout=2.0) assert victim.poll() is not None - assert marker_file.exists() # kept as crash evidence for _runtime_failure_reason + assert ( + marker_file.exists() + ) # kept as crash evidence for _runtime_failure_reason finally: if victim.poll() is None: victim.kill() @@ -1687,7 +1833,9 @@ def fake_ssh(ssh_target, command, **kwargs): assert result.returncode == 0, result.stderr victim.wait(timeout=5.0) assert victim.poll() is not None - assert marker_file.exists() # kept as crash evidence for _runtime_failure_reason + assert ( + marker_file.exists() + ) # kept as crash evidence for _runtime_failure_reason finally: if victim.poll() is None: victim.kill() @@ -1809,3 +1957,425 @@ def fake_ssh(ssh_target, command, **kwargs): finally: victim.kill() victim.wait() + + +def _fake_launcher(pid: int = 43210): + class Launcher: + stdout = None + stderr = None + + def __init__(self): + self.pid = pid + self.returncode = None + + def poll(self): + return self.returncode + + def wait(self, timeout): + self.returncode = 0 + return 0 + + return Launcher() + + +def _rank_marker(pid: int, rank: int, *, phase: str = "ready") -> dict: + return { + "schema_version": 1, + "deployment_id": "cluster-test", + "model": "org/model", + "backend": "ring", + "plan_hash": "c" * 64, + "phase": phase, + "updated_at": "2026-08-17T00:00:00+00:00", + "pid": pid, + "rank": rank, + "world_size": 2, + } + + +def test_supervisor_stop_retries_sigkill_once_then_succeeds(tmp_path, monkeypatch): + supervisor = launch.DistributedJobSupervisor( + _deployment(), + preflight=False, + stop_timeout=0.1, + state_dir=str(tmp_path), + ) + launcher = _fake_launcher() + supervisor.process = launcher + signals = [] + swept = [] + waits = iter((False, False, True)) + + monkeypatch.setattr(launch, "_process_group_alive", lambda _pgid: True) + monkeypatch.setattr( + launch, + "_wait_for_process_group_exit", + lambda _pgid, _timeout: next(waits), + ) + monkeypatch.setattr( + launch.os, + "killpg", + lambda pgid, sig: signals.append((pgid, sig)), + ) + monkeypatch.setattr( + supervisor, + "_sweep_rank_leftovers", + lambda **_kw: swept.append(True) or [], + ) + + supervisor.stop() + + assert signals == [ + (launcher.pid, signal.SIGTERM), + (launcher.pid, signal.SIGKILL), + (launcher.pid, signal.SIGKILL), + ] + assert swept == [True] + assert supervisor.process is None + assert supervisor.status().phase == "stopped" + + +def test_supervisor_stop_raises_and_keeps_state_when_group_survives( + tmp_path, monkeypatch +): + supervisor = launch.DistributedJobSupervisor( + _deployment(), + preflight=False, + stop_timeout=0.1, + state_dir=str(tmp_path), + ) + launcher = _fake_launcher() + supervisor.process = launcher + supervisor._phase = "ready" + supervisor._write_launch_manifest() + signals = [] + monkeypatch.setattr(launch, "_process_group_alive", lambda _pgid: True) + monkeypatch.setattr( + launch, + "_wait_for_process_group_exit", + lambda _pgid, _timeout: False, + ) + monkeypatch.setattr( + launch.os, + "killpg", + lambda pgid, sig: signals.append((pgid, sig)), + ) + monkeypatch.setattr(supervisor, "_sweep_rank_leftovers", lambda **_kw: []) + + with pytest.raises(launch.DistributedTeardownError) as excinfo: + supervisor.stop() + + assert "could not be verified" in str(excinfo.value) + assert signals == [ + (launcher.pid, signal.SIGTERM), + (launcher.pid, signal.SIGKILL), + (launcher.pid, signal.SIGKILL), + ] + # State is kept so a later stop() retries instead of dropping the job. + assert supervisor.process is launcher + assert supervisor.status().phase == "failed" + assert launch._launch_manifest_path(tmp_path, "cluster-test").exists() + + +def test_supervisor_stop_raises_on_unkillable_leftover_rank(tmp_path, monkeypatch): + supervisor = launch.DistributedJobSupervisor( + _deployment(), + preflight=False, + stop_timeout=0.1, + state_dir=str(tmp_path), + ) + launcher = _fake_launcher() + supervisor.process = launcher + monkeypatch.setattr(launch, "_process_group_alive", lambda _pgid: True) + monkeypatch.setattr( + launch, + "_wait_for_process_group_exit", + lambda _pgid, _timeout: True, + ) + monkeypatch.setattr(launch.os, "killpg", lambda _pgid, _sig: None) + monkeypatch.setattr( + supervisor, + "_sweep_rank_leftovers", + lambda **_kw: ["rank 0 (local) pid 424242 survived SIGKILL"], + ) + + with pytest.raises(launch.DistributedTeardownError) as excinfo: + supervisor.stop() + + assert "rank 0 (local) pid 424242 survived SIGKILL" in str(excinfo.value) + assert supervisor.process is launcher + + +def test_verified_stop_writes_then_removes_launch_manifest(tmp_path, monkeypatch): + supervisor = launch.DistributedJobSupervisor( + _deployment(), + preflight=False, + stop_timeout=0.1, + state_dir=str(tmp_path), + ) + launcher = _fake_launcher() + supervisor.process = launcher + supervisor.port = 18081 + supervisor._write_launch_manifest() + manifest_path = launch._launch_manifest_path(tmp_path, "cluster-test") + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + assert manifest["deployment_id"] == "cluster-test" + assert manifest["plan_hash"] == "c" * 64 + assert manifest["launcher_pid"] == launcher.pid + assert manifest["process_group"] == launcher.pid + assert manifest["coordinator_pid"] > 0 + assert manifest["api_port"] == 18081 + assert [host["rank"] for host in manifest["hosts"]] == [0, 1] + + monkeypatch.setattr(launch, "_process_group_alive", lambda _pgid: True) + monkeypatch.setattr( + launch, + "_wait_for_process_group_exit", + lambda _pgid, _timeout: True, + ) + monkeypatch.setattr(launch.os, "killpg", lambda _pgid, _sig: None) + monkeypatch.setattr(supervisor, "_sweep_rank_leftovers", lambda **_kw: []) + + supervisor.stop() + + assert not manifest_path.exists() + assert supervisor.status().phase == "stopped" + + +def test_teardown_sweep_kills_leftover_local_rank_by_marker_pid(tmp_path, monkeypatch): + supervisor = launch.DistributedJobSupervisor( + _deployment(), + preflight=False, + state_dir=str(tmp_path), + ) + marker_path = tmp_path / "cluster-test-rank-0.json" + marker_path.write_text(json.dumps(_rank_marker(424242, 0)), encoding="utf-8") + kills = [] + + def fake_kill(pid, sig): + # os.kill(pid, 0) liveness probes (also patched) are not kills. + if sig != 0: + kills.append((pid, sig)) + + monkeypatch.setattr(launch.os, "kill", fake_kill) + process = launch._LocalProcessState( + 424242, + 1, + 424242, + "S", + 1024, + "python -m omlx.cluster.inference_worker --deployment-id cluster-test", + ) + monkeypatch.setattr( + launch, + "_read_local_process_table", + lambda: ( + ((), "") + if any(sig == signal.SIGKILL for _, sig in kills) + else ((process,), "") + ), + ) + # The pid stays "alive" until the SIGKILL lands. + monkeypatch.setattr( + launch, + "_pid_alive", + lambda _pid: not any(sig == signal.SIGKILL for _, sig in kills), + ) + monkeypatch.setattr(launch, "marker_owner_is_live", lambda _marker: True) + monkeypatch.setattr( + launch, + "read_remote_marker", + lambda *_a, **_k: (None, None, None, ""), + ) + + failures = supervisor._sweep_rank_leftovers(kill_grace=0.01) + + assert failures == [] + assert kills == [ + (424242, signal.SIGTERM), + (424242, signal.SIGKILL), + ] + + +def test_teardown_sweep_reports_an_unkillable_rank(tmp_path, monkeypatch): + supervisor = launch.DistributedJobSupervisor( + _deployment(), + preflight=False, + state_dir=str(tmp_path), + ) + marker_path = tmp_path / "cluster-test-rank-0.json" + marker_path.write_text(json.dumps(_rank_marker(424242, 0)), encoding="utf-8") + monkeypatch.setattr(launch.os, "kill", lambda _pid, _sig: None) + process = launch._LocalProcessState( + 424242, + 1, + 424242, + "D", + 1024, + "python -m omlx.cluster.inference_worker --deployment-id cluster-test", + ) + monkeypatch.setattr( + launch, + "_read_local_process_table", + lambda: ((process,), ""), + ) + monkeypatch.setattr(launch, "_pid_alive", lambda _pid: True) + monkeypatch.setattr(launch, "marker_owner_is_live", lambda _marker: True) + monkeypatch.setattr( + launch, + "read_remote_marker", + lambda *_a, **_k: (None, None, None, ""), + ) + + failures = supervisor._sweep_rank_leftovers(kill_grace=0.01) + + assert any( + "pid 424242" in failure and "survived SIGKILL" in failure + for failure in failures + ) + assert any("Reboot this Mac" in failure for failure in failures) + + +def test_teardown_sweep_kills_live_remote_rank_over_ssh(tmp_path, monkeypatch): + supervisor = launch.DistributedJobSupervisor( + _deployment(), + preflight=False, + state_dir=str(tmp_path), + ) + commands = [] + + class Result: + stdout = "gone\n" + + monkeypatch.setattr( + launch, + "read_remote_marker", + lambda *_a, **_k: (_rank_marker(535353, 1), True, 0.0, ""), + ) + monkeypatch.setattr( + launch, + "_run_cluster_ssh", + lambda target, command, **kw: commands.append((target, command)) or Result(), + ) + + failures = supervisor._sweep_rank_leftovers(kill_grace=0.01) + + assert failures == [] + assert len(commands) == 1 + target, command = commands[0] + assert target == "user@studio.local" + assert "kill -TERM 535353" in command + assert "kill -KILL 535353" in command + + +def test_teardown_sweep_ignores_foreign_deployment_markers(tmp_path, monkeypatch): + supervisor = launch.DistributedJobSupervisor( + _deployment(), + preflight=False, + state_dir=str(tmp_path), + ) + foreign = _rank_marker(424242, 0) | {"deployment_id": "other-deployment"} + (tmp_path / "other-deployment-rank-0.json").write_text( + json.dumps(foreign), encoding="utf-8" + ) + kills = [] + monkeypatch.setattr( + launch.os, + "kill", + # os.kill(pid, 0) liveness probes (also patched) are not kills. + lambda pid, sig: kills.append((pid, sig)) if sig != 0 else None, + ) + monkeypatch.setattr(launch, "_pid_alive", lambda _pid: True) + monkeypatch.setattr(launch, "marker_owner_is_live", lambda _marker: True) + monkeypatch.setattr( + launch, + "read_remote_marker", + lambda *_a, **_k: (None, None, None, ""), + ) + + assert supervisor._sweep_rank_leftovers(kill_grace=0.01) == [] + assert kills == [] + + +def test_reap_orphaned_launches_reaps_ranks_of_a_dead_coordinator( + tmp_path, monkeypatch +): + deployment = _deployment() + launch._write_launch_manifest( + tmp_path, deployment, launcher_pid=433000, api_port=18081 + ) + marker_path = tmp_path / "cluster-test-rank-0.json" + marker_path.write_text(json.dumps(_rank_marker(424243, 0)), encoding="utf-8") + kills = [] + + def fake_kill(pid, sig): + # os.kill(pid, 0) liveness probes (also patched) are not kills. + if sig != 0: + kills.append((pid, sig)) + + coordinator_pid = json.loads( + launch._launch_manifest_path(tmp_path, "cluster-test").read_text( + encoding="utf-8" + ) + )["coordinator_pid"] + monkeypatch.setattr(launch.os, "kill", fake_kill) + process = launch._LocalProcessState( + 424243, + 1, + 424243, + "S", + 1024, + "python -m omlx.cluster.inference_worker --deployment-id cluster-test", + ) + monkeypatch.setattr( + launch, + "_read_local_process_table", + lambda: ( + ((), "") + if any(sig == signal.SIGKILL for _, sig in kills) + else ((process,), "") + ), + ) + # The crashed coordinator and its launcher are gone; the rank pid lives. + monkeypatch.setattr( + launch, + "_pid_alive", + lambda pid: ( + pid not in (coordinator_pid, 433000) + and not any(sig == signal.SIGKILL for _, sig in kills) + ), + ) + monkeypatch.setattr(launch, "_process_group_alive", lambda _pgid: False) + monkeypatch.setattr(launch, "marker_owner_is_live", lambda _marker: True) + monkeypatch.setattr( + launch, + "read_remote_marker", + lambda *_a, **_k: (None, None, None, ""), + ) + + report = launch.reap_orphaned_launches(tmp_path, kill_grace=0.01) + + assert report["reaped"] == ["cluster-test"] + assert report["failures"] == [] + assert kills == [ + (424243, signal.SIGTERM), + (424243, signal.SIGKILL), + ] + assert not launch._launch_manifest_path(tmp_path, "cluster-test").exists() + + +def test_reap_orphaned_launches_leaves_an_active_job_alone(tmp_path, monkeypatch): + launch._write_launch_manifest( + tmp_path, _deployment(), launcher_pid=433000, api_port=18081 + ) + kills = [] + monkeypatch.setattr(launch.os, "kill", lambda pid, sig: kills.append((pid, sig))) + monkeypatch.setattr(launch, "_pid_alive", lambda _pid: True) + monkeypatch.setattr(launch, "_process_group_alive", lambda _pgid: True) + + report = launch.reap_orphaned_launches(tmp_path, kill_grace=0.01) + + assert report["active"] == ["cluster-test"] + assert report["reaped"] == [] + assert kills == [] + assert launch._launch_manifest_path(tmp_path, "cluster-test").exists() diff --git a/tests/test_cluster_liveness.py b/tests/test_cluster_liveness.py index 893256a934..4cdad100b8 100644 --- a/tests/test_cluster_liveness.py +++ b/tests/test_cluster_liveness.py @@ -67,8 +67,12 @@ def explode(*args, **kwargs): def test_an_unreachable_peer_is_reported_not_raised(tmp_path): - health = check_peers(HOSTS, state_dir=str(tmp_path), deployment_id="d", - probe=lambda t: t == "127.0.0.1") + health = check_peers( + HOSTS, + state_dir=str(tmp_path), + deployment_id="d", + probe=lambda t: t == "127.0.0.1", + ) by_rank = {h.rank: h for h in health} assert by_rank[0].reachable is True @@ -80,8 +84,12 @@ def test_an_unreachable_peer_is_reported_not_raised(tmp_path): def test_a_pulled_cable_produces_an_actionable_message(tmp_path): """The exact failure that needed pkill: peer gone mid-generation.""" - health = check_peers(HOSTS, state_dir=str(tmp_path), deployment_id="d", - probe=lambda t: t == "127.0.0.1") + health = check_peers( + HOSTS, + state_dir=str(tmp_path), + deployment_id="d", + probe=lambda t: t == "127.0.0.1", + ) message = describe_failure(health) assert "mac-studio" in message @@ -91,15 +99,22 @@ def test_a_pulled_cable_produces_an_actionable_message(tmp_path): raise_if_peer_lost(health) -def test_a_rank_that_stopped_reporting_is_distinguished_from_one_that_vanished(tmp_path): +def test_a_rank_that_stopped_reporting_is_distinguished_from_one_that_vanished( + tmp_path, +): """Reachable but silent means crashed or stuck — a different remedy.""" _marker(tmp_path, "d", 0, age_seconds=0) _marker(tmp_path, "d", 1, age_seconds=300) - health = check_peers(HOSTS, state_dir=str(tmp_path), deployment_id="d", - probe=lambda t: True, require_heartbeat=True, - remote_reader=_remote_reader(tmp_path)) + health = check_peers( + HOSTS, + state_dir=str(tmp_path), + deployment_id="d", + probe=lambda t: True, + require_heartbeat=True, + remote_reader=_remote_reader(tmp_path), + ) by_rank = {h.rank: h for h in health} assert by_rank[1].reachable is True @@ -115,9 +130,14 @@ def test_a_busy_rank_is_not_mistaken_for_a_dead_one(tmp_path): _marker(tmp_path, "d", 0, age_seconds=0) _marker(tmp_path, "d", 1, age_seconds=20) - health = check_peers(HOSTS, state_dir=str(tmp_path), deployment_id="d", - probe=lambda t: True, require_heartbeat=True, - remote_reader=_remote_reader(tmp_path)) + health = check_peers( + HOSTS, + state_dir=str(tmp_path), + deployment_id="d", + probe=lambda t: True, + require_heartbeat=True, + remote_reader=_remote_reader(tmp_path), + ) assert all(h.healthy for h in health) assert describe_failure(health) == "All ranks are responding." raise_if_peer_lost(health) # must not raise @@ -126,8 +146,9 @@ def test_a_busy_rank_is_not_mistaken_for_a_dead_one(tmp_path): def test_a_remote_rank_without_a_local_marker_is_not_called_stale(tmp_path): """Markers are local files; a peer's marker lives on the peer.""" - health = check_peers(HOSTS, state_dir=str(tmp_path), deployment_id="d", - probe=lambda t: True) + health = check_peers( + HOSTS, state_dir=str(tmp_path), deployment_id="d", probe=lambda t: True + ) remote = next(h for h in health if h.rank == 1) assert remote.seconds_since_heartbeat is None assert remote.stale is False @@ -157,10 +178,14 @@ def test_clock_skew_between_macs_does_not_kill_a_healthy_cluster(tmp_path): _marker(tmp_path, "d", 0, age_seconds=0) _marker(tmp_path, "d", 1, age_seconds=605) - health = check_peers(HOSTS, state_dir=str(tmp_path), deployment_id="d", - probe=lambda t: True, require_heartbeat=True, - remote_reader=_remote_reader( - tmp_path, peer_clock_offset=-600.0)) + health = check_peers( + HOSTS, + state_dir=str(tmp_path), + deployment_id="d", + probe=lambda t: True, + require_heartbeat=True, + remote_reader=_remote_reader(tmp_path, peer_clock_offset=-600.0), + ) remote = next(h for h in health if h.rank == 1) assert remote.seconds_since_heartbeat == pytest.approx(5.0, abs=2.0) @@ -174,10 +199,14 @@ def test_a_rank_that_is_stale_by_its_own_clock_is_still_caught(tmp_path): _marker(tmp_path, "d", 0, age_seconds=0) _marker(tmp_path, "d", 1, age_seconds=905) - health = check_peers(HOSTS, state_dir=str(tmp_path), deployment_id="d", - probe=lambda t: True, require_heartbeat=True, - remote_reader=_remote_reader( - tmp_path, peer_clock_offset=-600.0)) + health = check_peers( + HOSTS, + state_dir=str(tmp_path), + deployment_id="d", + probe=lambda t: True, + require_heartbeat=True, + remote_reader=_remote_reader(tmp_path, peer_clock_offset=-600.0), + ) remote = next(h for h in health if h.rank == 1) assert remote.stale is True @@ -203,9 +232,10 @@ def test_the_injected_marker_script_reports_the_peer_clock(tmp_path): payload = json.loads(result.stdout) assert payload["marker"]["rank"] == 0 assert payload["process_live"] is True # the marker carries this test's pid - age = payload["peer_now"] - datetime.fromisoformat( - payload["marker"]["updated_at"] - ).timestamp() + age = ( + payload["peer_now"] + - datetime.fromisoformat(payload["marker"]["updated_at"]).timestamp() + ) assert 2.0 <= age <= 8.0 @@ -215,8 +245,11 @@ def test_a_marker_response_without_the_peer_clock_is_rejected(tmp_path): from omlx.cluster.liveness import read_remote_marker fake = subprocess.CompletedProcess( - args=[], returncode=0, - stdout=b'{"marker":{"rank":1},"process_live":true}', stderr=b"") + args=[], + returncode=0, + stdout=b'{"marker":{"rank":1},"process_live":true}', + stderr=b"", + ) marker, live, peer_now, error = read_remote_marker( "studio.local", "/tmp/x.json", runner=lambda *a, **k: fake @@ -232,8 +265,13 @@ def test_the_watchdog_reports_once_and_stops(tmp_path): """It ends the wait; it does not thrash trying to repair a collective.""" losses = [] - watchdog = PeerWatchdog(HOSTS, deployment_id="d", state_dir=str(tmp_path), - interval=0.0, on_lost=losses.append) + watchdog = PeerWatchdog( + HOSTS, + deployment_id="d", + state_dir=str(tmp_path), + interval=0.0, + on_lost=losses.append, + ) watchdog.run_once = lambda: ( # type: ignore[method-assign] PeerHealth("test-mbp", 0, True, 0.0), PeerHealth("mac-studio", 1, False, None, detail="gone"), @@ -253,8 +291,13 @@ def fake_sleep(_seconds): def test_a_healthy_cluster_keeps_the_watchdog_quiet(tmp_path): losses = [] - watchdog = PeerWatchdog(HOSTS, deployment_id="d", state_dir=str(tmp_path), - interval=0.0, on_lost=losses.append) + watchdog = PeerWatchdog( + HOSTS, + deployment_id="d", + state_dir=str(tmp_path), + interval=0.0, + on_lost=losses.append, + ) watchdog.run_once = lambda: ( # type: ignore[method-assign] PeerHealth("test-mbp", 0, True, 1.0), PeerHealth("mac-studio", 1, True, 2.0), @@ -286,8 +329,13 @@ def test_a_watchdog_with_no_peers_never_fires(tmp_path): """ losses = [] - watchdog = PeerWatchdog({}, deployment_id="d", state_dir=str(tmp_path), - interval=0.0, on_lost=losses.append) + watchdog = PeerWatchdog( + {}, + deployment_id="d", + state_dir=str(tmp_path), + interval=0.0, + on_lost=losses.append, + ) def fake_sleep(_seconds): raise AssertionError("a watchdog with no peers must not even poll") @@ -514,7 +562,12 @@ def test_a_reachable_mac_with_a_dead_worker_is_not_healthy(tmp_path): deployment_id="d", probe=lambda _target: True, require_heartbeat=True, - remote_reader=lambda _target, _path: (marker, False, datetime.now(UTC).timestamp(), ""), + remote_reader=lambda _target, _path: ( + marker, + False, + datetime.now(UTC).timestamp(), + "", + ), ) assert health[0].reachable is True @@ -563,3 +616,114 @@ def test_status_names_each_way_a_rank_can_be_wrong(tmp_path): assert PeerHealth("a", 0, True, 1.0).status == "healthy" assert PeerHealth("a", 0, True, None, heartbeat_required=True).status == "missing" assert PeerHealth("a", 0, True, 1.0, process_live=False).status == "dead" + + +# --------------------------------------------------------------------------- +# Graduated response: warn/abort first, exit last. +# --------------------------------------------------------------------------- + + +def test_the_watchdog_aborts_and_recovers_without_exiting(tmp_path): + losses = [] + aborts = [] + unhealthy = ( + PeerHealth("test-mbp", 0, True, 0.0), + PeerHealth("mac-studio", 1, False, None, detail="gone"), + ) + healthy = ( + PeerHealth("test-mbp", 0, True, 1.0), + PeerHealth("mac-studio", 1, True, 2.0), + ) + state = {"aborted": False} + + def on_abort(reason): + aborts.append(reason) + state["aborted"] = True + + watchdog = PeerWatchdog( + HOSTS, + deployment_id="d", + state_dir=str(tmp_path), + interval=0.0, + on_lost=losses.append, + on_abort=on_abort, + abort_grace=5.0, + ) + watchdog.run_once = lambda: healthy if state["aborted"] else unhealthy # type: ignore[method-assign] + + ticks = [0] + + def fake_sleep(_seconds): + ticks[0] += 1 + if ticks[0] > 10: + watchdog.stop() + + watchdog.run(sleep=fake_sleep) + + # The abort stage fired once at tolerance; the peer recovered during the + # grace window, so the exit stage never ran and the watchdog kept polling. + assert aborts and "mac-studio" in aborts[0] + assert losses == [] + assert watchdog._consecutive_failures == {0: 0, 1: 0} + + +def test_the_watchdog_exits_only_after_the_abort_grace_expires(tmp_path): + losses = [] + aborts = [] + unhealthy = ( + PeerHealth("test-mbp", 0, True, 0.0), + PeerHealth("mac-studio", 1, False, None, detail="gone"), + ) + watchdog = PeerWatchdog( + HOSTS, + deployment_id="d", + state_dir=str(tmp_path), + interval=0.0, + on_lost=losses.append, + on_abort=aborts.append, + abort_grace=0.2, + ) + watchdog.run_once = lambda: unhealthy # type: ignore[method-assign] + + import time as _time + + def fast_sleep(seconds): + _time.sleep(min(seconds, 0.01)) + + started = _time.monotonic() + watchdog.run(sleep=fast_sleep) + elapsed = _time.monotonic() - started + + assert len(aborts) == 1 + assert len(losses) == 1 + assert "mac-studio" in losses[0] + # The exit was delayed by the abort grace, not instant. + assert elapsed >= 0.2 + + +def test_without_an_abort_stage_the_timing_is_unchanged(tmp_path): + losses = [] + watchdog = PeerWatchdog( + HOSTS, + deployment_id="d", + state_dir=str(tmp_path), + interval=0.0, + on_lost=losses.append, + ) + watchdog.run_once = lambda: ( # type: ignore[method-assign] + PeerHealth("test-mbp", 0, True, 0.0), + PeerHealth("mac-studio", 1, False, None, detail="gone"), + ) + + ticks = [0] + + def fake_sleep(_seconds): + ticks[0] += 1 + if ticks[0] > 5: + raise AssertionError("watchdog should have reported immediately") + + watchdog.run(sleep=fake_sleep) + + # Two strikes (the failure tolerance) then the exit stage, no grace. + assert ticks[0] == 2 + assert len(losses) == 1 diff --git a/tests/test_cluster_prompt_snapshot_cache.py b/tests/test_cluster_prompt_snapshot_cache.py index 9bd197bf9e..3fabe015ae 100644 --- a/tests/test_cluster_prompt_snapshot_cache.py +++ b/tests/test_cluster_prompt_snapshot_cache.py @@ -325,6 +325,34 @@ def test_a_new_store_reclaims_what_a_dead_process_left(tmp_path): assert store.put(MODEL, list(range(STEP)), _kv()) # still fully usable +def test_persistent_store_restores_its_chain_after_rank_restart(tmp_path): + tokens = list(range(8)) + first = SSDPromptSnapshotStore(tmp_path, step=4, persistent=True) + kv = KVCache() + for boundary in (4, 8): + _feed(kv, 4) + assert first.put(MODEL, tokens[:boundary], [kv]) + + manifest = tmp_path / "index.json" + assert manifest.is_file() + second = SSDPromptSnapshotStore(tmp_path, step=4, persistent=True) + assert second.present_boundaries(MODEL, tokens) == (8, 4) + restored = second.load(MODEL, tokens, 8) + assert restored is not None + assert mx.array_equal(restored[0].state[0], kv.state[0]) + + +def test_invalid_persistent_manifest_fails_closed(tmp_path): + (tmp_path / "deadbeef.safetensors").write_bytes(b"stale") + (tmp_path / "index.json").write_text('{"version":1,"step":4,"entries":[{}]}') + + store = SSDPromptSnapshotStore(tmp_path, step=4, persistent=True) + + assert len(store) == 0 + assert not (tmp_path / "deadbeef.safetensors").exists() + assert (tmp_path / "index.json").is_file() + + def test_an_unaligned_prompt_is_rejected(tmp_path): store = SSDPromptSnapshotStore(tmp_path, step=STEP) assert store.put(MODEL, list(range(STEP + 1)), _kv()) is False @@ -465,3 +493,15 @@ def _boom(*_a, **_k): assert store.present_boundaries(MODEL, list(range(STEP))) == () # No half-written temp file is left behind. assert list(tmp_path.glob("*")) == [] + + +def test_clear_removes_live_files_without_a_write_behind_flush(tmp_path): + store = SSDPromptSnapshotStore(tmp_path, step=STEP, persistent=True) + assert store.put(MODEL, list(range(STEP)), _kv()) is True + assert len(store) == 1 + + assert store.clear(timeout=0.01) == 1 + + assert len(store) == 0 + assert store.nbytes == 0 + assert list(tmp_path.glob("*.safetensors")) == [] diff --git a/tests/test_cluster_prompt_snapshot_integration.py b/tests/test_cluster_prompt_snapshot_integration.py index fa2c55180b..42f351f843 100644 --- a/tests/test_cluster_prompt_snapshot_integration.py +++ b/tests/test_cluster_prompt_snapshot_integration.py @@ -73,7 +73,7 @@ def test_prefill_boundaries_are_snapshotted_to_ssd(tmp_path, monkeypatch): def test_a_later_miss_restores_the_longest_ssd_prefix(tmp_path, monkeypatch): mlx_server, ctx = _install(tmp_path, monkeypatch) - with ctx: + with ctx as telemetry: cache = mlx_server.LRUPromptCache() first = list(range(8)) cache.prefetch_nearest_cache(MODEL, first) @@ -91,9 +91,15 @@ def test_a_later_miss_restores_the_longest_ssd_prefix(tmp_path, monkeypatch): longer = list(range(12)) fresh = mlx_server.LRUPromptCache() restored, rest = fresh.prefetch_nearest_cache(MODEL, longer) + snapshot = telemetry.snapshot() assert restored is not None assert rest == [8, 9, 10, 11] + assert snapshot["cache"]["lookups"] == 2 + assert snapshot["cache"]["hits"] == 1 + assert snapshot["cache"]["tokens_reused"] == 8 + assert snapshot["cache"]["entries"] == 2 + assert snapshot["cache"]["bytes"] > 0 def test_the_fetch_path_alone_carries_the_ssd_tier(tmp_path, monkeypatch): @@ -224,6 +230,31 @@ def test_teardown_removes_the_snapshot_directory(tmp_path, monkeypatch): assert not tmp_path.exists() +def test_persistent_tier_survives_telemetry_teardown(tmp_path, monkeypatch): + import mlx_lm.server as mlx_server + + monkeypatch.setattr(mlx_server, "stream_generate", _fake_stream_generate) + with install_server_telemetry( + _Marker(), + ssd_cache_dir=str(tmp_path), + ssd_cache_persistent=True, + prefill_step_size=STEP, + ): + tokens = list(range(8)) + mlx_server.LRUPromptCache().fetch_nearest_cache(MODEL, tokens) + list( + mlx_server.stream_generate( + model=None, + prompt=tokens, + prompt_cache=_kv(), + prompt_progress_callback=None, + ) + ) + + assert (tmp_path / "index.json").is_file() + assert sorted(tmp_path.glob("*.safetensors")) + + class _FakeBaseBatchGenerator: """Report prefill progress at each step boundary, like BatchGenerator.""" diff --git a/tests/test_cluster_routes.py b/tests/test_cluster_routes.py index 941dc0d3f8..c96b69cc21 100644 --- a/tests/test_cluster_routes.py +++ b/tests/test_cluster_routes.py @@ -210,6 +210,20 @@ def _install_ready_pool( # established. Do not let their synthetic ``studio.local`` host escape to # the real SSH liveness probe; peer-loss behavior has dedicated coverage. monkeypatch.setattr(routes, "check_peers", lambda *args, **kwargs: ()) + pool.verified_teardowns = [] + monkeypatch.setattr( + routes, + "stop_deployment_processes", + lambda deployment: ( + pool.verified_teardowns.append(deployment.deployment_id) + or { + "verified": True, + "deployment_id": deployment.deployment_id, + "ranks_checked": deployment.world_size, + "manifest_retired": False, + } + ), + ) return pool @@ -522,7 +536,9 @@ def test_cluster_node_budgets_use_each_hosts_live_admission_ceiling(monkeypatch) assert studio["capacity_bytes"] < 223 * gib -def test_cluster_node_budgets_let_the_probe_discover_an_unknown_interpreter(monkeypatch): +def test_cluster_node_budgets_let_the_probe_discover_an_unknown_interpreter( + monkeypatch, +): """#2680: sys.executable is the coordinator's bundled binary, not the peer's.""" gib = 1024**3 @@ -608,9 +624,10 @@ def test_cluster_plan_route_builds_unequal_pipeline(): assert payload["assignments"][0]["layer_count"] == 54 assert payload["assignments"][1]["node_id"] == "mobile" assert payload["assignments"][1]["layer_count"] == 26 - assert [ - item["memory_guard_tier"] for item in payload["assignments"] - ] == ["aggressive", "safe"] + assert [item["memory_guard_tier"] for item in payload["assignments"]] == [ + "aggressive", + "safe", + ] def test_cluster_plan_route_requires_exactly_one_model_source(): @@ -823,28 +840,28 @@ def test_cluster_deployment_recomputes_plan_and_preflights(tmp_path, monkeypatch ) body = { - "deployment_id": "nemotron-pool", - "model_path": str(model_path), - "backend": "jaccl", - "nodes": [ - {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, - {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 10}, - ], - "hosts": [ - { - "node_id": "large", - "ssh": "127.0.0.1", - "ips": ["192.168.5.1"], - "rdma": [None, "rdma_en5"], - }, - { - "node_id": "small", - "ssh": "studio.local", - "ips": ["192.168.5.2"], - "rdma": ["rdma_en5", None], - }, - ], - } + "deployment_id": "nemotron-pool", + "model_path": str(model_path), + "backend": "jaccl", + "nodes": [ + {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, + {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 10}, + ], + "hosts": [ + { + "node_id": "large", + "ssh": "127.0.0.1", + "ips": ["192.168.5.1"], + "rdma": [None, "rdma_en5"], + }, + { + "node_id": "small", + "ssh": "studio.local", + "ips": ["192.168.5.2"], + "rdma": ["rdma_en5", None], + }, + ], + } body["approved_placement"] = _approval_for(body) response = _client().post("/admin/api/cluster/deployments", json=body) @@ -865,16 +882,29 @@ def test_cluster_deployment_recomputes_plan_and_preflights(tmp_path, monkeypatch assert pool.reloads == 1 assert len(payload["preflight"]) == 2 assert payload["performance_probe"]["status"] in {"applied", "placement_locked"} - assert ( - payload["plan"]["placement_signature"] - == body["approved_placement"] - ) + assert payload["plan"]["placement_signature"] == body["approved_placement"] assert payload["deployment"]["execution"]["profile"] == "balanced" listed = _client().get("/admin/api/cluster/deployments") assert listed.status_code == 200 assert listed.json()["deployments"][0]["deployment_id"] == "nemotron-pool" + unloaded = _client().post("/admin/api/cluster/deployments/nemotron-pool/unload") + assert unloaded.status_code == 200, unloaded.json() + assert unloaded.json()["configured"] is True + assert unloaded.json()["stopped"] is True + assert unloaded.json()["teardown"]["verified"] is True + assert pool.verified_teardowns == ["nemotron-pool"] + assert pool.entry.engine is None + assert routes.get_cluster_registry().get("nemotron-pool") is not None + + loaded = _client().post("/admin/api/cluster/deployments/nemotron-pool/load") + assert loaded.status_code == 200, loaded.json() + assert loaded.json()["loaded"] is True + assert loaded.json()["canary_completion_tokens"] == 1 + assert len(loaded.json()["ranks"]) == 2 + assert pool.entry.engine is not None + removed = _client().delete("/admin/api/cluster/deployments/nemotron-pool") assert removed.status_code == 200 @@ -915,26 +945,26 @@ def test_cluster_deployment_keeps_memory_plan_when_benchmark_is_unavailable( ) body = { - "deployment_id": "fallback-pool", - "model_path": str(model_path), - "backend": "ring", - "nodes": [ - {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, - {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 10}, - ], - "hosts": [ - { - "node_id": "large", - "ssh": "127.0.0.1", - "ips": ["10.0.0.1"], - }, - { - "node_id": "small", - "ssh": "studio.local", - "ips": ["10.0.0.2"], - }, - ], - } + "deployment_id": "fallback-pool", + "model_path": str(model_path), + "backend": "ring", + "nodes": [ + {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, + {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 10}, + ], + "hosts": [ + { + "node_id": "large", + "ssh": "127.0.0.1", + "ips": ["10.0.0.1"], + }, + { + "node_id": "small", + "ssh": "studio.local", + "ips": ["10.0.0.2"], + }, + ], + } body["approved_placement"] = _approval_for(body) response = _client().post("/admin/api/cluster/deployments", json=body) @@ -974,27 +1004,27 @@ def test_cluster_activation_rolls_back_when_canary_fails(tmp_path, monkeypatch): ) body = { - "deployment_id": "canary-failure", - "model_path": str(model_path), - "backend": "ring", - "auto_tune": False, - "nodes": [ - {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, - {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 10}, - ], - "hosts": [ - { - "node_id": "large", - "ssh": "127.0.0.1", - "ips": ["10.0.0.1"], - }, - { - "node_id": "small", - "ssh": "studio.local", - "ips": ["10.0.0.2"], - }, - ], - } + "deployment_id": "canary-failure", + "model_path": str(model_path), + "backend": "ring", + "auto_tune": False, + "nodes": [ + {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, + {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 10}, + ], + "hosts": [ + { + "node_id": "large", + "ssh": "127.0.0.1", + "ips": ["10.0.0.1"], + }, + { + "node_id": "small", + "ssh": "studio.local", + "ips": ["10.0.0.2"], + }, + ], + } body["approved_placement"] = _approval_for(body) response = _client().post("/admin/api/cluster/deployments", json=body) @@ -1022,25 +1052,25 @@ def test_cluster_deployment_rejects_unsafe_ssh_target(tmp_path, monkeypatch): ) body = { - "model_path": str(tmp_path / "model"), - "backend": "ring", - "nodes": [ - {"node_id": "local", "capacity_bytes": 10}, - {"node_id": "peer", "capacity_bytes": 10}, - ], - "hosts": [ - { - "node_id": "local", - "ssh": "127.0.0.1", - "ips": ["10.0.0.1"], - }, - { - "node_id": "peer", - "ssh": "peer.local; bad", - "ips": ["10.0.0.2"], - }, - ], - } + "model_path": str(tmp_path / "model"), + "backend": "ring", + "nodes": [ + {"node_id": "local", "capacity_bytes": 10}, + {"node_id": "peer", "capacity_bytes": 10}, + ], + "hosts": [ + { + "node_id": "local", + "ssh": "127.0.0.1", + "ips": ["10.0.0.1"], + }, + { + "node_id": "peer", + "ssh": "peer.local; bad", + "ips": ["10.0.0.2"], + }, + ], + } body["approved_placement"] = _approval_for(body) response = _client().post("/admin/api/cluster/deployments", json=body) @@ -1192,9 +1222,7 @@ def test_pairing_token_route_authenticates_with_the_shared_secret(): assert rejected.json() == {"valid": False} -def test_cuda_join_command_is_single_use_pinned_and_not_cached( - monkeypatch, tmp_path -): +def test_cuda_join_command_is_single_use_pinned_and_not_cached(monkeypatch, tmp_path): from omlx.cluster import ssh_keys store = ClusterEnrollmentStore(tmp_path) @@ -1226,9 +1254,10 @@ def test_cuda_join_command_is_single_use_pinned_and_not_cached( assert payload["controller_key_fingerprint"] == fingerprint assert payload["single_use"] is True assert payload["expires_at"] - payload["created_at"] == 30 * 60 - assert '"join_key":' not in _enrollment_client().get( - "/admin/api/cluster/join-status" - ).text + assert ( + '"join_key":' + not in _enrollment_client().get("/admin/api/cluster/join-status").text + ) def test_cuda_join_command_only_accepts_a_private_ipv4_controller(): @@ -1242,9 +1271,7 @@ def test_cuda_join_command_only_accepts_a_private_ipv4_controller(): assert "controller" in response.json()["detail"] -def test_cuda_worker_claim_replay_and_completion_fail_closed( - monkeypatch, tmp_path -): +def test_cuda_worker_claim_replay_and_completion_fail_closed(monkeypatch, tmp_path): from omlx.cluster import ssh_keys store = ClusterEnrollmentStore(tmp_path) @@ -1342,9 +1369,10 @@ def test_cuda_worker_completion_refuses_a_forged_host_fingerprint( fingerprint=ssh_keys.ssh_public_key_fingerprint(controller_key), ), ) - worker_key = "ssh-ed25519 " + base64.b64encode( - b"worker-host-key-material-long-enough" - ).decode() + worker_key = ( + "ssh-ed25519 " + + base64.b64encode(b"worker-host-key-material-long-enough").decode() + ) raw_key, _ = store.issue_join_key( controller_url="http://10.42.0.10:8000", source_digest="b" * 64, @@ -2037,8 +2065,7 @@ def verify(hosts): ("192.168.100.2", "192.168.101.2"), ] assert all( - host.interfaces == ("enp1s0f0np0", "enp2s0f0np0") - for host in captured["hosts"] + host.interfaces == ("enp1s0f0np0", "enp2s0f0np0") for host in captured["hosts"] ) diff --git a/tests/test_cluster_runtime.py b/tests/test_cluster_runtime.py index de52bcd1ff..05d0b34986 100644 --- a/tests/test_cluster_runtime.py +++ b/tests/test_cluster_runtime.py @@ -98,6 +98,22 @@ def test_runtime_markers_report_this_macs_live_rank(tmp_path): assert result["jobs"][0]["end_layer"] == 26 +def test_runtime_reader_ignores_launch_and_control_json_files(tmp_path): + (tmp_path / "job.json").write_text(json.dumps(_marker())) + for name in ( + "launch-deployment.json", + "deployment-cancel.json", + "deployment-cancel-ack.json", + "deployment-serve.json", + ): + (tmp_path / name).write_text("not a rank marker", encoding="utf-8") + + result = read_runtime_markers(tmp_path) + + assert len(result["jobs"]) == 1 + assert result["warnings"] == [] + + def test_runtime_marker_with_reused_live_pid_is_not_reported_as_running(tmp_path): payload = _marker( updated_at=(datetime.now(UTC) - timedelta(minutes=5)).isoformat(), diff --git a/tests/test_cluster_runtime_v2.py b/tests/test_cluster_runtime_v2.py new file mode 100644 index 0000000000..a424387b56 --- /dev/null +++ b/tests/test_cluster_runtime_v2.py @@ -0,0 +1,409 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Runtime-membership v2 tests: backend selection, N-node launch manifest, +and ring-backend verified-teardown parity. + +All offline: process groups, killpg, SSH sweeps, pools, and probes are mocked. +""" + +import signal +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from omlx.cluster import launch, routes +from omlx.cluster.backends import ( + MemberFabric, + members_from_host_records, + select_cluster_backend, +) +from omlx.cluster.deployment import ( + ClusterDeployment, + ClusterHost, + decode_worker_contract, +) +from omlx.cluster.planner import ModelLayout, PipelineAssignment +from omlx.cluster.registry import configure_cluster_registry + + +def _client() -> TestClient: + app = FastAPI() + app.include_router(routes.router) + return TestClient(app) + + +# --------------------------------------------------------------------------- +# Backend selection +# --------------------------------------------------------------------------- + + +def test_backend_selection_picks_jaccl_when_all_members_ready(): + selection = select_cluster_backend( + [ + MemberFabric("a", True, ("rdma_en5",)), + MemberFabric("b", True, ("rdma_en1", "rdma_en2")), + MemberFabric("c", True, ("rdma_en0",)), + ] + ) + + assert selection.backend == "jaccl" + assert selection.blockers == () + assert len(selection.members) == 3 + + +def test_backend_selection_falls_back_to_ring_and_names_blockers(): + selection = select_cluster_backend( + [ + MemberFabric("a", True, ("rdma_en5",)), + MemberFabric("b", False, ()), + MemberFabric("c", True, ()), # enabled but deviceless + ] + ) + + assert selection.backend == "ring" + assert selection.blockers == ("b", "c") + assert "b has rdma_ctl disabled" in selection.reason + assert "c reports no RDMA device" in selection.reason + + +def test_backend_selection_requires_two_members_and_unique_ids(): + with pytest.raises(ValueError, match="at least two"): + select_cluster_backend([MemberFabric("a", True, ("rdma_en0",))]) + with pytest.raises(ValueError, match="unique"): + select_cluster_backend( + [MemberFabric("a", True, ("rdma_en0",)), MemberFabric("a")] + ) + + +def test_members_from_host_records_reads_complete_matrices(): + hosts = [ + SimpleNamespace(node_id="a", rdma=[None, "rdma_en5"]), + SimpleNamespace(node_id="b", rdma=["rdma_en5", None]), + ] + members = members_from_host_records(hosts) + assert all(member.rdma_ctl_enabled for member in members) + assert select_cluster_backend(members).backend == "jaccl" + + incomplete = [ + SimpleNamespace(node_id="a", rdma=[]), + SimpleNamespace(node_id="b", rdma=["rdma_en5", None]), + ] + members = members_from_host_records(incomplete) + assert [member.rdma_ctl_enabled for member in members] == [False, True] + selection = select_cluster_backend(members) + assert selection.backend == "ring" + assert selection.blockers == ("a",) + + +def test_backend_selection_endpoint(): + response = _client().post( + "/admin/api/cluster/backend-selection", + json={ + "members": [ + { + "node_id": "studio", + "rdma_ctl_enabled": True, + "rdma_devices": ["rdma_en5"], + }, + {"node_id": "macbook", "rdma_ctl_enabled": False}, + ] + }, + ) + + assert response.status_code == 200 + payload = response.json() + assert payload["backend"] == "ring" + assert payload["blockers"] == ["macbook"] + assert {m["node_id"] for m in payload["members"]} == {"studio", "macbook"} + + +def test_backend_selection_endpoint_all_rdma_picks_jaccl(): + response = _client().post( + "/admin/api/cluster/backend-selection", + json={ + "members": [ + { + "node_id": "a", + "rdma_ctl_enabled": True, + "rdma_devices": ["rdma_en1"], + }, + { + "node_id": "b", + "rdma_ctl_enabled": True, + "rdma_devices": ["rdma_en5"], + }, + ] + }, + ) + + assert response.status_code == 200 + assert response.json()["backend"] == "jaccl" + + +# --------------------------------------------------------------------------- +# Replan with backend="auto" +# --------------------------------------------------------------------------- + + +def _install_route_doubles(monkeypatch): + monkeypatch.setattr( + routes, + "inspect_safetensors_layout", + lambda path: ModelLayout( + source=path, + fixed_weight_bytes=1, + layer_weight_bytes=(10, 10, 10, 10), + supports_pipeline=True, + ), + ) + monkeypatch.setattr(routes, "check_peers", lambda *args, **kwargs: ()) + + +def test_replan_auto_selects_jaccl_from_complete_matrix(tmp_path, monkeypatch): + configure_cluster_registry(tmp_path) + _install_route_doubles(monkeypatch) + monkeypatch.setattr( + routes, + "_get_engine_pool", + lambda: SimpleNamespace(), + ) + nodes = [ + {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, + {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 10}, + ] + hosts = [ + { + "node_id": "large", + "ssh": "127.0.0.1", + "ips": ["192.168.5.1"], + "rdma": [None, "rdma_en5"], + }, + { + "node_id": "small", + "ssh": "studio.local", + "ips": ["192.168.5.2"], + "rdma": ["rdma_en5", None], + }, + ] + + response = _client().post( + "/admin/api/cluster/replan", + json={ + "model_path": "/models/example", + "backend": "auto", + "nodes": nodes, + "hosts": hosts, + }, + ) + + assert response.status_code == 200, response.json() + payload = response.json() + assert payload["mode"] == "preview" + assert payload["backend"] == "jaccl" + assert payload["backend_decision"]["backend"] == "jaccl" + assert payload["deployment_id"] + + +def test_replan_auto_falls_back_to_ring(tmp_path, monkeypatch): + configure_cluster_registry(tmp_path) + _install_route_doubles(monkeypatch) + monkeypatch.setattr(routes, "_get_engine_pool", lambda: SimpleNamespace()) + + response = _client().post( + "/admin/api/cluster/replan", + json={ + "model_path": "/models/example", + "backend": "auto", + "nodes": [ + {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, + {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 10}, + ], + "hosts": [ + {"node_id": "large", "ssh": "127.0.0.1", "ips": ["192.168.5.1"]}, + {"node_id": "small", "ssh": "studio.local", "ips": ["192.168.5.2"]}, + ], + }, + ) + + assert response.status_code == 200, response.json() + payload = response.json() + assert payload["backend"] == "ring" + assert payload["backend_decision"]["blockers"] == ["large", "small"] + + +# --------------------------------------------------------------------------- +# N-node launch manifest +# --------------------------------------------------------------------------- + + +def _three_node_ring_deployment() -> ClusterDeployment: + return ClusterDeployment( + deployment_id="cluster-nnode", + model="org/model", + backend="ring", + hosts=( + ClusterHost("local", "127.0.0.1", ("10.0.0.1",)), + ClusterHost("studio", "user@studio.local", ("10.0.0.2",)), + ClusterHost("mini", "user@mini.local", ("10.0.0.3",)), + ), + assignments=( + PipelineAssignment("local", 0, 6, 9, 5, 1, 1, 16), + PipelineAssignment("studio", 1, 3, 6, 3, 1, 1, 8), + PipelineAssignment("mini", 2, 0, 3, 3, 1, 1, 8), + ), + plan_hash="d" * 64, + ) + + +def test_launch_manifest_records_every_host(tmp_path): + deployment = _three_node_ring_deployment() + + path = launch._write_launch_manifest( + tmp_path, deployment, launcher_pid=43210, api_port=32100 + ) + + manifest = launch._read_launch_manifest(path) + assert manifest is not None + assert manifest["deployment_id"] == "cluster-nnode" + assert manifest["process_group"] == 43210 + assert manifest["hosts"] == [ + {"rank": 0, "node_id": "local", "ssh": "127.0.0.1"}, + {"rank": 1, "node_id": "studio", "ssh": "user@studio.local"}, + {"rank": 2, "node_id": "mini", "ssh": "user@mini.local"}, + ] + + +def test_three_node_ring_deployment_validates_and_maps_backend(): + deployment = _three_node_ring_deployment() + + assert deployment.world_size == 3 + assert deployment.distributed_init_backend == "ring" + hostfile = deployment.hostfile_dict() + assert hostfile["backend"] == "ring" + assert len(hostfile["hosts"]) == 3 + # The worker contract carries all three assignments, rank-indexed. + plan_hash, assignments, _, tp = decode_worker_contract( + deployment.encode_worker_plan() + ) + assert plan_hash == deployment.plan_hash + assert [item.rank for item in assignments] == [0, 1, 2] + assert tp == 1 + + +# --------------------------------------------------------------------------- +# Ring carries the same verified-teardown semantics as JACCL +# --------------------------------------------------------------------------- + + +class _Launcher: + pid = 43210 + stdout = None + stderr = None + + def __init__(self, returncode=None): + self.returncode = returncode + + def poll(self): + return self.returncode + + def wait(self, timeout=None): + self.returncode = 0 + return 0 + + +def _teardown_mocks(monkeypatch, group_exit_results): + results = iter(group_exit_results) + monkeypatch.setattr(launch, "_process_group_alive", lambda _pgid: True) + monkeypatch.setattr( + launch, + "_wait_for_process_group_exit", + lambda _pgid, _timeout: next(results), + ) + signals = [] + monkeypatch.setattr( + launch.os, + "killpg", + lambda pgid, sig: signals.append((pgid, sig)), + ) + return signals + + +def test_ring_teardown_verifies_killpg_and_raises_on_survivors(monkeypatch): + supervisor = launch.DistributedJobSupervisor( + _three_node_ring_deployment(), + preflight=False, + stop_timeout=0.1, + ) + supervisor.process = _Launcher() + signals = _teardown_mocks(monkeypatch, [False, False, False]) + swept = [] + monkeypatch.setattr( + launch.DistributedJobSupervisor, + "_sweep_rank_leftovers", + lambda self, **_kw: swept.append(True) or [], + ) + + with pytest.raises(launch.DistributedTeardownError, match="survived SIGKILL"): + supervisor.stop() + + # TERM, then KILL twice — identical escalation to the JACCL path, because + # there is exactly one teardown path and it is backend-agnostic. + assert signals == [ + (43210, signal.SIGTERM), + (43210, signal.SIGKILL), + (43210, signal.SIGKILL), + ] + # The rank sweep runs even when the group is the problem, and it covers + # every host of the N-node ring, not just local ranks. + assert swept == [True] + # State is kept so a later stop() retries instead of forgetting the job. + assert supervisor.process is not None + + +def test_ring_teardown_sweeps_leftover_ranks_by_marker_pid(monkeypatch): + deployment = _three_node_ring_deployment() + supervisor = launch.DistributedJobSupervisor( + deployment, + preflight=False, + stop_timeout=0.1, + ) + supervisor.process = _Launcher() + _teardown_mocks(monkeypatch, [True]) + swept_hosts = [] + + def fake_sweep(deployment_id, hosts, **kwargs): + swept_hosts.extend(hosts) + return [] + + monkeypatch.setattr(launch, "_sweep_rank_processes", fake_sweep) + + supervisor.stop() + + assert supervisor.process is None + assert supervisor.status().phase == "stopped" + assert swept_hosts == [ + {"rank": 0, "node_id": "local", "ssh": "127.0.0.1"}, + {"rank": 1, "node_id": "studio", "ssh": "user@studio.local"}, + {"rank": 2, "node_id": "mini", "ssh": "user@mini.local"}, + ] + + +def test_ring_teardown_reports_unkillable_leftover_rank(monkeypatch): + supervisor = launch.DistributedJobSupervisor( + _three_node_ring_deployment(), + preflight=False, + stop_timeout=0.1, + ) + supervisor.process = _Launcher() + _teardown_mocks(monkeypatch, [True]) + monkeypatch.setattr( + launch, + "_sweep_rank_processes", + lambda *args, **kwargs: ["rank 2 (mini): pid 999 survived SIGKILL"], + ) + + with pytest.raises(launch.DistributedTeardownError, match="rank 2 \\(mini\\)"): + supervisor.stop() + + assert supervisor.process is not None diff --git a/tests/test_cluster_seams.py b/tests/test_cluster_seams.py index 59716bb2c6..62b3803a08 100644 --- a/tests/test_cluster_seams.py +++ b/tests/test_cluster_seams.py @@ -77,6 +77,14 @@ def test_no_cluster_route_is_unreachable_from_the_dashboard(): # The backend PR intentionally lands before the Cluster v2 dashboard. The # UI follow-up will call replan after the deployment contract settles. allowed_without_caller: set[str] = {"/admin/api/cluster/replan"} + # Runtime lifecycle APIs land before the Cluster v2 dashboard follow-up. + allowed_without_caller.update( + { + "/admin/api/cluster/backend-selection", + "/admin/api/cluster/deployments/{parameter}/load", + "/admin/api/cluster/deployments/{parameter}/unload", + } + ) unreachable = _registered_routes() - _js_called_paths() - allowed_without_caller assert not unreachable, ( f"cluster routes nothing calls: {sorted(unreachable)} — wire them up or " diff --git a/tests/test_cluster_telemetry.py b/tests/test_cluster_telemetry.py index 0c37b17e3b..8089466aab 100644 --- a/tests/test_cluster_telemetry.py +++ b/tests/test_cluster_telemetry.py @@ -1,14 +1,19 @@ # SPDX-License-Identifier: Apache-2.0 """Tests for rank-local, end-to-end distributed inference telemetry.""" +import json +import struct import threading import time from types import SimpleNamespace +import pytest + from omlx.cluster.performance import execution_profile from omlx.cluster.planner import PipelineAssignment from omlx.cluster.telemetry import ( RuntimeTelemetry, + _python_token_id, _TelemetryQueue, install_server_telemetry, ) @@ -39,6 +44,24 @@ def put(self, item, *args, **kwargs): return "queued" +def test_generated_token_is_normalized_for_logprob_indexing(): + class Scalar: + def item(self): + return 129_279 + + assert _python_token_id(Scalar()) == 129_279 + assert _python_token_id([[42]]) == 42 + + +def test_generated_token_normalization_rejects_non_scalar_and_high_bit(): + import pytest + + with pytest.raises(ValueError, match="scalar"): + _python_token_id([1, 2]) + with pytest.raises(ValueError, match="signed int32"): + _python_token_id(2**31) + + def test_telemetry_calculates_ttft_prefill_and_decode_rates(): clock = _Clock() marker = _Marker() @@ -193,6 +216,26 @@ def test_queue_observer_preserves_mlx_lm_queue_contract(): assert snapshot["completion_tokens_total"] == 1 +def test_shared_uid_removal_terminates_the_waiting_response_queue(): + telemetry = RuntimeTelemetry(_Marker(), publish_interval=0) + target = _Queue() + queue = _TelemetryQueue(target, telemetry) + context = SimpleNamespace( + prompt=[1, 2, 3], + prompt_cache_count=0, + stop=lambda: None, + ) + queue.put(context) + telemetry.bind_pending_uid((91,)) + + telemetry.cancel_uids([91]) + + assert [item[0] for item in target.items] == [context, None] + snapshot = telemetry.snapshot() + assert snapshot["active_requests"] == 0 + assert snapshot["requests_cancelled"] == 1 + + def test_telemetry_marker_failure_never_interrupts_inference(): class BrokenMarker: def update(self, phase, **extra): @@ -351,9 +394,7 @@ def nbytes(self): assert progress["active"] is True assert batch.remove([73]) == "removed" assert generator._tokenize(None, None, None)[0] == [1, 2, 3, 4] - assert generator.prompt_cache.fetch_nearest_cache( - "model", [1, 2, 3, 4] - ) == ( + assert generator.prompt_cache.fetch_nearest_cache("model", [1, 2, 3, 4]) == ( "cache", [3, 4], ) @@ -446,9 +487,7 @@ def test_an_idle_rank_still_refreshes_its_marker(): """No requests, no tokens, nothing to report — and the marker still ages.""" marker = _CountingMarker() - telemetry = RuntimeTelemetry( - marker, publish_interval=0, heartbeat_interval=0.01 - ) + telemetry = RuntimeTelemetry(marker, publish_interval=0, heartbeat_interval=0.01) telemetry.start_heartbeat() try: @@ -464,9 +503,7 @@ def test_an_idle_rank_still_refreshes_its_marker(): def test_stopping_the_heartbeat_ends_the_thread(): marker = _CountingMarker() - telemetry = RuntimeTelemetry( - marker, publish_interval=0, heartbeat_interval=0.01 - ) + telemetry = RuntimeTelemetry(marker, publish_interval=0, heartbeat_interval=0.01) before = set(threading.enumerate()) telemetry.start_heartbeat() @@ -480,7 +517,8 @@ def test_stopping_the_heartbeat_ends_the_thread(): leaked = { thread for thread in threading.enumerate() - if thread not in before and thread.is_alive() + if thread not in before + and thread.is_alive() and thread.name == "omlx-cluster-telemetry-heartbeat" } assert not leaked @@ -554,3 +592,363 @@ class FakeBatchGenerator: settled = marker.count() time.sleep(0.1) assert marker.count() == settled, "the heartbeat outlived the serving block" + + +class _BatchGenerator: + def __init__(self) -> None: + self.removed = [] + + def remove(self, uids): + self.removed.append(list(uids)) + + +class _GenerationContext: + def __init__(self) -> None: + self.stopped = False + + def stop(self) -> None: + self.stopped = True + + +def _cancel_telemetry(tmp_path, clock=None, *, plan_hash="", epoch_floor=0): + marker = _Marker() + telemetry = RuntimeTelemetry( + marker, + clock=clock or _Clock(), + publish_interval=0, + cancel_path=tmp_path / "dep-1-cancel.json", + cancel_deployment_id="dep-1", + cancel_plan_hash=plan_hash, + cancel_epoch_floor=epoch_floor, + ) + return telemetry + + +def test_force_cancel_all_marks_context_for_the_shared_batch_loop(tmp_path): + telemetry = _cancel_telemetry(tmp_path) + generator = _BatchGenerator() + telemetry.register_batch_generator(generator) + request_id = telemetry.begin_request() + telemetry.mark_pending_uid(request_id) + context = _GenerationContext() + telemetry.register_context(request_id, context) + telemetry.bind_pending_uid((73,)) + + cancelled = telemetry.force_cancel_all(reason="test") + + assert cancelled == 1 + assert context.stopped is True + assert generator.removed == [], "telemetry must never mutate one rank directly" + generator.remove([73]) + telemetry.cancel_uids([73]) + assert generator.removed == [[73]] + assert telemetry._requests == {} + assert telemetry._requests_cancelled == 1 + + +def test_force_cancel_all_without_generator_or_uids_is_a_noop(tmp_path): + telemetry = _cancel_telemetry(tmp_path) + + assert telemetry.force_cancel_all(reason="test") == 0 + + generator = _BatchGenerator() + telemetry.register_batch_generator(generator) + assert telemetry.force_cancel_all(reason="test") == 0 + assert generator.removed == [] + + +def test_force_cancel_all_survives_a_failing_generation_context(tmp_path): + telemetry = _cancel_telemetry(tmp_path) + + class BrokenContext: + def stop(self): + raise RuntimeError("wedged") + + request_id = telemetry.begin_request() + telemetry.mark_pending_uid(request_id) + telemetry.register_context(request_id, BrokenContext()) + telemetry.bind_pending_uid((5,)) + + assert telemetry.force_cancel_all(reason="test") == 0 + # The request stays tracked; the coordinator's process teardown is the + # fallback for this failure mode. + assert request_id in telemetry._requests + + +def test_cancel_file_is_consumed_once_and_acked(tmp_path): + + telemetry = _cancel_telemetry(tmp_path) + generator = _BatchGenerator() + telemetry.register_batch_generator(generator) + request_id = telemetry.begin_request() + telemetry.mark_pending_uid(request_id) + context = _GenerationContext() + telemetry.register_context(request_id, context) + telemetry.bind_pending_uid((9,)) + + cancel_path = tmp_path / "dep-1-cancel.json" + cancel_path.write_text( + json.dumps( + { + "schema_version": 1, + "deployment_id": "dep-1", + "epoch": 42, + "scope": "all", + "reason": "memory pressure", + } + ), + encoding="utf-8", + ) + + assert telemetry.poll_cancel_requests(min_interval=0.0) == 1 + assert context.stopped is True + assert generator.removed == [] + ack = json.loads((tmp_path / "dep-1-cancel-ack.json").read_text(encoding="utf-8")) + assert ack["epoch"] == 42 + assert ack["cancelled"] == 1 + + # Same epoch is not consumed twice. + assert telemetry.poll_cancel_requests(min_interval=0.0) == 0 + assert generator.removed == [] + + +def test_cancel_file_from_a_foreign_deployment_is_ignored(tmp_path): + + telemetry = _cancel_telemetry(tmp_path) + generator = _BatchGenerator() + telemetry.register_batch_generator(generator) + (tmp_path / "dep-1-cancel.json").write_text( + json.dumps( + { + "schema_version": 1, + "deployment_id": "somebody-else", + "epoch": 7, + "scope": "all", + } + ), + encoding="utf-8", + ) + + assert telemetry.poll_cancel_requests(min_interval=0.0) == 0 + assert generator.removed == [] + + +def test_cancel_file_is_scoped_to_plan_and_worker_lifetime(tmp_path): + telemetry = _cancel_telemetry( + tmp_path, + plan_hash="current-plan", + epoch_floor=1000, + ) + request_id = telemetry.begin_request() + telemetry.mark_pending_uid(request_id) + context = _GenerationContext() + telemetry.register_context(request_id, context) + telemetry.bind_pending_uid((11,)) + cancel_path = tmp_path / "dep-1-cancel.json" + + for plan_hash, epoch in (("old-plan", 2000), ("current-plan", 999)): + cancel_path.write_text( + json.dumps( + { + "schema_version": 1, + "deployment_id": "dep-1", + "plan_hash": plan_hash, + "epoch": epoch, + "scope": "all", + } + ), + encoding="utf-8", + ) + assert telemetry.poll_cancel_requests(min_interval=0.0) == 0 + + cancel_path.write_text( + json.dumps( + { + "schema_version": 1, + "deployment_id": "dep-1", + "plan_hash": "current-plan", + "epoch": 1001, + "scope": "all", + } + ), + encoding="utf-8", + ) + assert telemetry.poll_cancel_requests(min_interval=0.0) == 1 + assert context.stopped is True + ack = json.loads((tmp_path / "dep-1-cancel-ack.json").read_text(encoding="utf-8")) + assert ack["plan_hash"] == "current-plan" + + +def test_existing_matching_cancel_is_a_startup_watermark(tmp_path): + cancel_path = tmp_path / "dep-1-cancel.json" + cancel_path.write_text( + json.dumps( + { + "schema_version": 1, + "deployment_id": "dep-1", + "plan_hash": "same-plan", + "epoch": 4242, + "scope": "all", + } + ), + encoding="utf-8", + ) + telemetry = _cancel_telemetry(tmp_path, plan_hash="same-plan") + request_id = telemetry.begin_request() + telemetry.mark_pending_uid(request_id) + context = _GenerationContext() + telemetry.register_context(request_id, context) + telemetry.bind_pending_uid((12,)) + + assert telemetry.poll_cancel_requests(min_interval=0.0) == 0 + payload = json.loads(cancel_path.read_text(encoding="utf-8")) + payload["epoch"] = 4243 + cancel_path.write_text(json.dumps(payload), encoding="utf-8") + assert telemetry.poll_cancel_requests(min_interval=0.0) == 1 + assert context.stopped is True + + +def test_distributed_cancel_vote_drains_and_rendezvous_before_removal(monkeypatch): + import mlx.core as mx + import mlx_lm.server as mlx_server + + events = [] + + class Group: + rank = staticmethod(lambda: 0) + size = staticmethod(lambda: 2) + + class ControlPlane: + def broadcast_object(self, obj): + events.append(("broadcast", obj)) + return obj + + def barrier(self): + events.append(("barrier", None)) + + class FakeResponseGenerator: + def __init__(self): + self._is_distributed = True + self._rank = 0 + + def _share_object(self, _obj): + raise AssertionError("patched sharing must own cancellation") + + class FakeBatchGenerator: + def remove(self, uids): + events.append(("remove", list(uids))) + return "removed" + + monkeypatch.setattr(mx.distributed, "init", lambda: Group()) + monkeypatch.setattr(mx, "synchronize", lambda *args: events.append(("drain", None))) + monkeypatch.setattr(mlx_server, "ResponseGenerator", FakeResponseGenerator) + monkeypatch.setattr(mlx_server, "BatchGenerator", FakeBatchGenerator) + + with install_server_telemetry( + _Marker(), + heartbeat_interval=0, + control_plane=ControlPlane(), + ): + generator = mlx_server.ResponseGenerator() + batch = mlx_server.BatchGenerator() + with pytest.raises(RuntimeError, match="not armed"): + batch.remove([73]) + assert generator._share_object([73]) == [73] + assert batch.remove([73]) == "removed" + + assert [event[0] for event in events] == [ + "broadcast", + "drain", + "barrier", + "remove", + ] + + +def test_pipeline_cache_plan_requires_rank_agreement(monkeypatch): + import mlx.core as mx + import mlx_lm.server as mlx_server + + class Group: + rank = staticmethod(lambda: 0) + size = staticmethod(lambda: 2) + + class FakePromptCache: + def fetch_nearest_cache(self, _model, tokens): + return "rank-zero-cache", tokens[2:] + + def __len__(self): + return 1 + + nbytes = 64 + + class ControlPlane: + peer_plan = (2, 2, 0) + + def broadcast_owned_bytes(self, payload, *, source_rank, expected_size): + assert expected_size == 24 + return payload if source_rank == 0 else struct.pack("!QQQ", *self.peer_plan) + + monkeypatch.setattr(mx.distributed, "init", lambda: Group()) + monkeypatch.setattr(mlx_server, "LRUPromptCache", FakePromptCache) + control = ControlPlane() + + with install_server_telemetry( + _Marker(), heartbeat_interval=0, control_plane=control + ): + cache = mlx_server.LRUPromptCache() + tokens = [1, 2, 3, 4] + assert cache.fetch_nearest_cache("model", tokens) == ( + "rank-zero-cache", + [3, 4], + ) + control.peer_plan = (0, 4, 0) + assert cache.fetch_nearest_cache("model", tokens) == (None, tokens) + + +def test_rank_hot_clear_reaches_live_prompt_cache_instances(monkeypatch): + from io import BytesIO + + import mlx_lm.server as mlx_server + + class Marker(_Marker): + payload = {"deployment_id": "dep", "plan_hash": "p" * 64} + path = None + + class FakePromptCache: + def __init__(self): + self.entries = 3 + + def __len__(self): + return self.entries + + @property + def nbytes(self): + return self.entries * 64 + + def trim_to(self, *, n_sequences, n_bytes): + assert (n_sequences, n_bytes) == (0, 0) + self.entries = 0 + + class Handler: + path = "/omlx/internal/cache/hot/clear" + headers = {"X-oMLX-Plan-Hash": "p" * 64} + + def __init__(self): + self.wfile = BytesIO() + self.status = None + + def _set_completion_headers(self, status): + self.status = status + + def end_headers(self): + return None + + monkeypatch.setattr(mlx_server, "LRUPromptCache", FakePromptCache) + with install_server_telemetry(Marker(), heartbeat_interval=0): + cache = mlx_server.LRUPromptCache() + handler = Handler() + mlx_server.APIHandler.do_POST(handler) + + assert cache.entries == 0 + assert handler.status == 200 + assert json.loads(handler.wfile.getvalue())["hot_cleared"] == 3 diff --git a/tests/test_distributed_engine.py b/tests/test_distributed_engine.py index 2a2e3ab0db..e909aaee33 100644 --- a/tests/test_distributed_engine.py +++ b/tests/test_distributed_engine.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 import json +import tempfile from dataclasses import replace from types import SimpleNamespace @@ -49,9 +50,102 @@ def _ready_engine(handler) -> DistributedBatchedEngine: base_url="http://127.0.0.1:1", transport=httpx.MockTransport(handler), ) + engine._supervisor.port = 8001 return engine +@pytest.mark.asyncio +async def test_acknowledged_cancel_all_does_not_widen_later_targeted_cancel(tmp_path): + engine = _ready_engine(lambda request: httpx.Response(200, json={})) + engine._supervisor.state_dir = str(tmp_path) + cancel_path = tmp_path / "engine-test-cancel.json" + ack_path = tmp_path / "engine-test-cancel-ack.json" + old_epoch = 9_999_999_999_999 + cancel_path.write_text( + json.dumps( + { + "schema_version": 1, + "deployment_id": "engine-test", + "plan_hash": "d" * 64, + "epoch": old_epoch, + "scope": "all", + } + ), + encoding="utf-8", + ) + ack_path.write_text( + json.dumps( + { + "schema_version": 1, + "deployment_id": "engine-test", + "plan_hash": "d" * 64, + "epoch": old_epoch, + "cancelled": 1, + } + ), + encoding="utf-8", + ) + request_id = await engine._enter_request("transport-new-client") + try: + assert await engine.abort_request(request_id, reason="socket closed") is True + payload = json.loads(cancel_path.read_text(encoding="utf-8")) + assert payload["scope"] == "requests" + assert payload["request_ids"] == [request_id] + finally: + await engine._leave_request(request_id) + await engine._client.aclose() + + +@pytest.mark.asyncio +async def test_distributed_ssd_clear_reaches_every_rank(monkeypatch): + requests = [] + + def handler(request): + requests.append(request) + return httpx.Response( + 200, + json={"status": "ok", "rank": 0, "ssd_deleted": 3, "hot_cleared": 0}, + ) + + remote_calls = [] + + def remote(ssh_target, command, timeout, runner): + remote_calls.append((ssh_target, command, timeout)) + return SimpleNamespace( + returncode=0, + stdout=json.dumps( + {"status": "ok", "rank": 1, "ssd_deleted": 5, "hot_cleared": 0} + ), + stderr="", + ) + + monkeypatch.setattr(distributed, "_run_cluster_ssh", remote) + engine = _ready_engine(handler) + try: + result = await engine.clear_prompt_caches(ssd=True) + finally: + await engine._client.aclose() + + assert result["ssd_deleted"] == 8 + assert len(result["ranks"]) == 2 + assert requests[0].url.path == "/omlx/internal/cache/ssd/clear" + assert requests[0].headers["X-oMLX-Plan-Hash"] == "d" * 64 + assert remote_calls[0][0] == "peer.local" + assert "engine-test-cache-clear.json" in remote_calls[0][1] + assert '"ssd":true' in remote_calls[0][1] + + +@pytest.mark.asyncio +async def test_distributed_cache_clear_refuses_active_requests(): + engine = _ready_engine(lambda _request: httpx.Response(200, json={})) + engine._active_requests = 1 + try: + with pytest.raises(DistributedInferenceError, match="requests are active"): + await engine.clear_prompt_caches(ssd=True) + finally: + await engine._client.aclose() + + def test_backend_chat_messages_serialize_native_tool_history_once(): messages = [ { @@ -145,6 +239,9 @@ def handler(request): raise httpx.ReadTimeout("collective stalled", request=request) engine = _ready_engine(handler) + # Read timeouts now drop a rank-side cancel file; keep it out of the + # real runtime state dir. + engine._supervisor.state_dir = tempfile.mkdtemp(prefix="omlx-test-runtime-") status_calls = [] def status(): @@ -872,9 +969,7 @@ def test_reasoning_effort_retry_payloads_ignores_when_not_requested(): payload = {"chat_template_kwargs": {}} assert ( - _reasoning_effort_retry_payloads( - payload, "Unexpected reasoning effort high." - ) + _reasoning_effort_retry_payloads(payload, "Unexpected reasoning effort high.") == [] ) @@ -900,7 +995,10 @@ def handler(request): 200, json={ "choices": [ - {"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"} + { + "message": {"role": "assistant", "content": "ok"}, + "finish_reason": "stop", + } ], "usage": {"prompt_tokens": 1, "completion_tokens": 1}, }, @@ -1086,6 +1184,26 @@ def _healthy_supervisor_status(): return SimpleNamespace(returncode=None, failure_reason=None) +def test_runtime_failure_reconciles_supervisor_terminal_state(monkeypatch): + """Pool status/release must see a rank death even after a 200 response.""" + + engine = _ready_engine(lambda request: httpx.Response(200)) + monkeypatch.setattr( + engine._supervisor, + "status", + lambda: SimpleNamespace( + returncode=0, + failure_reason=( + "rank 0 exited with code 75 after JACCL all_reduce made no progress" + ), + phase="failed", + ), + ) + + assert engine.runtime_failed_reason is not None + assert "rank 0 exited with code 75" in engine.runtime_failed_reason + + @pytest.mark.asyncio async def test_preflight_rejects_an_unhealthy_rank_before_streaming(monkeypatch): # The 200 commits before a streaming body runs, so preflight is the last diff --git a/tests/test_jaccl_side_channel.py b/tests/test_jaccl_side_channel.py new file mode 100644 index 0000000000..1f51bd5f11 --- /dev/null +++ b/tests/test_jaccl_side_channel.py @@ -0,0 +1,136 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Tests for the bounded Python control plane used to bootstrap JACCL.""" + +from __future__ import annotations + +import socket +import threading + +import pytest + +from omlx.cluster.jaccl_side_channel import ( + _coordinator_endpoint, + init_cluster_group, + jaccl_all_gather_factory, +) + + +def _free_loopback_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: + listener.bind(("127.0.0.1", 0)) + return int(listener.getsockname()[1]) + + +def test_socket_side_channel_orders_ranks_and_reuses_connections(monkeypatch): + port = _free_loopback_port() + monkeypatch.setenv("MLX_JACCL_COORDINATOR", f"127.0.0.1:{port}") + monkeypatch.setenv("OMLX_JACCL_SIDE_CHANNEL_TIMEOUT_SECONDS", "3") + monkeypatch.setenv("OMLX_JACCL_SIDE_CHANNEL_TRANSPORT", "direct") + results: dict[str, bytes] = {} + errors: list[BaseException] = [] + server_ready = threading.Event() + + def rank_zero() -> None: + try: + gather = jaccl_all_gather_factory(0, 2) + server_ready.set() + results["first_server"] = gather(b"aa", 2) + results["second_server"] = gather(b"cc", 2) + except BaseException as exc: # propagate thread failures to pytest + errors.append(exc) + server_ready.set() + + thread = threading.Thread(target=rank_zero) + thread.start() + gather = jaccl_all_gather_factory(1, 2) + assert server_ready.wait(3) + results["first_client"] = gather(b"bb", 2) + results["second_client"] = gather(b"dd", 2) + thread.join(3) + + assert not thread.is_alive() + assert not errors + assert results == { + "first_server": b"aabb", + "first_client": b"aabb", + "second_server": b"ccdd", + "second_client": b"ccdd", + } + + +def test_sidecar_orders_ranks_without_using_parent_network(monkeypatch): + port = _free_loopback_port() + monkeypatch.setenv("MLX_JACCL_COORDINATOR", f"127.0.0.1:{port}") + monkeypatch.setenv("OMLX_JACCL_SIDE_CHANNEL_TIMEOUT_SECONDS", "3") + monkeypatch.setenv("OMLX_JACCL_SIDE_CHANNEL_TRANSPORT", "sidecar") + results: dict[str, bytes] = {} + errors: list[BaseException] = [] + + first = jaccl_all_gather_factory(0, 2) + second = jaccl_all_gather_factory(1, 2) + + def rank_zero() -> None: + try: + results["server"] = first(b"aa", 2) + except BaseException as exc: + errors.append(exc) + + thread = threading.Thread(target=rank_zero) + thread.start() + results["client"] = second(b"bb", 2) + thread.join(3) + first.close() + second.close() + + assert not thread.is_alive() + assert not errors + assert results == {"server": b"aabb", "client": b"aabb"} + + +@pytest.mark.parametrize("value", ["", "host", "127.0.0.1:0", "[::1]:8000"]) +def test_side_channel_requires_a_valid_ipv4_coordinator(monkeypatch, value): + monkeypatch.setenv("MLX_JACCL_COORDINATOR", value) + with pytest.raises(RuntimeError, match="coordinator|IPv4"): + _coordinator_endpoint() + + +def test_init_cluster_group_only_injects_factory_for_enabled_jaccl(monkeypatch): + calls: list[dict[str, object]] = [] + + class Distributed: + def init(self, **kwargs): + calls.append(kwargs) + return "group" + + Distributed.init.__doc__ = "init(..., *, all_gather_factory: Callable = None)" + + class MX: + distributed = Distributed() + + monkeypatch.setenv("MLX_JACCL_COORDINATOR", "10.0.0.1:8000") + assert init_cluster_group(MX(), backend="jaccl", strict=True) == "group" + assert calls[-1]["backend"] == "jaccl" + assert calls[-1]["strict"] is True + assert calls[-1]["all_gather_factory"] is jaccl_all_gather_factory + + monkeypatch.setenv("OMLX_JACCL_PYTHON_SIDE_CHANNEL", "0") + assert init_cluster_group(MX(), backend="jaccl", strict=True) == "group" + assert calls[-1] == {"backend": "jaccl", "strict": True} + + assert init_cluster_group(MX(), backend="ring", strict=False) == "group" + assert calls[-1] == {"backend": "ring", "strict": False} + + +def test_init_cluster_group_does_not_trust_a_newer_stub_than_native(): + calls: list[dict[str, object]] = [] + + class Distributed: + def init(self, **kwargs): + calls.append(kwargs) + return "group" + + class MX: + distributed = Distributed() + + assert init_cluster_group(MX(), backend="jaccl", strict=True) == "group" + assert calls == [{"backend": "jaccl", "strict": True}] diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index e618dd512f..eeb333fd06 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -807,10 +807,10 @@ def test_add_request_under_pressure_skips_hot_cache_preload_and_promotion( ) scheduler._current_usage_bytes.assert_called_once_with() - def test_add_request_below_pressure_keeps_hot_cache_preload_and_promotion( + def test_add_request_below_pressure_promotes_during_single_reconstruction( self, mock_model, mock_tokenizer ): - """Normal memory state should preserve existing hot-cache acceleration.""" + """Normal state promotes while reconstructing, without a duplicate preload.""" from omlx.cache.paged_cache import BlockTable scheduler = self._scheduler_with_mock_block_cache( @@ -839,7 +839,7 @@ def test_add_request_below_pressure_keeps_hot_cache_preload_and_promotion( scheduler.add_request(request) scheduler._prepare_prefix_cache_for_request(request) - scheduler.block_aware_cache.preload_blocks.assert_called_once_with(block_table) + scheduler.block_aware_cache.preload_blocks.assert_not_called() scheduler.block_aware_cache.reconstruct_cache.assert_called_once_with( block_table ) @@ -877,7 +877,7 @@ def test_add_request_hot_cache_only_ignores_pressure_bypass( scheduler.add_request(request) scheduler._prepare_prefix_cache_for_request(request) - scheduler.block_aware_cache.preload_blocks.assert_called_once_with(block_table) + scheduler.block_aware_cache.preload_blocks.assert_not_called() scheduler.block_aware_cache.reconstruct_cache.assert_called_once_with( block_table ) diff --git a/tests/test_server.py b/tests/test_server.py index ad835473ee..884349c04d 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -67,6 +67,40 @@ def test_reset_helper_skips_no_cache(self, tmp_path): assert stale_dir.exists() +@pytest.mark.asyncio +async def test_text_completion_stream_forwards_transport_request_id(): + from omlx.api.openai_models import CompletionRequest + from omlx.server import stream_completion + + class Engine: + tokenizer = None + + def __init__(self): + self.kwargs = None + + async def stream_generate(self, **kwargs): + self.kwargs = kwargs + if False: + yield None + + engine = Engine() + request = CompletionRequest(model="model", prompt="hello", stream=True) + + chunks = [ + chunk + async for chunk in stream_completion( + engine, + "hello", + request, + prompt_token_ids=[], + inference_request_id="transport-completion-1", + ) + ] + + assert chunks == ["data: [DONE]\n\n"] + assert engine.kwargs["_request_id"] == "transport-completion-1" + + class TestDiffusionStructuredOutputGuard: class _DiffusionEngine: is_diffusion_model = True diff --git a/tests/test_sse_keepalive.py b/tests/test_sse_keepalive.py index f9ed1307f7..325a022053 100644 --- a/tests/test_sse_keepalive.py +++ b/tests/test_sse_keepalive.py @@ -3,10 +3,15 @@ import asyncio import json +import socket import pytest -from omlx.server import _with_sse_keepalive +from omlx.server import ( + ClientDisconnectTrackingMiddleware, + _with_request_disconnect_abort, + _with_sse_keepalive, +) async def _collect(gen): @@ -130,6 +135,79 @@ async def is_disconnected(self): assert closed.is_set() +@pytest.mark.asyncio +async def test_real_uvicorn_socket_disconnect_aborts_only_its_request(): + """Exercise the real Uvicorn/Starlette receive race, not a mocked Request.""" + + import uvicorn + from fastapi import FastAPI, Request + from fastapi.responses import StreamingResponse + + aborted: list[str] = [] + abort_seen = asyncio.Event() + + class Engine: + supports_request_scoped_abort = True + + async def abort_request(self, request_id, **_kwargs): + aborted.append(request_id) + abort_seen.set() + return True + + engine = Engine() + socket_app = FastAPI() + socket_app.add_middleware(ClientDisconnectTrackingMiddleware) + + @socket_app.get("/stream") + async def stream(http_request: Request): + async def prefill(): + while True: + await asyncio.sleep(60) + yield "data: token\n\n" + + body = _with_request_disconnect_abort( + _with_sse_keepalive( + prefill(), + http_request=http_request, + interval=60, + disconnect_poll=60, + ), + http_request, + engine, + "transport-socket-owner", + ) + return StreamingResponse(body, media_type="text/event-stream") + + listener = socket.socket() + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind(("127.0.0.1", 0)) + listener.listen() + listener.setblocking(False) + port = listener.getsockname()[1] + config = uvicorn.Config(socket_app, lifespan="off", log_level="warning") + server = uvicorn.Server(config) + server_task = asyncio.create_task(server.serve(sockets=[listener])) + try: + while not server.started: + await asyncio.sleep(0.01) + reader, writer = await asyncio.open_connection("127.0.0.1", port) + writer.write( + b"GET /stream HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n" + ) + await writer.drain() + await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=2.0) + await asyncio.wait_for(reader.read(1024), timeout=2.0) # initial keepalive + writer.close() + await writer.wait_closed() + + await asyncio.wait_for(abort_seen.wait(), timeout=2.0) + finally: + server.should_exit = True + await asyncio.wait_for(server_task, timeout=5.0) + + assert aborted == ["transport-socket-owner"] + + class TestKeepaliveChunkFormats: """Tests for protocol-aware keepalive chunk emission.""" @@ -268,7 +346,9 @@ def test_static_sentinel_frame_carries_assistant_role(self): def test_id_sharing_frame_carries_assistant_role(self): from omlx.server import _chat_keepalive_chunk - assert self._first_chunk_role(_chat_keepalive_chunk("chatcmpl-x")) == "assistant" + assert ( + self._first_chunk_role(_chat_keepalive_chunk("chatcmpl-x")) == "assistant" + ) class TestResolveKeepalive: @@ -296,7 +376,9 @@ def test_chunk_mode_returns_protocol_specific_frames(self): try: self._set_mode("chunk") assert _resolve_keepalive("openai_chat") == _KEEPALIVE_CHAT_CHUNK - assert _resolve_keepalive("openai_completion") == _KEEPALIVE_COMPLETION_CHUNK + assert ( + _resolve_keepalive("openai_completion") == _KEEPALIVE_COMPLETION_CHUNK + ) assert _resolve_keepalive("anthropic") == _KEEPALIVE_ANTHROPIC_PING # Responses API has no official ping; chunk mode disables keepalive assert _resolve_keepalive("openai_responses") is None @@ -311,7 +393,12 @@ def test_comment_mode_returns_legacy_comment(self): original = _server_state.global_settings.server.sse_keepalive_mode try: self._set_mode("comment") - for protocol in ("openai_chat", "openai_completion", "anthropic", "openai_responses"): + for protocol in ( + "openai_chat", + "openai_completion", + "anthropic", + "openai_responses", + ): assert _resolve_keepalive(protocol) == _KEEPALIVE_COMMENT finally: _server_state.global_settings.server.sse_keepalive_mode = original @@ -324,7 +411,12 @@ def test_off_mode_returns_none(self): original = _server_state.global_settings.server.sse_keepalive_mode try: self._set_mode("off") - for protocol in ("openai_chat", "openai_completion", "anthropic", "openai_responses"): + for protocol in ( + "openai_chat", + "openai_completion", + "anthropic", + "openai_responses", + ): assert _resolve_keepalive(protocol) is None finally: _server_state.global_settings.server.sse_keepalive_mode = original diff --git a/tests/test_tool_calling.py b/tests/test_tool_calling.py index 76f7b45e21..6216233f91 100644 --- a/tests/test_tool_calling.py +++ b/tests/test_tool_calling.py @@ -781,6 +781,90 @@ def _make_tokenizer(tool_call_start=""): class TestToolCallStreamFilter: """Tests for ToolCallStreamFilter.""" + def test_complete_envelope_is_exposed_once_for_structured_streaming(self): + f = ToolCallStreamFilter( + _make_tokenizer(), + capture_ordered_segments=True, + ) + assert f.feed("") == "" + assert f.envelope_open + assert f.take_completed_envelopes() == [] + assert ( + f.feed( + "Seattle" + "" + ) + == "" + ) + assert not f.envelope_open + assert f.take_completed_envelopes() == [ + "" + "Seattle" + "" + ] + assert f.take_completed_envelopes() == [] + + def test_ordered_segments_preserve_content_call_content_fifo(self): + f = ToolCallStreamFilter( + _make_tokenizer(), + capture_ordered_segments=True, + ) + envelope = ( + "" + "Oslo" + ) + assert f.feed("before " + envelope + " after") == "before after" + segments = f.take_ordered_segments() + assert [(segment.kind, segment.text) for segment in segments] == [ + ("content", "before "), + ("envelope", envelope), + ("content", " after"), + ] + + def test_default_filter_does_not_retain_completed_envelope_copies(self): + f = ToolCallStreamFilter(_make_tokenizer()) + envelope = '{"name":"f","arguments":{}}' + assert f.feed(envelope) == "" + assert f.take_completed_envelopes() == [] + assert f.take_ordered_segments() == [] + + def test_seventeenth_queued_envelope_latches_off_eighteenth(self): + f = ToolCallStreamFilter( + _make_tokenizer(), + capture_ordered_segments=True, + ) + + def envelope(index): + return f"{{\"name\":\"f\",\"arguments\":{{\"i\":{index}}}}}" + + assert f.feed("".join(envelope(i) for i in range(17))) == "" + assert f.completed_envelope_overflowed + assert f.take_completed_envelopes() == [] + assert f.take_ordered_segments() == [] + assert f.feed(envelope(17)) == "" + assert f.take_completed_envelopes() == [] + assert f.take_ordered_segments() == [] + + def test_oversize_envelope_latches_off_later_valid_envelope(self): + f = ToolCallStreamFilter( + _make_tokenizer(), + capture_ordered_segments=True, + ) + oversize = ( + "" + + ("x" * (f._COMPLETED_ENVELOPE_MAX_BYTES + 1)) + + "" + ) + assert f.feed(oversize) == "" + assert f.completed_envelope_overflowed + assert f.take_completed_envelopes() == [] + assert f.take_ordered_segments() == [] + + later = '{"name":"f","arguments":{}}' + assert f.feed(later) == "" + assert f.take_completed_envelopes() == [] + assert f.take_ordered_segments() == [] + def test_no_marker_passthrough(self): """Without tokenizer marker, fallback envelopes are still active.""" f = ToolCallStreamFilter(_make_tokenizer())