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/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/catalogue.py b/omlx/cluster/catalogue.py index 4aae39864e..3507147cad 100644 --- a/omlx/cluster/catalogue.py +++ b/omlx/cluster/catalogue.py @@ -117,9 +117,7 @@ def context_is_limited(self) -> bool: """Does memory, not the model, set the usable context?""" declared = self.declared_context_tokens - return bool( - self.fits and declared and self.max_context_tokens < declared - ) + return bool(self.fits and declared and self.max_context_tokens < declared) def describe(self) -> str: """One line a person can act on.""" @@ -175,12 +173,17 @@ def _splits( *, tensor_parallel_ok: bool, pipeline_ok: bool = True, + prefer_tensor: bool = False, ) -> tuple[tuple[int, int], ...]: """Every (tensor_parallel_size, pipeline_stages) this cluster can form. - Ordered fewest-nodes-first, then pipeline before tensor parallelism at - equal width: pipeline loads faster, uses less memory, and survives a - slow link, so it is the better answer when both fit. + Ordered fewest-nodes-first. At equal width the default is pipeline before + tensor parallelism: pipeline loads faster, uses less memory, and survives + a slow link, so it is the better answer when both fit and nothing is + known about the link. ``prefer_tensor`` flips the tie-break for callers + that know every link is fast (JACCL/Thunderbolt): there, splitting each + layer's compute across the group cuts per-token latency, which is what a + user who just cabled two Macs together is after. """ options: list[tuple[int, int]] = [] @@ -196,7 +199,15 @@ def _splits( # weights and then fail at load. continue options.append((tp, used // tp)) - return tuple(sorted(options, key=lambda item: (item[0] * item[1], item[0]))) + return tuple( + sorted( + options, + key=lambda item: ( + item[0] * item[1], + -item[0] if prefer_tensor else item[0], + ), + ) + ) _SHORTFALL_RE = re.compile(r"\bat least (\d+) additional bytes required\b") @@ -340,11 +351,14 @@ def assess_model( tensor_parallel_ok: bool | None = None, pipeline_ok: bool | None = None, workload_profile: str = "balanced", + prefer_tensor: bool = False, ) -> ModelFit: """Whether this model runs here, using the fewest nodes that work. ``tensor_parallel_ok`` defaults to what the layout already determined, so a model mlx-lm cannot shard is never offered a tensor-parallel plan. + ``prefer_tensor`` requests the tensor-parallel split when both strategies + fit at equal width — callers set it when every link is known-fast. """ if tensor_parallel_ok is None: @@ -361,6 +375,7 @@ def assess_model( len(nodes), tensor_parallel_ok=tensor_parallel_ok, pipeline_ok=pipeline_ok, + prefer_tensor=prefer_tensor, ) for tp_size, stages in splits: used = tp_size * stages @@ -368,9 +383,7 @@ def assess_model( # them, which is where the fast links were placed. Ranks are positional # to the planner and must be contiguous from zero, so a subset — or a # caller's single node that happened to be rank 1 — is renumbered. - subset = [ - replace(node, rank=index) for index, node in enumerate(nodes[:used]) - ] + subset = [replace(node, rank=index) for index, node in enumerate(nodes[:used])] plan, reason = _plan_or_none( layout, subset, @@ -466,9 +479,7 @@ def assess_model( if standalone_node_id: failure_kind = "single_node_only" context = ( - f" at up to {standalone_context:,} tokens" - if standalone_context - else "" + f" at up to {standalone_context:,} tokens" if standalone_context else "" ) last_reason = ( "This model cannot combine Macs because mlx-lm supports neither " @@ -508,6 +519,7 @@ def assess_model_path( nodes: Sequence[NodeBudget], *, workload_profile: str = "balanced", + prefer_tensor: bool = False, ) -> ModelFit: """Assess a model directory, reading its real layout and config.""" @@ -536,6 +548,7 @@ def assess_model_path( model_id=root.name, declared_context_tokens=declared, workload_profile=workload_profile, + prefer_tensor=prefer_tensor, ) @@ -544,6 +557,7 @@ def catalogue_for_cluster( nodes: Sequence[NodeBudget], *, workload_profile: str = "balanced", + prefer_tensor: bool = False, ) -> tuple[ModelFit, ...]: """Assess every model, largest first among those that fit. @@ -553,7 +567,12 @@ def catalogue_for_cluster( """ fits = [ - assess_model_path(path, nodes, workload_profile=workload_profile) + assess_model_path( + path, + nodes, + workload_profile=workload_profile, + prefer_tensor=prefer_tensor, + ) for path in model_paths ] runnable = sorted( diff --git a/omlx/cluster/control_plane.py b/omlx/cluster/control_plane.py new file mode 100644 index 0000000000..9f0aee35b1 --- /dev/null +++ b/omlx/cluster/control_plane.py @@ -0,0 +1,330 @@ +# 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 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" +_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") +_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" + + +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 + + 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.""" + + 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 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 8f7f637abc..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 @@ -27,6 +28,15 @@ DistributedBackend = Literal["ring", "jaccl", "jaccl-ring"] +# Version 2 adds ``path_map``: an optional per-node absolute model path, so +# nodes no longer need the model at the same absolute path on every Mac. +# Version 1 payloads decode with an empty map, which reproduces the legacy +# shared-path behavior exactly. +DEPLOYMENT_SCHEMA_VERSION = 2 +_SUPPORTED_DEPLOYMENT_SCHEMAS = (1, DEPLOYMENT_SCHEMA_VERSION) +_MAX_PATH_MAP_ENTRIES = 64 +_MAX_MODEL_PATH_BYTES = 4096 + _SSH_TARGET = re.compile( r"^(?:[A-Za-z0-9._-]+@)?(?:[A-Za-z0-9._-]+|\[[0-9A-Fa-f:]+\])$" ) @@ -35,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 @@ -54,6 +97,11 @@ def validate_ssh_target(value: str) -> str: def _validate_ip(value: str) -> str: value = value.strip() + # macOS reports Thunderbolt/link-local addresses with a zone id + # (fe80::…%en10). mlx's address parser cannot read the suffix — a rank + # died at startup on exactly that — and a zone only means something on + # the machine that named it, so it never belongs on the wire. + value = value.split("%", 1)[0] try: ipaddress.ip_address(value) except ValueError as exc: @@ -61,6 +109,22 @@ def _validate_ip(value: str) -> str: return value +def _hostfile_ips(host: ClusterHost) -> list[str]: + """Communication IPs in the order a rank should try them. + + Routable addresses first: a link-local IPv6 without its (machine-local) + zone id is ambiguous, so it can only ever be a fallback. This is what + keeps a Mac that announces fe80:: Thunderbolt addresses alongside its + configured link IPs from advertising the unusable one first. + """ + + def _link_local(ip: str) -> bool: + return ipaddress.ip_address(ip).is_link_local + + routable = [ip for ip in host.ips if not _link_local(ip)] + return routable + [ip for ip in host.ips if _link_local(ip)] + + def _validate_rdma_path(value: Any) -> RDMAPath: if value is None: return None @@ -79,6 +143,48 @@ def _validate_rdma_path(value: Any) -> RDMAPath: raise ValueError("RDMA entries must be a device, a device list, or null") +def validate_model_path_map( + path_map: Any, + node_ids: tuple[str, ...] | None = None, +) -> dict[str, str]: + """Validate an optional per-node model path override map. + + Keys are cluster node IDs; values are absolute paths that exist only on + the node that resolves them, so no existence check happens here. An empty + map is the legacy "same absolute path on every node" behavior. + """ + + if path_map is None: + return {} + if not isinstance(path_map, dict): + raise ValueError("path_map must be an object mapping node IDs to paths") + if len(path_map) > _MAX_PATH_MAP_ENTRIES: + raise ValueError("path_map cannot hold more than 64 nodes") + known = set(node_ids) if node_ids is not None else None + validated: dict[str, str] = {} + for node_id, raw_path in path_map.items(): + if not isinstance(node_id, str) or _NODE_ID.fullmatch(node_id) is None: + raise ValueError(f"invalid path_map node ID: {node_id!r}") + if known is not None and node_id not in known: + raise ValueError( + f"path_map names a node outside the deployment: {node_id!r}" + ) + if not isinstance(raw_path, str): + raise ValueError(f"path_map path for {node_id!r} must be a string") + path = raw_path.strip() + if ( + not path + or "\x00" in path + or "\n" in path + or "\r" in path + or len(path.encode()) > _MAX_MODEL_PATH_BYTES + or not Path(path).is_absolute() + ): + raise ValueError(f"path_map path for {node_id!r} must be absolute") + validated[node_id] = path + return validated + + @dataclass(frozen=True) class ClusterHost: """One rank in an MLX hostfile.""" @@ -248,6 +354,10 @@ class ClusterDeployment: performance_profiles: tuple[NodePerformanceProfile, ...] = () tensor_parallel_size: int = 1 target_context_tokens: int = 8192 + # node_id → absolute model path on that node. Empty means every node uses + # ``model`` — the pre-v2 same-absolute-path requirement. Entries override + # only the nodes they name; the coordinator path stays the fallback. + path_map: dict[str, str] = field(default_factory=dict) def __post_init__(self) -> None: if _NODE_ID.fullmatch(self.deployment_id) is None: @@ -268,23 +378,27 @@ def __post_init__(self) -> None: "tensor_parallel_size must be between 1 and the host count" ) if len(self.hosts) % self.tensor_parallel_size != 0: - raise ValueError( - "host count must be divisible by tensor_parallel_size" - ) + raise ValueError("host count must be divisible by tensor_parallel_size") if ( not isinstance(self.target_context_tokens, int) or isinstance(self.target_context_tokens, bool) or not 1 <= self.target_context_tokens <= 1_048_576 ): - raise ValueError( - "target_context_tokens must be between 1 and 1,048,576" - ) + raise ValueError("target_context_tokens must be between 1 and 1,048,576") if len(self.assignments) != len(self.hosts): raise ValueError("host count must match pipeline assignment count") if self.hosts[0].ssh != "127.0.0.1": raise ValueError("rank 0 must use SSH target 127.0.0.1") if len({host.node_id for host in self.hosts}) != len(self.hosts): raise ValueError("cluster node IDs must be unique") + object.__setattr__( + self, + "path_map", + validate_model_path_map( + self.path_map, + tuple(host.node_id for host in self.hosts), + ), + ) if len(self.plan_hash) != 64 or any( char not in "0123456789abcdef" for char in self.plan_hash ): @@ -340,14 +454,23 @@ def world_size(self) -> int: def distributed_init_backend(self) -> str: return "jaccl" if self.backend.startswith("jaccl") else "ring" + def model_path_for(self, node_id: str) -> str: + """The model directory one rank loads, honouring per-node overrides. + + Nodes absent from ``path_map`` keep the coordinator's shared path, + which is exactly the legacy same-absolute-path behavior. + """ + + return self.path_map.get(node_id, self.model) + def hostfile_dict(self) -> dict[str, Any]: return { "backend": self.backend, - "envs": ["MLX_METAL_FAST_SYNCH=1"], + "envs": _hostfile_envs(), "hosts": [ { "ssh": host.ssh, - "ips": list(host.ips), + "ips": _hostfile_ips(host), "rdma": [ list(path) if isinstance(path, tuple) else path for path in host.rdma @@ -359,7 +482,7 @@ def hostfile_dict(self) -> dict[str, Any]: def to_dict(self) -> dict[str, Any]: return { - "schema_version": 1, + "schema_version": DEPLOYMENT_SCHEMA_VERSION, "deployment_id": self.deployment_id, "model": self.model, "backend": self.backend, @@ -373,11 +496,15 @@ def to_dict(self) -> dict[str, Any]: ], "tensor_parallel_size": self.tensor_parallel_size, "target_context_tokens": self.target_context_tokens, + "path_map": dict(sorted(self.path_map.items())), } @classmethod def from_dict(cls, payload: dict[str, Any]) -> ClusterDeployment: - if not isinstance(payload, dict) or payload.get("schema_version", 1) != 1: + if ( + not isinstance(payload, dict) + or payload.get("schema_version", 1) not in _SUPPORTED_DEPLOYMENT_SCHEMAS + ): raise ValueError("unsupported cluster deployment schema") hosts = payload.get("hosts") assignments = payload.get("assignments") @@ -414,6 +541,9 @@ def from_dict(cls, payload: dict[str, Any]) -> ClusterDeployment: ), tensor_parallel_size=int(payload.get("tensor_parallel_size", 1)), target_context_tokens=int(payload.get("target_context_tokens", 8192)), + # Schema 1 payloads predate per-node paths; they decode to the + # empty map, which is the shared-path behavior they ran with. + path_map=validate_model_path_map(payload.get("path_map")), ) def encode_worker_plan(self) -> str: @@ -421,7 +551,7 @@ def encode_worker_plan(self) -> str: raw = json.dumps( { - "schema_version": 1, + "schema_version": DEPLOYMENT_SCHEMA_VERSION, "plan_hash": self.plan_hash, "assignments": [ assignment.to_dict() for assignment in self.assignments @@ -430,6 +560,7 @@ def encode_worker_plan(self) -> str: profile.to_dict() for profile in self.performance_profiles ], "tensor_parallel_size": self.tensor_parallel_size, + "path_map": dict(sorted(self.path_map.items())), }, sort_keys=True, separators=(",", ":"), @@ -439,15 +570,8 @@ def encode_worker_plan(self) -> str: return base64.urlsafe_b64encode(zlib.compress(raw, level=9)).decode() -def decode_worker_contract( - encoded: str, -) -> tuple[ - str, - tuple[PipelineAssignment, ...], - tuple[NodePerformanceProfile, ...], - int, -]: - """Decode and validate the full worker contract without accepting code.""" +def _decode_worker_payload(encoded: str) -> dict[str, Any]: + """Inflate and validate a worker plan payload without accepting code.""" if not isinstance(encoded, str) or len(encoded) > _MAX_PLAN_BYTES * 2: raise ValueError("encoded pipeline plan is too large") @@ -470,7 +594,10 @@ def decode_worker_contract( payload = json.loads(raw) except (UnicodeDecodeError, json.JSONDecodeError) as exc: raise ValueError("pipeline plan is not valid JSON") from exc - if not isinstance(payload, dict) or payload.get("schema_version") != 1: + if ( + not isinstance(payload, dict) + or payload.get("schema_version") not in _SUPPORTED_DEPLOYMENT_SCHEMAS + ): raise ValueError("unsupported pipeline plan schema") plan_hash = payload.get("plan_hash") assignments = payload.get("assignments") @@ -485,13 +612,28 @@ def decode_worker_contract( char not in "0123456789abcdef" for char in plan_hash ): raise ValueError("pipeline plan hash is invalid") - parsed = tuple(_assignment_from_dict(item) for item in assignments) + return payload + + +def decode_worker_contract( + encoded: str, +) -> tuple[ + str, + tuple[PipelineAssignment, ...], + tuple[NodePerformanceProfile, ...], + int, +]: + """Decode and validate the full worker contract without accepting code.""" + + payload = _decode_worker_payload(encoded) + parsed = tuple(_assignment_from_dict(item) for item in payload["assignments"]) if [item.rank for item in sorted(parsed, key=lambda item: item.rank)] != list( range(len(parsed)) ): raise ValueError("pipeline plan ranks must be contiguous from zero") profiles = tuple( - NodePerformanceProfile.from_dict(item) for item in performance_profiles + NodePerformanceProfile.from_dict(item) + for item in payload.get("performance_profiles", []) ) if profiles and ( len(profiles) != len(parsed) @@ -501,8 +643,22 @@ def decode_worker_contract( raise ValueError("worker performance profiles do not match the shard plan") tensor_parallel_size = int(payload.get("tensor_parallel_size", 1)) if not 1 <= tensor_parallel_size <= len(parsed): - raise ValueError("tensor_parallel_size must be between 1 and the assignment count") - return plan_hash, parsed, profiles, tensor_parallel_size + raise ValueError( + "tensor_parallel_size must be between 1 and the assignment count" + ) + return payload["plan_hash"], parsed, profiles, tensor_parallel_size + + +def decode_worker_path_map(encoded: str) -> dict[str, str]: + """Per-node model path overrides carried inside the worker contract. + + Schema 1 contracts predate per-node paths and decode to an empty map; + callers then fall back to the shared ``--model`` argument, which is the + legacy behavior those contracts ran with. + """ + + payload = _decode_worker_payload(encoded) + return validate_model_path_map(payload.get("path_map")) def decode_worker_plan(encoded: str) -> tuple[str, tuple[PipelineAssignment, ...]]: diff --git a/omlx/cluster/inference_worker.py b/omlx/cluster/inference_worker.py index bf17ef5618..807582e9da 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 +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 = 120.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. @@ -481,23 +531,121 @@ def _prompt_cache_ssd_dir(args: argparse.Namespace, rank: int) -> str | None: return str(root / f"{args.deployment_id}-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. + """ + + payload: dict[str, Any] = { + "schema_version": 1, + "deployment_id": deployment_id, + "epoch": int(time.time() * 1000), + "scope": "all", + "reason": reason, + } + if plan_hash: + payload["plan_hash"] = plan_hash + try: + root = Path(state_dir).expanduser() + root.mkdir(parents=True, exist_ok=True) + path = root / f"{deployment_id}-cancel.json" + 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 +653,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 +775,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 +809,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, ) @@ -666,9 +893,9 @@ def _validate_loaded_stage( and start in (None, 0) and end in (None, len(layers)) ) - if ( - not expected_complete_tensor_stage - and (start, end) != (assignment.start_layer, assignment.end_layer) + if not expected_complete_tensor_stage and (start, end) != ( + assignment.start_layer, + assignment.end_layer, ): raise RuntimeError( "loaded model pipeline range does not match the approved plan: " @@ -959,7 +1186,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): @@ -970,6 +1207,15 @@ def run_worker(args: argparse.Namespace) -> int: if args.plan_hash != plan_hash: raise RuntimeError("worker plan hash does not match launch contract") + # Cluster v2: a deployment may give each node its own absolute model path. + # The rank's path comes from the signed contract's path_map; nodes without + # an entry keep the shared --model argument, the pre-v2 behavior. + path_map = decode_worker_path_map(args.plan) + if path_map: + rank_model_path = path_map.get(assignments[rank].node_id) + if rank_model_path and rank_model_path != args.model: + args.model = rank_model_path + marker = RuntimeMarker( state_dir=args.state_dir, deployment_id=args.deployment_id, @@ -987,7 +1233,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. @@ -1103,25 +1349,28 @@ def run_worker(args: argparse.Namespace) -> int: # it is checked again against what the rank actually holds, all the # way through the load. A rank that overruns dies here rather than # taking the Mac with it. - with watch_rank_load( - load_budget, - rank=rank, - node_id=getattr(assignment, "node_id", ""), - on_sample=lambda observed: marker.update( - "loading", - load_stage="loading_weights", - load_memory_bytes=observed, + with ( + watch_rank_load( + load_budget, + rank=rank, + node_id=getattr(assignment, "node_id", ""), + on_sample=lambda observed: marker.update( + "loading", + load_stage="loading_weights", + load_memory_bytes=observed, + ), ), - ), install_progressive_loader( - mlx_server, - progress=lambda progress: marker.update( - "loading", - load_stage=progress.get("phase", "materializing_layers"), - **{ - key: value - for key, value in progress.items() - if key != "phase" - }, + install_progressive_loader( + mlx_server, + progress=lambda progress: marker.update( + "loading", + load_stage=progress.get("phase", "materializing_layers"), + **{ + key: value + for key, value in progress.items() + if key != "phase" + }, + ), ), ): provider.load_default() @@ -1200,7 +1449,25 @@ def run_worker(args: argparse.Namespace) -> int: "optimizations": optimizations, } ) + _wait_for_serve_release( + args.state_dir, + args.deployment_id, + plan_hash, + world_size, + ) + 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, @@ -1211,9 +1478,7 @@ def run_worker(args: argparse.Namespace) -> int: provider.model, rank=rank, node_id=getattr(assignment, "node_id", ""), - layer_count=( - assignment.end_layer - assignment.start_layer - ), + layer_count=(assignment.end_layer - assignment.start_layer), tensor_parallel_size=assignment.tensor_parallel_size, memory_guard_tier=guard_tier, # The attention peak is set by the prefill chunk, so the @@ -1221,6 +1486,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, @@ -1253,6 +1519,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 @@ -1301,6 +1569,9 @@ 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("--trust-remote-code", action="store_true") parser.add_argument( "--execution-profile", @@ -1335,6 +1606,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 f3be0d47c0..b3c1df65df 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,152 @@ _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 +_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 +270,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 +980,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: @@ -227,9 +1056,7 @@ def _python_minor(version: str) -> tuple[str, str] | None: return (parts[0], parts[1]) -def _interpreter_parity( - local: str, remote: Any -) -> tuple[str | None, str | None]: +def _interpreter_parity(local: str, remote: Any) -> tuple[str | None, str | None]: """Compare the interpreter two ranks will actually run under (#2695). Returns ``(blocking, warning)``, at most one of which is set. @@ -284,8 +1111,7 @@ def _rank_python_module_argv( for rank, executable in enumerate(executables) ) script = ( - f'case "${{MLX_RANK:-}}" in {cases} *) exit 64;; esac; ' - 'exec "$omlx_python" "$@"' + f'case "${{MLX_RANK:-}}" in {cases} *) exit 64;; esac; exec "$omlx_python" "$@"' ) return ["/bin/sh", "-c", script, "omlx-rank-python", "-m", module] @@ -299,6 +1125,9 @@ 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, ) -> list[str]: """Build an argument vector without a user-controlled shell fragment. @@ -326,6 +1155,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") @@ -398,6 +1245,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( [ @@ -690,7 +1552,10 @@ def run_cuda_fabric_probe( raise DistributedLaunchError( f"CUDA fabric probe exited with code {completed.returncode}{suffix}" ) - if len(completed.stdout.encode()) + len(completed.stderr.encode()) > _REMOTE_OUTPUT_LIMIT: + if ( + len(completed.stdout.encode()) + len(completed.stderr.encode()) + > _REMOTE_OUTPUT_LIMIT + ): raise DistributedLaunchError("CUDA fabric probe output exceeded the safe limit") records: list[dict[str, Any]] = [] for line in completed.stdout.splitlines(): @@ -705,7 +1570,9 @@ def run_cuda_fabric_probe( raise DistributedLaunchError( "CUDA fabric probe did not return one result from each worker" ) - observed = min(float(record.get("payload_bytes_per_second") or 0) for record in records) + observed = min( + float(record.get("payload_bytes_per_second") or 0) for record in records + ) verified = observed >= minimum_bytes_per_second identity = "\0".join(sorted(host.ssh for host in hosts)).encode() group_id = f"connectx-{hashlib.sha256(identity).hexdigest()[:16]}" @@ -854,8 +1721,7 @@ def discover_remote_python_executable( # bare command name (``python3``) needs ``sys.executable`` to become an # absolute path. script = ( - "import os,omlx; print(os.path.expanduser(" - f"{candidate!r}))" + f"import os,omlx; print(os.path.expanduser({candidate!r}))" if candidate.startswith(("~", "/")) else "import sys,omlx; print(sys.executable)" ) @@ -1127,9 +1993,7 @@ def probe_remote_system_host( "ssh_reachable": True, "status": payload, "runtime_compatible": False, - "runtime_mismatches": [ - _RUNTIME_UNVERIFIED if evidence else _RUNTIME_MISSING - ], + "runtime_mismatches": [_RUNTIME_UNVERIFIED if evidence else _RUNTIME_MISSING], # Same keys as the healthy path, so a caller never has to know which # branch produced the result before reading it. "runtime_warnings": [], @@ -1458,7 +2322,10 @@ def preflight_remote_hosts( script = _PREFLIGHT_SCRIPT local_python_version = platform.python_version() results: list[dict[str, Any]] = [] - local_model_exists = Path(deployment.model).is_dir() + # Cluster v2: each rank validates against its own path_map entry; nodes + # without an entry share the coordinator path, as before v2. + local_model_path = deployment.model_path_for(deployment.hosts[0].node_id) + local_model_exists = Path(local_model_path).is_dir() assignments = sorted(deployment.assignments, key=lambda item: item.rank) if len(assignments) != len(deployment.hosts): raise DistributedLaunchError( @@ -1466,7 +2333,7 @@ def preflight_remote_hosts( ) local_validation = ( validate_staged_model( - deployment.model, + local_model_path, assignments[0].start_layer, assignments[0].end_layer, ) @@ -1478,9 +2345,7 @@ def preflight_remote_hosts( from .memory_guard import ceiling_breakdown local_admission_ceiling = int( - ceiling_breakdown( - assignments[0].memory_guard_tier - ).get("hard_limit", 0) + ceiling_breakdown(assignments[0].memory_guard_tier).get("hard_limit", 0) ) except Exception as exc: raise DistributedLaunchError( @@ -1513,15 +2378,18 @@ def preflight_remote_hosts( ) continue remote_python = host.python_executable or python_executable - # Send the ~-form: deployment.model is the coordinator's absolute path, - # which names nothing on a peer with a different macOS account. The - # preflight script expanduser()s it in the peer's own home. + # A path_map entry is already absolute on this peer. Without one, send + # the portable ~-form so peers with different macOS accounts resolve + # the model under their own home directory. + remote_model_path = deployment.path_map.get( + host.node_id, home_relative_model_path(deployment.model) + ) remote_command = shlex.join( [ remote_python, "-c", script, - home_relative_model_path(deployment.model), + remote_model_path, str(assignment.start_layer), str(assignment.end_layer), assignment.memory_guard_tier, @@ -1573,9 +2441,12 @@ def preflight_remote_hosts( runtime_warnings = [warning] if warning is not None else [] if versions.get("model-exists") is not True: mismatches.append( - f"model directory is missing on remote host: {deployment.model}" + f"model directory is missing on remote host: {remote_model_path}" ) - if local_identity is not None and versions.get("model_identity") != local_identity: + if ( + local_identity is not None + and versions.get("model_identity") != local_identity + ): mismatches.append( "model identity differs from the coordinator " "(config, tokenizer, processor, or weight index)" @@ -1641,9 +2512,7 @@ def _validate_deployment_admission( 0.0, min( 1.0, - ( - assignment.capacity_bytes - assignment.reserve_bytes - ) + (assignment.capacity_bytes - assignment.reserve_bytes) / assignment.capacity_bytes, ), ) @@ -1740,6 +2609,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 @@ -1757,12 +2628,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" @@ -1776,6 +2662,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, @@ -1784,6 +2676,9 @@ 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, ) self._phase = "loading" try: @@ -1803,14 +2698,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: @@ -1929,30 +2845,161 @@ 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()) - ) + process.wait(timeout=max(0.0, deadline - time.monotonic())) # mlx.launch can exit promptly while a local rank remains blocked # in a Metal/JACCL collective. Waiting only for the launcher left # 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) @@ -1967,10 +3014,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 @@ -2104,9 +3156,7 @@ def _reap_remote_ranks(self, *, runner: SSHRunner = subprocess.run) -> None: host.ssh, ) elif action in ("terminated", "killed"): - logger.info( - "reaped remote rank %d on %s (%s)", rank, host.ssh, action - ) + logger.info("reaped remote rank %d on %s (%s)", rank, host.ssh, action) elif action: logger.debug( "remote rank reap for rank %d on %s: %s", @@ -2116,8 +3166,7 @@ def _reap_remote_ranks(self, *, runner: SSHRunner = subprocess.run) -> None: ) else: logger.warning( - "remote rank reap for rank %d on %s returned no report " - "(exit %s)", + "remote rank reap for rank %d on %s returned no report (exit %s)", rank, host.ssh, completed.returncode, @@ -2148,9 +3197,7 @@ def _runtime_failure_reason(self) -> str | None: for rank, host in enumerate(self.deployment.hosts): filename = f"{self.deployment.deployment_id}-rank-{rank}.json" if host.ssh in _LOOPBACK_TARGETS: - marker = read_marker( - Path(self.state_dir).expanduser() / filename - ) + marker = read_marker(Path(self.state_dir).expanduser() / filename) else: remote_root = self.state_dir.rstrip("/") or "." marker, _, _, _ = read_remote_marker( @@ -2163,7 +3210,8 @@ def _runtime_failure_reason(self) -> str | None: marker.get("deployment_id") != self.deployment.deployment_id or marker.get("plan_hash") != self.deployment.plan_hash or marker.get("rank") != rank - or marker.get("phase") not in { + or marker.get("phase") + not in { "failed", "peer_lost", "launcher_lost", @@ -2172,9 +3220,7 @@ def _runtime_failure_reason(self) -> str | None: continue error = marker.get("error") if isinstance(error, str) and error.strip(): - failures.append( - f"rank {rank} ({host.node_id}): {error.strip()}" - ) + failures.append(f"rank {rank} ({host.node_id}): {error.strip()}") return "; ".join(failures)[:_LOG_LINE_LIMIT] or None def _failure_reason(self) -> str | None: 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/modelsync.py b/omlx/cluster/modelsync.py new file mode 100644 index 0000000000..3f71841a9b --- /dev/null +++ b/omlx/cluster/modelsync.py @@ -0,0 +1,863 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Model synchronization and per-node model paths for cluster v2. + +Two responsibilities: + +* A bounded, content-describing **manifest** for a locally-known model + (safetensors index hash + file list + total bytes), served to peers over + ``GET /api/cluster/models/{model_id}/manifest`` so a coordinator can answer + "does that node have this model?" without SSHing anywhere. +* A :class:`ModelSyncManager` that compares two manifests and then moves the + model, either over the enrolled SSH channel (``rsync``, resumable via + ``--partial --append-verify``) or as a per-node Hugging Face download of + only the files a shard needs (allow-patterns derived from the weight-map + index — the exo pattern). Progress events are emitted for the UI. + +All transports are injectable so unit tests never open a socket, run rsync, +or touch the Hugging Face hub. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import shlex +import subprocess +import threading +import time +from collections.abc import Callable, Iterable +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal + +from fastapi import APIRouter, HTTPException + +from ..exceptions import ModelNotFoundError +from .deployment import validate_ssh_target +from .ssh_policy import cluster_ssh_options +from .staging import ( + index_shards, + model_identity_digest, + shards_for_stage, + sidecar_files, +) + +SyncMethod = Literal["auto", "rsync", "download"] +SyncState = Literal["present", "missing", "partial", "mismatch"] + +#: Above this size ``method="auto"`` prefers a direct rsync over the enrolled +#: SSH channel; at or below it, each node downloads its own shard files. +AUTO_RSYNC_THRESHOLD_BYTES = 20 * 1024**3 + +_MANIFEST_TIMEOUT_SECONDS = 10.0 +_MAX_MODEL_ID_LENGTH = 4096 +_MAX_PROGRESS_EVENTS = 512 + +# ``rsync --info=progress2`` emits lines such as: +# " 1,234,567,890 42% 123.45MB/s 0:01:23" +_PROGRESS2 = re.compile( + r"^\s*(?P[\d,]+)\s+(?P\d+)%\s+" + r"(?P[\d.,]+)\s*(?P[KMGTP]?B)/s\s+" + r"(?P\d+:\d{2}(?::\d{2})?)" +) +_RATE_MULTIPLIERS = { + "B": 1, + "KB": 1000, + "MB": 1000**2, + "GB": 1000**3, + "TB": 1000**4, + "PB": 1000**5, +} + + +class ModelSyncError(RuntimeError): + """A sync operation could not start or finish.""" + + +@dataclass(frozen=True) +class ManifestFile: + """One file in a model directory: name and size, nothing else.""" + + name: str + size_bytes: int + + def to_dict(self) -> dict[str, Any]: + return {"name": self.name, "size_bytes": self.size_bytes} + + @classmethod + def from_dict(cls, payload: dict[str, Any]) -> ManifestFile: + return cls(name=str(payload["name"]), size_bytes=int(payload["size_bytes"])) + + +@dataclass(frozen=True) +class ModelManifest: + """Content description of one model directory, cheap to compute. + + Hashing every weight file would take minutes on a 300 GB model, so the + identity rests on the safetensors weight-map index plus the sidecar + digest staging already uses, with per-file sizes for drift detection. + """ + + model_id: str + path: str + index_sha256: str | None + identity_sha256: str + files: tuple[ManifestFile, ...] + total_bytes: int + source_repo_id: str | None = None + + def to_dict(self) -> dict[str, Any]: + return { + "schema_version": 1, + "model_id": self.model_id, + "path": self.path, + "index_sha256": self.index_sha256, + "identity_sha256": self.identity_sha256, + "files": [item.to_dict() for item in self.files], + "total_bytes": self.total_bytes, + "source_repo_id": self.source_repo_id, + } + + @classmethod + def from_dict(cls, payload: dict[str, Any]) -> ModelManifest: + if not isinstance(payload, dict) or payload.get("schema_version") != 1: + raise ValueError("unsupported model manifest schema") + files = payload.get("files") + if not isinstance(files, list): + raise ValueError("model manifest files must be an array") + return cls( + model_id=str(payload.get("model_id") or ""), + path=str(payload.get("path") or ""), + index_sha256=payload.get("index_sha256"), + identity_sha256=str(payload.get("identity_sha256") or ""), + files=tuple(ManifestFile.from_dict(item) for item in files), + total_bytes=int(payload.get("total_bytes") or 0), + source_repo_id=payload.get("source_repo_id"), + ) + + +@dataclass(frozen=True) +class SyncProgress: + """One progress event for the UI; bytes/s and ETA when measurable.""" + + model_id: str + peer: str + method: str + phase: Literal["checking", "transferring", "verifying", "done", "error"] + bytes_done: int = 0 + bytes_total: int = 0 + bytes_per_second: float | None = None + eta_seconds: float | None = None + detail: str = "" + at: float = field(default_factory=time.time) + + def to_dict(self) -> dict[str, Any]: + return { + "model_id": self.model_id, + "peer": self.peer, + "method": self.method, + "phase": self.phase, + "bytes_done": self.bytes_done, + "bytes_total": self.bytes_total, + "bytes_per_second": self.bytes_per_second, + "eta_seconds": self.eta_seconds, + "detail": self.detail, + "at": self.at, + } + + +def build_manifest( + model_path: str | Path, + *, + model_id: str | None = None, + source_repo_id: str | None = None, +) -> ModelManifest: + """Describe a local model directory for peer comparison.""" + + root = Path(model_path).expanduser() + if not root.is_dir(): + raise ValueError(f"model path is not a directory: {root}") + weights = sorted(root.glob("*.safetensors")) + if not weights: + raise ValueError(f"no safetensors weights found in {root}") + + index_path = root / "model.safetensors.index.json" + index_sha256 = ( + hashlib.sha256(index_path.read_bytes()).hexdigest() + if index_path.is_file() + else None + ) + files = [ + ManifestFile(name=path.name, size_bytes=path.stat().st_size) for path in weights + ] + for name in sidecar_files(root): + path = root / name + files.append(ManifestFile(name=name, size_bytes=path.stat().st_size)) + files.sort(key=lambda item: item.name) + return ModelManifest( + model_id=model_id or root.name, + path=str(root), + index_sha256=index_sha256, + identity_sha256=model_identity_digest(root), + files=tuple(files), + total_bytes=sum(item.size_bytes for item in files), + source_repo_id=source_repo_id, + ) + + +def allow_patterns_for_shard( + model_path: str | Path, + start_layer: int | None = None, + end_layer: int | None = None, +) -> tuple[str, ...]: + """HF ``allow_patterns`` for only the files one shard needs. + + Derived from the weight-map index (or shard headers when no index ships) + via the same layer→file map staging uses: layer-scoped shards for + ``[start_layer, end_layer)`` plus the shared sidecars. With no layer + range, the pattern list covers the whole model. + """ + + shards = index_shards(model_path) + if start_layer is not None and end_layer is not None: + if not 0 <= start_layer < end_layer: + raise ValueError("shard layer range must satisfy 0 <= start < end") + shards = shards_for_stage(shards, start_layer, end_layer) + patterns = {shard.name for shard in shards} + patterns.update(sidecar_files(model_path)) + return tuple(sorted(patterns)) + + +def compare_manifests( + local: ModelManifest, peer: ModelManifest | None +) -> dict[str, Any]: + """Whether ``peer`` can serve the model ``local`` describes. + + * ``missing`` — the peer answered 404 or is unreachable. + * ``mismatch`` — the peer has a different model (weight-map index hash or + sidecar identity differs). + * ``partial`` — same model, but files are absent or truncated. + * ``present`` — every file is there at the expected size. + """ + + if peer is None: + return { + "state": "missing", + "bytes": 0, + "total_bytes": local.total_bytes, + "missing": [item.name for item in local.files], + } + if ( + local.index_sha256 is not None + and peer.index_sha256 is not None + and local.index_sha256 != peer.index_sha256 + ) or local.identity_sha256 != peer.identity_sha256: + return { + "state": "mismatch", + "bytes": 0, + "total_bytes": local.total_bytes, + "missing": [item.name for item in local.files], + } + peer_sizes = {item.name: item.size_bytes for item in peer.files} + missing = [ + item.name + for item in local.files + if peer_sizes.get(item.name) != item.size_bytes + ] + matched = sum( + item.size_bytes for item in local.files if item.name not in set(missing) + ) + return { + "state": "partial" if missing else "present", + "bytes": matched, + "total_bytes": local.total_bytes, + "missing": missing, + } + + +def parse_rsync_progress(line: str) -> tuple[int, float, float] | None: + """Parse one ``--info=progress2`` line → (bytes_done, bytes/s, eta_s).""" + + match = _PROGRESS2.match(line.strip()) + if match is None: + return None + done = int(match.group("bytes").replace(",", "")) + rate = ( + float(match.group("rate").replace(",", "")) + * _RATE_MULTIPLIERS[match.group("unit")] + ) + parts = [int(part) for part in match.group("eta").split(":")] + eta = ( + parts[0] * 3600 + parts[1] * 60 + parts[2] + if len(parts) == 3 + else (parts[0] * 60 + parts[1]) + ) + return done, rate, float(eta) + + +def build_rsync_argv( + source_dir: str | Path, + ssh_target: str, + destination_dir: str | Path, + *, + ssh_identity: str | Path | None = None, +) -> list[str]: + """A resumable rsync over the enrolled SSH channel. + + ``--partial --append-verify`` resumes interrupted transfers and verifies + the appended bytes, the functional equivalent of ``-P --append-verify`` + without the interactive progress format. The SSH transport uses the one + shared non-interactive cluster policy (managed identity, accept-new + host keys, BatchMode) — never a hand-rolled option set. + """ + + ssh_target = validate_ssh_target(ssh_target) + target_dir = str(destination_dir) + if ( + not Path(target_dir).is_absolute() + or "\x00" in target_dir + or "\n" in target_dir + or "\r" in target_dir + ): + raise ValueError("rsync destination must be an absolute single-line path") + ssh_argv = ["ssh", *cluster_ssh_options()] + if ssh_identity is not None: + ssh_argv.extend(["-i", str(ssh_identity)]) + source = str(Path(source_dir).expanduser()).rstrip("/") + "/" + # macOS ships openrsync 2.6.9 without --protect-args/-s. Quote the remote + # path inside the host:path operand so the peer shell receives one literal + # filename while retaining compatibility with the system binary. + destination = f"{ssh_target}:{shlex.quote(target_dir)}" + return [ + "rsync", + "-a", + "--partial", + "--append-verify", + "--info=progress2", + "-e", + shlex.join(ssh_argv), + source, + destination, + ] + + +def _default_ssh_trust(ssh_target: str) -> bool: + """Whether the dedicated cluster key exists for non-interactive SSH.""" + + del ssh_target # the key is shared; the target itself is probed at launch + return (Path.home() / ".ssh" / "omlx_cluster").is_file() + + +def _default_hf_download( + *, + repo_id: str, + allow_patterns: Iterable[str], + local_dir: str | Path, +) -> None: + try: + from huggingface_hub import snapshot_download + except ImportError as exc: + raise ModelSyncError( + "huggingface_hub is not installed on this node; install it or use " + "method='rsync' to copy the model from the coordinator instead" + ) from exc + snapshot_download( + repo_id=repo_id, + allow_patterns=list(allow_patterns), + local_dir=str(local_dir), + ) + + +def _normalize_peer_url(peer: str) -> str: + peer = peer.strip() + if not peer: + raise ValueError("peer must be a host:port or http(s) URL") + if "://" not in peer: + if ":" not in peer.rsplit("]", 1)[-1]: + raise ValueError(f"peer {peer!r} has no port; use host:port or a full URL") + peer = f"http://{peer}" + return peer.rstrip("/") + + +class ModelSyncManager: + """Compare and synchronize model files between cluster nodes. + + Every transport is injectable: ``http_fetch`` for peer manifests, + ``ssh_trust`` for the auto-method decision, ``rsync_run`` for the copy, + and ``hf_download`` for per-node downloads. Tests inject fakes; the + defaults are the real thing and are never exercised offline. + """ + + def __init__( + self, + *, + http_fetch: Callable[[str, float], dict[str, Any] | None] | None = None, + ssh_trust: Callable[[str], bool] | None = None, + rsync_run: Callable[..., int] | None = None, + hf_download: Callable[..., None] | None = None, + pool_getter: Callable[[], Any] | None = None, + settings_loader: Callable[[], Any] | None = None, + manifest_timeout: float = _MANIFEST_TIMEOUT_SECONDS, + ) -> None: + self._http_fetch = http_fetch or self._default_http_fetch + self._ssh_trust = ssh_trust or _default_ssh_trust + self._rsync_run = rsync_run or self._default_rsync_run + self._hf_download = hf_download or _default_hf_download + self._pool_getter = pool_getter + self._settings_loader = settings_loader + self._manifest_timeout = manifest_timeout + self._events: list[SyncProgress] = [] + self._lock = threading.Lock() + + # -- model resolution ------------------------------------------------ + + def resolve_local_model_path(self, model_id: str) -> Path: + """Resolve a model ID, repo ID, or path to a local directory.""" + + if not model_id or len(model_id) > _MAX_MODEL_ID_LENGTH or "\x00" in model_id: + raise ModelNotFoundError(model_id or "", []) + candidate = Path(model_id).expanduser() + if candidate.is_dir(): + return candidate.resolve() + pool = self._pool_getter() if self._pool_getter is not None else None + if pool is not None: + status = pool.get_status() + for item in status.get("models", []) if isinstance(status, dict) else []: + if not isinstance(item, dict): + continue + if model_id in { + item.get("id"), + item.get("source_repo_id"), + item.get("model_path"), + }: + path = Path(str(item["model_path"])).expanduser() + if path.is_dir(): + return path.resolve() + settings = ( + self._settings_loader() if self._settings_loader is not None else None + ) + if settings is not None: + from ..model_discovery import discover_models_from_dirs + + model_dirs = [ + Path(entry).expanduser() + for entry in settings.get_effective_model_dirs() + ] + discovered = discover_models_from_dirs(model_dirs) + for key, entry in discovered.items(): + if model_id in {key, entry.model_id, entry.source_repo_id}: + path = Path(entry.model_path).expanduser() + if path.is_dir(): + return path.resolve() + raise ModelNotFoundError(model_id, []) + + def local_manifest(self, model_id: str) -> ModelManifest: + path = self.resolve_local_model_path(model_id) + source_repo_id = None if Path(model_id).expanduser().is_dir() else model_id + return build_manifest(path, model_id=model_id, source_repo_id=source_repo_id) + + # -- peer manifest ---------------------------------------------------- + + @staticmethod + def _default_http_fetch(url: str, timeout: float) -> dict[str, Any] | None: + import urllib.error + import urllib.request + + request = urllib.request.Request(url, headers={"Accept": "application/json"}) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + return json.loads(response.read().decode()) + except urllib.error.HTTPError as exc: + if exc.code == 404: + return None + raise ModelSyncError( + f"peer manifest request failed: HTTP {exc.code}" + ) from exc + except (OSError, urllib.error.URLError) as exc: + raise ModelSyncError(f"peer is unreachable: {exc}") from exc + + def peer_manifest(self, peer: str, model_id: str) -> ModelManifest | None: + """Fetch a peer's manifest; ``None`` when the model is unknown there.""" + + base = _normalize_peer_url(peer) + payload = self._http_fetch( + f"{base}/api/cluster/models/{model_id}/manifest", + self._manifest_timeout, + ) + if payload is None: + return None + try: + return ModelManifest.from_dict(payload) + except (KeyError, TypeError, ValueError) as exc: + raise ModelSyncError(f"peer returned an invalid manifest: {exc}") from exc + + def status( + self, + peer: str, + model_id: str, + *, + local: ModelManifest | None = None, + ) -> dict[str, Any]: + """{state: present|missing|partial|mismatch, bytes} for a peer.""" + + local = local or self.local_manifest(model_id) + result = compare_manifests(local, self.peer_manifest(peer, model_id)) + result["peer"] = peer + result["model_id"] = model_id + return result + + # -- sync -------------------------------------------------------------- + + def decide_method( + self, + ssh_target: str | None, + total_bytes: int, + ) -> Literal["rsync", "download"]: + """auto = rsync when SSH trust exists AND the model is over 20 GB.""" + + if ( + ssh_target + and total_bytes > AUTO_RSYNC_THRESHOLD_BYTES + and self._ssh_trust(ssh_target) + ): + return "rsync" + return "download" + + def sync( + self, + peer: str, + model_id: str, + method: SyncMethod = "auto", + *, + ssh_target: str | None = None, + destination: str | Path | None = None, + repo_id: str | None = None, + start_layer: int | None = None, + end_layer: int | None = None, + on_progress: Callable[[SyncProgress], None] | None = None, + ) -> dict[str, Any]: + """Bring ``peer`` (or a local destination) to ``present`` for a model. + + ``rsync`` copies the local model directory to ``ssh_target:destination`` + over the enrolled channel. ``download`` fetches only shard-needed files + from the Hugging Face hub into ``destination`` on this node (run the + same call on each node, exo-style). Progress events are emitted to + ``on_progress`` and retained in :attr:`events` for UI polling. + """ + + if method not in {"auto", "rsync", "download"}: + raise ValueError(f"unsupported sync method: {method!r}") + local = self.local_manifest(model_id) + chosen = ( + self.decide_method(ssh_target, local.total_bytes) + if method == "auto" + else method + ) + self._emit( + on_progress, + local.model_id, + peer, + chosen, + "checking", + bytes_total=local.total_bytes, + detail="comparing manifests", + ) + try: + if chosen == "rsync": + result = self._sync_rsync( + local, peer, ssh_target, destination, on_progress + ) + else: + result = self._sync_download( + local, + model_id, + peer, + destination, + repo_id, + start_layer, + end_layer, + on_progress, + ) + except Exception as exc: + self._emit( + on_progress, + local.model_id, + peer, + chosen, + "error", + bytes_total=local.total_bytes, + detail=str(exc)[:500], + ) + raise + self._emit( + on_progress, + local.model_id, + peer, + chosen, + "done", + bytes_done=local.total_bytes, + bytes_total=local.total_bytes, + ) + return result + + def _sync_rsync( + self, + local: ModelManifest, + peer: str, + ssh_target: str | None, + destination: str | Path | None, + on_progress: Callable[[SyncProgress], None] | None, + ) -> dict[str, Any]: + if not ssh_target: + raise ModelSyncError( + "rsync sync needs ssh_target (the enrolled SSH destination)" + ) + if not self._ssh_trust(ssh_target): + raise ModelSyncError( + f"no enrolled SSH trust for {ssh_target}; pair the nodes first " + "or use method='download'" + ) + # Without an explicit destination the peer keeps the coordinator's + # absolute path — the legacy shared-path layout, still the default + # until a path_map says otherwise. + target_dir = str(destination or local.path) + argv = build_rsync_argv(local.path, ssh_target, target_dir) + + def progress(done: int, rate: float, eta: float) -> None: + self._emit( + on_progress, + local.model_id, + peer, + "rsync", + "transferring", + bytes_done=done, + bytes_total=local.total_bytes, + bytes_per_second=rate, + eta_seconds=eta, + ) + + rc = self._rsync_run(argv, on_line=self._progress_line_parser(progress)) + if rc != 0: + raise ModelSyncError(f"rsync to {ssh_target} exited with status {rc}") + self._emit( + on_progress, + local.model_id, + peer, + "rsync", + "verifying", + bytes_total=local.total_bytes, + detail="verifying peer manifest", + ) + return { + "method": "rsync", + "peer": peer, + "ssh_target": ssh_target, + "destination": target_dir, + "bytes": local.total_bytes, + } + + def _sync_download( + self, + local: ModelManifest, + model_id: str, + peer: str, + destination: str | Path | None, + repo_id: str | None, + start_layer: int | None, + end_layer: int | None, + on_progress: Callable[[SyncProgress], None] | None, + ) -> dict[str, Any]: + repo = repo_id or local.source_repo_id + if not repo or Path(repo).expanduser().is_dir(): + raise ModelSyncError( + "download sync needs the model's Hugging Face repo ID; the " + "local copy has no repository reference, use method='rsync'" + ) + if destination is None: + raise ModelSyncError( + "download sync needs a destination directory on this node" + ) + patterns = allow_patterns_for_shard(local.path, start_layer, end_layer) + self._emit( + on_progress, + local.model_id, + peer, + "download", + "transferring", + bytes_total=local.total_bytes, + detail=f"fetching {len(patterns)} files from {repo}", + ) + self._hf_download( + repo_id=repo, + allow_patterns=patterns, + local_dir=destination, + ) + return { + "method": "download", + "peer": peer, + "repo_id": repo, + "destination": str(destination), + "allow_patterns": list(patterns), + "bytes": local.total_bytes, + } + + # -- progress plumbing --------------------------------------------------- + + @staticmethod + def _progress_line_parser( + progress: Callable[[int, float, float], None], + ) -> Callable[[str], None]: + def parse(line: str) -> None: + parsed = parse_rsync_progress(line) + if parsed is not None: + progress(*parsed) + + return parse + + @staticmethod + def _default_rsync_run(argv: list[str], on_line: Callable[[str], None]) -> int: + process = subprocess.Popen( + argv, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + assert process.stdout is not None + for line in process.stdout: + on_line(line) + return process.wait() + + def _emit( + self, + on_progress: Callable[[SyncProgress], None] | None, + model_id: str, + peer: str, + method: str, + phase: str, + **fields: Any, + ) -> SyncProgress: + event = SyncProgress( + model_id=model_id, + peer=peer, + method=method, + phase=phase, # type: ignore[arg-type] + **fields, + ) + with self._lock: + self._events.append(event) + if len(self._events) > _MAX_PROGRESS_EVENTS: + del self._events[: len(self._events) - _MAX_PROGRESS_EVENTS] + if on_progress is not None: + on_progress(event) + return event + + @property + def events(self) -> tuple[SyncProgress, ...]: + """Bounded recent progress history for UI polling.""" + + with self._lock: + return tuple(self._events) + + +# -- manifest endpoint ------------------------------------------------------ + +manifest_router = APIRouter(prefix="/api/cluster", tags=["cluster-modelsync"]) + +_pool_getter: Callable[[], Any] | None = None +_settings_loader: Callable[[], Any] | None = None + + +def set_modelsync_getters( + engine_pool_getter: Callable[[], Any] | None = None, + settings_loader: Callable[[], Any] | None = None, +) -> None: + """Inject server-owned dependencies without importing ``omlx.server``.""" + + global _pool_getter, _settings_loader + _pool_getter = engine_pool_getter + _settings_loader = settings_loader + + +def _default_settings_loader() -> Any: + from ..settings import GlobalSettings + + return GlobalSettings.load() + + +def _manager() -> ModelSyncManager: + return ModelSyncManager( + pool_getter=_pool_getter, + settings_loader=_settings_loader or _default_settings_loader, + ) + + +def _allowed_model_roots() -> tuple[Path, ...]: + try: + settings = (_settings_loader or _default_settings_loader)() + return tuple( + Path(entry).expanduser().resolve() + for entry in settings.get_effective_model_dirs() + ) + except Exception: # noqa: BLE001 - a broken settings file must not 500 here + return () + + +def _guard_manifest_path(path: Path) -> None: + """Path-typed model IDs stay inside the configured model directories. + + Repo-style IDs are resolved through the engine pool / discovery, which + already only surfaces registered models. A raw path must not let an admin + token enumerate arbitrary directories. + """ + + roots = _allowed_model_roots() + if not roots: + return + if not any(root == path or root in path.parents for root in roots): + raise HTTPException( + status_code=403, + detail="model path is outside the configured model directories", + ) + + +@manifest_router.get("/models/{model_id:path}/manifest") +async def cluster_model_manifest(model_id: str) -> dict[str, Any]: + """Safetensors index hash + file list + total bytes for a local model. + + Peers call this to decide whether they must sync before activation; the + payload is names and sizes only — never weights, never credentials. + """ + + import asyncio + + manager = _manager() + try: + path = manager.resolve_local_model_path(model_id) + except ModelNotFoundError as exc: + raise HTTPException( + status_code=404, detail=f"unknown model: {model_id}" + ) from exc + _guard_manifest_path(path) + try: + manifest = await asyncio.to_thread(build_manifest, path, model_id=model_id) + except ValueError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + return manifest.to_dict() + + +__all__ = [ + "AUTO_RSYNC_THRESHOLD_BYTES", + "ManifestFile", + "ModelManifest", + "ModelSyncError", + "ModelSyncManager", + "SyncProgress", + "allow_patterns_for_shard", + "build_manifest", + "build_rsync_argv", + "compare_manifests", + "manifest_router", + "parse_rsync_progress", + "set_modelsync_getters", +] 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/planner.py b/omlx/cluster/planner.py index cdc31edecf..31069da1e5 100644 --- a/omlx/cluster/planner.py +++ b/omlx/cluster/planner.py @@ -11,7 +11,8 @@ import threading from collections.abc import Iterator, Sequence from contextlib import contextmanager -from dataclasses import dataclass, replace +from dataclasses import dataclass, field, replace +from fractions import Fraction from pathlib import Path from typing import Any @@ -54,16 +55,13 @@ def normalize_node_role(value: Any) -> str: if value is None: return "" if not isinstance(value, str): - raise ValueError( - f"node role must be a string, got {type(value).__name__}" - ) + raise ValueError(f"node role must be a string, got {type(value).__name__}") text = value.strip().lower() if not text: return "" if text not in ROLES: raise ValueError( - f"unknown node role: {value!r} (expected one of " - f"{', '.join(sorted(ROLES))})" + f"unknown node role: {value!r} (expected one of {', '.join(sorted(ROLES))})" ) return text @@ -213,8 +211,7 @@ def from_dict(cls, payload: dict[str, Any]) -> ModelLayout: payload.get("tensor_parallel_kv_heads", 0) ), tensor_parallel_divisors=tuple( - int(value) - for value in payload.get("tensor_parallel_divisors", ()) + int(value) for value in payload.get("tensor_parallel_divisors", ()) ), kv_bytes_per_token_per_layer=int( payload.get("kv_bytes_per_token_per_layer", 0) @@ -426,6 +423,11 @@ class ShardPlan: # case the per-rank byte reservation is zero, but the operator's requested # runtime limit must still be visible and part of the plan identity. target_context_tokens: int = _DEFAULT_CONTEXT_TOKENS + # node_id → absolute model path on that node (cluster v2). Display and + # staging metadata only: the layer split is path-independent, so the map + # is deliberately excluded from ``plan_hash``. Empty means every node + # loads the shared coordinator path — the legacy behavior. + path_map: dict[str, str] = field(default_factory=dict) @property def max_context_tokens(self) -> int: @@ -458,7 +460,7 @@ def cluster_resident_weight_bytes(self) -> int: return sum(item.planned_weight_bytes for item in self.assignments) def to_dict(self) -> dict[str, Any]: - return { + result = { "plan_version": 1, "plan_hash": self.plan_hash, "strategy": ( @@ -484,6 +486,9 @@ def to_dict(self) -> dict[str, Any]: "tensor_parallel_size": self.tensor_parallel_size, "pipeline_stages": self.pipeline_stages, } + if self.path_map: + result["path_map"] = dict(sorted(self.path_map.items())) + return result def synthetic_model_layout(*, total_weight_bytes: int, layer_count: int) -> ModelLayout: @@ -677,9 +682,9 @@ def _tensor_parallel_divisors(config: dict[str, Any]) -> tuple[int, ...]: // max(_config_int(config, "num_attention_heads", 1), 1) ) attn_dim = _config_int(config, "num_attention_heads", 0) * head_dim - mamba_dim = _config_int( - config, "mamba_num_heads", 0 - ) * _config_int(config, "mamba_head_dim", 0) + mamba_dim = _config_int(config, "mamba_num_heads", 0) * _config_int( + config, "mamba_head_dim", 0 + ) shared_dim = _config_int( config, "moe_shared_expert_intermediate_size", @@ -868,11 +873,7 @@ def _kv_bytes_per_token_per_layer(config: dict[str, Any]) -> int: head_dim = _config_int(config, "head_dim", 0) if head_dim <= 0: hidden = _config_int(config, "hidden_size", 0, maximum=1_000_000) - head_dim = ( - hidden // heads - if hidden and heads and hidden % heads == 0 - else 0 - ) + head_dim = hidden // heads if hidden and heads and hidden % heads == 0 else 0 if head_dim > 4096: return 0 if kv_heads <= 0 or head_dim <= 0: @@ -1053,14 +1054,10 @@ def inspect_safetensors_layout(model_path: str | Path) -> ModelLayout: # the runtime model never instantiates them. Counting them as decoder # layers put a stage boundary over weights that do not exist at runtime, # and the last stage failed activation with end_layer beyond the model. - declared_depth = _config_int( - _model_config(root), "num_hidden_layers", 0 - ) + declared_depth = _config_int(_model_config(root), "num_hidden_layers", 0) if declared_depth > 0 and max(layer_sizes) >= declared_depth: trimmed = { - index: size - for index, size in layer_sizes.items() - if index < declared_depth + index: size for index, size in layer_sizes.items() if index < declared_depth } if trimmed: layer_sizes = trimmed @@ -1087,12 +1084,8 @@ def inspect_safetensors_layout(model_path: str | Path) -> ModelLayout: tensor_parallel_divisors=_tensor_parallel_divisors(_model_config(root)), supports_tensor_parallel=_supports_tensor_parallel(_model_config(root)), supports_pipeline=_supports_pipeline(_model_config(root)), - kv_bytes_per_token_per_layer=_kv_bytes_per_token_per_layer( - _model_config(root) - ), - kv_replicated_across_tp=_kv_cache_replicated_across_tp( - _model_config(root) - ), + kv_bytes_per_token_per_layer=_kv_bytes_per_token_per_layer(_model_config(root)), + kv_replicated_across_tp=_kv_cache_replicated_across_tp(_model_config(root)), ) @@ -1330,9 +1323,7 @@ def _partition_layers( start = previous_end for end in range(max(start + 1, minimum_end), maximum_end + 1): layer_bytes = weight_prefix[end] - weight_prefix[start] - resident_layer_bytes = ( - resident_prefix[end] - resident_prefix[start] - ) + resident_layer_bytes = resident_prefix[end] - resident_prefix[start] planned_weight_bytes = fixed_weight_bytes + layer_bytes planned_resident_bytes = fixed_weight_bytes + resident_layer_bytes if planned_weight_bytes > node.weight_ceiling_bytes: @@ -1356,14 +1347,12 @@ def _partition_layers( previous_score[score_offset + 1] + stage_seconds * stage_seconds, max(previous_score[score_offset + 2], utilization), - previous_score[score_offset + 3] - + utilization * utilization, + previous_score[score_offset + 3] + utilization * utilization, ) else: score = ( max(previous_score[score_offset], utilization), - previous_score[score_offset + 1] - + utilization * utilization, + previous_score[score_offset + 1] + utilization * utilization, ) if target_aware: target = node.target_weight_bytes @@ -1386,8 +1375,7 @@ def _partition_layers( final = states.get(layer_count) if final is None: resident_capacity = sum( - max(0, node.usable_bytes - fixed_weight_bytes) - for node in pipeline_nodes + max(0, node.usable_bytes - fixed_weight_bytes) for node in pipeline_nodes ) weight_capacity = sum( max(0, node.weight_ceiling_bytes - fixed_weight_bytes) @@ -1443,15 +1431,13 @@ def _predict_stage_seconds( return compute_seconds, send_seconds, compute_seconds + send_seconds -def plan_unequal_pipeline( +def _validate_pipeline_request( model: ModelLayout, nodes: Sequence[NodeBudget], - *, - workload_profile: ExecutionProfileName = "balanced", - microbatch_size: int = 1, - context_tokens: int = _DEFAULT_CONTEXT_TOKENS, -) -> ShardPlan: - """Assign contiguous layers in MLX pipeline order across unequal nodes.""" + workload_profile: ExecutionProfileName, + microbatch_size: int, +) -> None: + """The input contract every pipeline planner enforces identically.""" if not nodes: raise ValueError("at least one node is required") @@ -1475,6 +1461,19 @@ def plan_unequal_pipeline( f"replicated fixed weights do not fit node {node.node_id}" ) + +def plan_unequal_pipeline( + model: ModelLayout, + nodes: Sequence[NodeBudget], + *, + workload_profile: ExecutionProfileName = "balanced", + microbatch_size: int = 1, + context_tokens: int = _DEFAULT_CONTEXT_TOKENS, +) -> ShardPlan: + """Assign contiguous layers in MLX pipeline order across unequal nodes.""" + + _validate_pipeline_request(model, nodes, workload_profile, microbatch_size) + # MLX-LM sends activations from the highest rank (early layers) down to # rank zero (late layers / HTTP coordinator), so partition in reverse rank. pipeline_nodes = tuple(sorted(nodes, key=lambda item: item.rank, reverse=True)) @@ -1500,6 +1499,132 @@ def plan_unequal_pipeline( f"fit the supplied per-node budgets: {exc}" ) from exc raise + return _finish_pipeline_plan( + model, + nodes, + pipeline_nodes, + ranges, + workload_profile=workload_profile, + microbatch_size=microbatch_size, + context_tokens=context_tokens, + optimization="performance" if performance_aware else "memory", + ) + + +def allocate_layers_proportional( + layer_count: int, + shares: Sequence[int], +) -> tuple[int, ...]: + """Split ``layer_count`` across nodes proportionally to ``shares``. + + Largest-remainder rounding with a one-layer minimum per node — the + allocation rule exo's placement uses, so a 256 GB + 128 GB pair splits + roughly ⅔–⅓. Fractions are exact (no float drift) and ties break toward + the larger share, then the earlier pipeline position, so the result is + deterministic and reproducible across machines. + """ + + if not isinstance(layer_count, int) or layer_count <= 0: + raise ValueError("layer_count must be a positive integer") + if not shares: + raise ValueError("at least one share is required") + for share in shares: + if not isinstance(share, int) or isinstance(share, bool) or share <= 0: + raise ValueError("shares must be positive integers") + node_count = len(shares) + if node_count > layer_count: + raise PlanningError( + f"{node_count} nodes cannot each receive a layer from {layer_count} layers" + ) + total = sum(shares) + exact = [Fraction(layer_count * share, total) for share in shares] + counts = [max(1, value.numerator // value.denominator) for value in exact] + remainder = layer_count - sum(counts) + # Σfloor(exact) ≤ layer_count and the one-layer floor adds at most one per + # node that floored to zero, so ``remainder`` is never negative. + assert remainder >= 0 + order = sorted( + range(node_count), + key=lambda index: ( + -(exact[index] - counts[index]), + -shares[index], + index, + ), + ) + for index in order[:remainder]: + counts[index] += 1 + return tuple(counts) + + +def plan_proportional_pipeline( + model: ModelLayout, + nodes: Sequence[NodeBudget], + *, + workload_profile: ExecutionProfileName = "balanced", + microbatch_size: int = 1, + context_tokens: int = _DEFAULT_CONTEXT_TOKENS, +) -> ShardPlan: + """RAM-proportional N-node pipeline plan (largest-remainder, exo-style). + + Layer counts are proportional to each node's usable memory + (``capacity − reserve``), rounded by largest remainder. Unlike the + balanced planner this does not optimize for the bottleneck stage or honor + soft weight targets — it is the predictable "split by RAM" rule operators + expect when generalizing beyond two nodes. Per-node weight ceilings (the + split control) and KV reservations are still enforced: a node whose + proportional share does not fit fails the plan with its name, rather than + being silently rebalanced. + """ + + _validate_pipeline_request(model, nodes, workload_profile, microbatch_size) + + pipeline_nodes = tuple(sorted(nodes, key=lambda item: item.rank, reverse=True)) + counts = allocate_layers_proportional( + len(model.layer_weight_bytes), + [node.usable_bytes for node in pipeline_nodes], + ) + ranges: list[tuple[int, int]] = [] + start = 0 + for count in counts: + ranges.append((start, start + count)) + start += count + for node, (range_start, range_end) in zip(pipeline_nodes, ranges): + layer_weight = sum(model.layer_weight_bytes[range_start:range_end]) + if model.fixed_weight_bytes + layer_weight > node.weight_ceiling_bytes: + raise PlanningError( + f"the RAM-proportional split gives node {node.node_id} " + f"{range_end - range_start} layers " + f"({model.fixed_weight_bytes + layer_weight} bytes with fixed " + f"weights) above its weight ceiling of " + f"{node.weight_ceiling_bytes}; raise that node's split cap or " + "plan with the balanced allocator" + ) + return _finish_pipeline_plan( + model, + nodes, + pipeline_nodes, + tuple(ranges), + workload_profile=workload_profile, + microbatch_size=microbatch_size, + context_tokens=context_tokens, + optimization="ram-proportional", + ) + + +def _finish_pipeline_plan( + model: ModelLayout, + nodes: Sequence[NodeBudget], + pipeline_nodes: Sequence[NodeBudget], + ranges: tuple[tuple[int, int], ...] | list[tuple[int, int]], + *, + workload_profile: ExecutionProfileName, + microbatch_size: int, + context_tokens: int, + optimization: str, +) -> ShardPlan: + """Assignments, per-node fit checks, and the signed hash for a partition.""" + + performance_aware = all(node.performance is not None for node in pipeline_nodes) assignments: list[PipelineAssignment] = [] for node, (start, end) in zip(pipeline_nodes, ranges): layer_weight_bytes = sum(model.layer_weight_bytes[start:end]) @@ -1552,7 +1677,7 @@ def plan_unequal_pipeline( hash_payload = { "model": model.to_dict(), "context_tokens": context_tokens, - "optimization": "performance" if performance_aware else "memory", + "optimization": optimization, "workload_profile": workload_profile, "microbatch_size": microbatch_size, "performance_profiles": [ @@ -1570,9 +1695,7 @@ def plan_unequal_pipeline( "reserve_bytes": item.reserve_bytes, "manual_memory_limit": item.manual_memory_limit, "target_weight_bytes": next( - node.target_weight_bytes - for node in nodes - if node.rank == item.rank + node.target_weight_bytes for node in nodes if node.rank == item.rank ), # Part of the plan's identity: the same layers on the same Mac # mean a different deployment depending on whether someone is @@ -1593,7 +1716,7 @@ def plan_unequal_pipeline( model=model, assignments=tuple(assignments), plan_hash=plan_hash, - optimization="performance" if performance_aware else "memory", + optimization=optimization, workload_profile=workload_profile, performance_profiles=tuple( node.performance @@ -1738,9 +1861,7 @@ def _max_context_for_stage( "not known" rather than "unlimited". """ - per_token = _kv_bytes_per_token_for_stage( - model, layer_count, tensor_parallel_size - ) + per_token = _kv_bytes_per_token_for_stage(model, layer_count, tensor_parallel_size) if per_token <= 0: return 0 spare = node.usable_bytes - weight_bytes @@ -1894,7 +2015,11 @@ def plan_hybrid( # them, split within each layer by shard_linear. ordered_nodes = sorted(nodes, key=lambda item: item.rank) stage_groups = [ - tuple(ordered_nodes[stage * tensor_parallel_size : (stage + 1) * tensor_parallel_size]) + tuple( + ordered_nodes[ + stage * tensor_parallel_size : (stage + 1) * tensor_parallel_size + ] + ) for stage in range(pipeline_stages) ] @@ -2013,10 +2138,13 @@ def plan_hybrid( assignments.sort(key=lambda a: a.rank) # Build performance profiles if available - profiles = tuple( - node.performance for node in ordered_nodes - if node.performance is not None - ) if performance_aware else () + profiles = ( + tuple( + node.performance for node in ordered_nodes if node.performance is not None + ) + if performance_aware + else () + ) # Compute plan hash covering all assignment fields hash_payload = { 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/registry.py b/omlx/cluster/registry.py index ccaf5c9b5d..33f6fec496 100644 --- a/omlx/cluster/registry.py +++ b/omlx/cluster/registry.py @@ -13,6 +13,11 @@ from .deployment import ClusterDeployment +# Version 2 persists per-node model paths (``path_map`` on each deployment). +# Version 1 files are migrated in memory on load and rewritten atomically. +REGISTRY_SCHEMA_VERSION = 2 +_SUPPORTED_REGISTRY_SCHEMAS = (1, REGISTRY_SCHEMA_VERSION) + def _model_key(model: str) -> str: path = Path(model).expanduser() @@ -30,6 +35,8 @@ def __init__(self, base_path: Path) -> None: self._lock = threading.RLock() self._deployments: dict[str, ClusterDeployment] = {} self.load_error: str | None = None + #: Set when an on-disk legacy schema was upgraded on load. + self.migrated_from: int | None = None try: self._load() except ValueError as exc: @@ -49,7 +56,9 @@ def _load(self) -> None: raise ValueError( f"could not read cluster deployment registry: {exc}" ) from exc - if not isinstance(payload, dict) or payload.get("schema_version") != 1: + if not isinstance(payload, dict) or payload.get("schema_version") not in ( + _SUPPORTED_REGISTRY_SCHEMAS + ): raise ValueError("unsupported cluster deployment registry schema") raw_deployments = payload.get("deployments") if not isinstance(raw_deployments, list): @@ -62,11 +71,19 @@ def _load(self) -> None: } if len(self._deployments) != len(deployments): raise ValueError("cluster deployment registry has duplicate models") + if payload.get("schema_version") != REGISTRY_SCHEMA_VERSION: + # Legacy files hold no per-node paths; every deployment decoded + # above with an empty path_map, which is the exact behavior the + # file described. Persist the upgrade so the migration happens + # once, but never let an unwritable file block server startup. + self.migrated_from = int(payload.get("schema_version", 1)) + with suppress(OSError): + self._save() def _save(self) -> None: self.path.parent.mkdir(parents=True, exist_ok=True) payload = { - "schema_version": 1, + "schema_version": REGISTRY_SCHEMA_VERSION, "deployments": [ deployment.to_dict() for _, deployment in sorted(self._deployments.items()) @@ -152,9 +169,10 @@ def remove(self, deployment_id: str) -> bool: def to_dict(self) -> dict[str, Any]: return { - "schema_version": 1, + "schema_version": REGISTRY_SCHEMA_VERSION, "deployments": [deployment.to_dict() for deployment in self.list()], "load_error": self.load_error, + "migrated_from": self.migrated_from, } diff --git a/omlx/cluster/replan.py b/omlx/cluster/replan.py new file mode 100644 index 0000000000..bd93d8efd6 --- /dev/null +++ b/omlx/cluster/replan.py @@ -0,0 +1,122 @@ +# SPDX-License-Identifier: Apache-2.0 +"""One-action cluster re-plan: deactivate → re-plan → reload. + +Today a membership or budget change is a manual four-step dance: deactivate +the deployment, rebuild a plan, approve it, then reload the model. This module +is the pure/data half of collapsing that into a single ``POST +/admin/api/cluster/replan`` call (the route handler in +``omlx/cluster/routes.py`` owns the async orchestration): + +- :func:`nodes_from_deployment` / :func:`hosts_from_deployment` derive the + plan inputs for the *next* plan from the *current* approved deployment, so + a replan with no explicit overrides re-plans the same cluster the operator + already trusts. A pairing/membership inventory (the v2 discovery/pairing + modules) can later supply overrides for added or removed nodes; until then + the explicit ``nodes``/``hosts`` request fields are how membership changes + are expressed. +- :func:`summarize_deployment` produces the compact, secret-free description + of what a replan replaced. + +Derivation caveats (documented contract, not bugs): + +- ``max_weight_bytes`` / ``target_weight_bytes`` are operator preferences that + live on the plan *request*, not on the signed assignment, so a derived + replan cannot recover them and resets both to "automatic". Operators moving + the split control must pass explicit ``nodes``. +- KV reservations and per-rank context limits are recomputed by the planner + from ``target_context_tokens``, never copied forward. +- Signed performance profiles *are* copied forward. Dropping them silently + turns a heterogeneous tensor deployment back into an equal split on every + replan, even when the previous activation already measured both ranks. +""" + +from __future__ import annotations + +from typing import Any + +from .deployment import ClusterDeployment + + +def nodes_from_deployment(deployment: ClusterDeployment) -> list[dict[str, Any]]: + """Rank-ordered node-budget payloads equivalent to this deployment. + + The returned dicts match ``ClusterPlanNodeRequest`` fields. Split-control + preferences (``max_weight_bytes`` / ``target_weight_bytes``) are not + recoverable from a signed plan and are reset to automatic. + """ + + profiles = { + (profile.rank, profile.node_id): profile + for profile in deployment.performance_profiles + } + nodes: list[dict[str, Any]] = [] + for assignment in sorted(deployment.assignments, key=lambda item: item.rank): + payload: dict[str, Any] = { + "node_id": assignment.node_id, + "capacity_bytes": assignment.capacity_bytes, + "reserve_bytes": assignment.reserve_bytes, + "manual_memory_limit": assignment.manual_memory_limit, + "role": assignment.role or "headless", + "memory_guard_tier": assignment.memory_guard_tier, + } + profile = profiles.get((assignment.rank, assignment.node_id)) + if profile is not None: + payload["performance"] = profile.to_dict() + nodes.append(payload) + return nodes + + +def hosts_from_deployment(deployment: ClusterDeployment) -> list[dict[str, Any]]: + """Rank-ordered host payloads equivalent to this deployment's hostfile.""" + + hosts: list[dict[str, Any]] = [] + for host in deployment.hosts: + payload: dict[str, Any] = { + "node_id": host.node_id, + "ssh": host.ssh, + "ips": list(host.ips), + "rdma": [ + list(path) if isinstance(path, tuple) else path for path in host.rdma + ], + } + if host.python_executable: + payload["python_executable"] = host.python_executable + hosts.append(payload) + return hosts + + +def summarize_deployment(deployment: ClusterDeployment) -> dict[str, Any]: + """What a replan is replacing, in the terms the plan view displays.""" + + return { + "deployment_id": deployment.deployment_id, + "model": deployment.model, + "backend": deployment.backend, + "world_size": deployment.world_size, + "plan_hash": deployment.plan_hash, + "target_context_tokens": deployment.target_context_tokens, + "assignments": [ + { + "rank": assignment.rank, + "node_id": assignment.node_id, + "start_layer": assignment.start_layer, + "end_layer": assignment.end_layer, + "planned_weight_bytes": assignment.planned_weight_bytes, + "kv_cache_bytes": assignment.kv_cache_bytes, + } + for assignment in sorted(deployment.assignments, key=lambda item: item.rank) + ], + } + + +def placement_view(deployment: ClusterDeployment) -> dict[str, Any]: + """The ``plan``-shaped assignment list used for placement diffs. + + ``_placement_rows`` in the routes module reads ``plan["assignments"]``; + this rebuilds that shape from a persisted deployment so a replan can diff + the running placement against the proposed one with the exact same code. + """ + + return { + "assignments": [assignment.to_dict() for assignment in deployment.assignments] + } diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index ea4419dba5..da57bf22d6 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -37,13 +37,23 @@ 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, run_local_collective_smoke, run_local_pipeline_smoke, ) -from .deployment import ClusterDeployment, ClusterHost, validate_ssh_target +from .deployment import ( + ClusterDeployment, + ClusterHost, + validate_model_path_map, + validate_ssh_target, +) from .discovery import ( discover_all_peers, record_peer_transports, @@ -55,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, @@ -84,12 +96,20 @@ ShardPlan, complete_model_layout, plan_hybrid, + plan_proportional_pipeline, plan_unequal_pipeline, remote_model_layout, synthetic_model_layout, ) from .probe import collect_cluster_status -from .registry import get_cluster_registry +from .registry import get_cluster_registry, get_device_registry +from .identity import get_node_identity +from .replan import ( + hosts_from_deployment, + nodes_from_deployment, + placement_view, + summarize_deployment, +) from .runtime import read_runtime_markers from .staging import ( DEFAULT_REMOTE_PYTHON, @@ -421,9 +441,15 @@ class ClusterPlanRequest(BaseModel): layer_count: int = Field(default=80, gt=0, le=2048) nodes: list[ClusterPlanNodeRequest] = Field(min_length=1, max_length=64) execution_profile: Literal["interactive", "balanced", "throughput"] = "balanced" + # "balanced" runs the bottleneck-minimizing DP planner; "proportional" + # splits layers ∝ usable RAM with largest-remainder rounding (exo-style). + allocation: Literal["balanced", "proportional"] = "balanced" pipeline_microbatch_size: int | None = Field(default=None, gt=0, le=256) tensor_parallel_size: int = Field(default=1, ge=1, le=64) target_context_tokens: int = Field(default=8192, ge=1, le=1_048_576) + # Cluster v2: optional node_id → absolute model path on that node. Empty + # keeps the legacy same-absolute-path-on-every-node behavior. + path_map: dict[str, str] | None = Field(default=None, max_length=64) class ClusterHostRequest(BaseModel): @@ -464,6 +490,7 @@ class ClusterDeploymentRequest(BaseModel): hosts: list[ClusterHostRequest] = Field(min_length=2, max_length=64) preflight: Literal[True] = True execution_profile: Literal["interactive", "balanced", "throughput"] = "balanced" + allocation: Literal["balanced", "proportional"] = "balanced" auto_tune: bool = True sampling_rank_only: bool = True async_overlap: bool = True @@ -479,6 +506,9 @@ class ClusterDeploymentRequest(BaseModel): # one dropped the role and the split cap without saying so. Activation is a # GUI workflow: callers must preview and name the placement they approve. approved_placement: str = Field(min_length=16, max_length=64) + # Cluster v2: node_id → absolute model path on that node. Nodes not listed + # load ``model_path`` — the pre-v2 shared-path behavior. + path_map: dict[str, str] | None = Field(default=None, max_length=64) class ClusterPeerProbeRequest(BaseModel): @@ -699,7 +729,14 @@ def _placement_rows(plan: dict[str, Any]) -> list[dict[str, Any]]: def _placement_signature(plan: dict[str, Any]) -> str: """Identity of the plan a user approves, stable across cosmetic re-planning.""" - payload = json.dumps(_placement_rows(plan), sort_keys=True, separators=(",", ":")) + rows: Any = _placement_rows(plan) + # A per-node path override changes what actually runs, so it is part of + # what the user approves. Folded in only when present, keeping signatures + # byte-identical to the legacy format for shared-path deployments. + path_map = plan.get("path_map") + if path_map: + rows = {"rows": rows, "path_map": path_map} + payload = json.dumps(rows, sort_keys=True, separators=(",", ":")) return hashlib.sha256(payload.encode()).hexdigest()[:16] @@ -800,9 +837,18 @@ def _create_cluster_plan(request: ClusterPlanRequest): f"across {len(nodes)} Macs." ) raise PlanningError(detail) + path_map = validate_model_path_map( + request.path_map, + tuple(node.node_id.strip() for node in request.nodes), + ) defaults = execution_profile(request.execution_profile) if request.tensor_parallel_size > 1: - return plan_hybrid( + if request.allocation != "balanced": + raise PlanningError( + "RAM-proportional allocation is a pipeline-only rule; tensor " + "parallelism uses the hybrid planner (allocation='balanced')" + ) + plan = plan_hybrid( model, nodes, tensor_parallel_size=request.tensor_parallel_size, @@ -812,15 +858,29 @@ def _create_cluster_plan(request: ClusterPlanRequest): ), context_tokens=request.target_context_tokens, ) - return plan_unequal_pipeline( - model, - nodes, - workload_profile=request.execution_profile, - microbatch_size=( - request.pipeline_microbatch_size or defaults.pipeline_microbatch_size - ), - context_tokens=request.target_context_tokens, - ) + elif request.allocation == "proportional": + plan = plan_proportional_pipeline( + model, + nodes, + workload_profile=request.execution_profile, + microbatch_size=( + request.pipeline_microbatch_size or defaults.pipeline_microbatch_size + ), + context_tokens=request.target_context_tokens, + ) + else: + plan = plan_unequal_pipeline( + model, + nodes, + workload_profile=request.execution_profile, + microbatch_size=( + request.pipeline_microbatch_size or defaults.pipeline_microbatch_size + ), + context_tokens=request.target_context_tokens, + ) + if path_map: + plan = replace(plan, path_map=path_map) + return plan class ClusterAutoconfigureRequest(BaseModel): @@ -1585,19 +1645,26 @@ def _run_staging_job( portable_model_path = home_relative_model_path(deployment.model) failed_nodes: list[str] = [] for host, assignment in zip(deployment.hosts, assignments): + # Cluster v2: files land at the node's path_map entry when one + # exists. Otherwise preserve the cross-account behavior by + # resolving the portable model path in the remote Mac's home. + explicit_destination = deployment.path_map.get(host.node_id) if _local_ssh_target(host.ssh): - destination_dir = str(model_path) + destination_dir = explicit_destination or str(model_path) + destination_path = Path(destination_dir) present = ( - { - path.name: path.stat().st_size - for path in model_path.iterdir() - if path.is_file() - } - if model_path.is_dir() + { + path.name: path.stat().st_size + for path in destination_path.iterdir() + if path.is_file() + } + if destination_path.is_dir() else {} ) else: - destination_dir = remote_model_dir(host.ssh, portable_model_path) + destination_dir = explicit_destination or remote_model_dir( + host.ssh, portable_model_path + ) present = remote_file_sizes(host.ssh, destination_dir) plan = plan_staging( model_path, @@ -2566,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]}" @@ -2645,9 +2753,11 @@ def _create_deployment( model_source_python=request.model_source_python, nodes=request.nodes, execution_profile=request.execution_profile, + allocation=request.allocation, pipeline_microbatch_size=requested_microbatch, tensor_parallel_size=request.tensor_parallel_size, target_context_tokens=request.target_context_tokens, + path_map=request.path_map, ) plan = _create_cluster_plan(plan_request) execution = _execution_for_request( @@ -2691,6 +2801,7 @@ def _create_deployment( performance_profiles=_request_performance_profiles(request.nodes), tensor_parallel_size=request.tensor_parallel_size, target_context_tokens=request.target_context_tokens, + path_map=validate_model_path_map(request.path_map, tuple(host_ids)), ) return deployment, plan.to_dict() @@ -3008,11 +3119,45 @@ async def read_host( } +def _requested_links_fast(nodes: list[ClusterPlanNodeRequest]) -> bool: + """Whether every requested peer sits on a fast (JACCL/Thunderbolt) link. + + The catalogue's default tie-break prefers pipeline at equal width because + it survives slow links; when the paired registry shows every requested + peer is reachable over JACCL/Thunderbolt RDMA, tensor parallelism is the + better recommendation — it splits per-token compute across the group. + The coordinator's own row is not in the paired registry, so only + non-self node_ids are consulted. Unknown or unpaired peers fail closed: + pipeline stays the recommendation where tensor would crawl. + """ + + if len(nodes) < 2: + return False + try: + identity = get_node_identity() + registry = get_device_registry() + except RuntimeError: + return False + for node in nodes: + if node.node_id == identity.node_id: + continue + if not registry.is_paired(node.node_id): + return False + record = registry.get(node.node_id) or {} + caps = record.get("caps") + if not isinstance(caps, dict): + return False + if not (caps.get("jaccl") or caps.get("thunderbolt")): + return False + return True + + def _catalogue_for_candidates( candidates: list[ClusterCatalogueModelRequest], nodes: list[NodeBudget], *, workload_profile: str, + prefer_tensor: bool = False, ) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] for candidate in candidates: @@ -3035,6 +3180,7 @@ def _catalogue_for_candidates( model_id=candidate.id, declared_context_tokens=candidate.model_context_length, workload_profile=workload_profile, + prefer_tensor=prefer_tensor, ) except (OSError, PlanningError, RuntimeError, ValueError) as exc: fit = ModelFit( @@ -3075,6 +3221,7 @@ async def cluster_catalogue(request: ClusterCatalogueRequest) -> dict[str, Any]: """ nodes = _node_budgets(request.nodes) + prefer_tensor = _requested_links_fast(request.nodes) paths = [Path(item) for item in request.model_paths] if request.model_dir: @@ -3096,6 +3243,7 @@ async def cluster_catalogue(request: ClusterCatalogueRequest) -> dict[str, Any]: request.models, nodes, workload_profile=request.execution_profile, + prefer_tensor=prefer_tensor, ) else: catalogue = await asyncio.to_thread( @@ -3103,6 +3251,7 @@ async def cluster_catalogue(request: ClusterCatalogueRequest) -> dict[str, Any]: paths, nodes, workload_profile=request.execution_profile, + prefer_tensor=prefer_tensor, ) model_rows = [fit.to_dict() for fit in catalogue] runnable = [row for row in model_rows if row["fits"]] @@ -3125,9 +3274,20 @@ async def cluster_deployments(): raise HTTPException(status_code=503, detail=str(exc)) from exc -@router.post("/deployments") -async def activate_cluster_deployment(request: ClusterDeploymentRequest): - """Recompute, preflight, eagerly load, and prove one distributed model.""" +async def _activate_and_report( + request: ClusterDeploymentRequest, +) -> dict[str, Any]: + """Recompute, preflight, eagerly load, and prove one distributed model. + + This is the single activation pipeline behind both ``POST /deployments`` + (explicit approval of a previewed plan) and the approve phase of + ``POST /replan`` (one-action deactivate → re-plan → reload). The + deactivate half of a replan is exactly what this pipeline already does: + ``pool.prepare_cluster_reload`` unloads the resident engine under the + pool lock — quiescence-gated, and for distributed engines the supervisor's + *verified* teardown is the memory barrier — before the registry swap and + the eager reload below. + """ plan_changes: dict[str, Any] = { "changed": False, @@ -3275,6 +3435,7 @@ async def activate_cluster_deployment(request: ClusterDeploymentRequest): loaded_deployment is not None and loaded_deployment.deployment_id == deployment.deployment_id and loaded_deployment.plan_hash == deployment.plan_hash + and loaded_deployment.path_map == deployment.path_map ) if not already_loaded: await pool.prepare_cluster_reload(model_id) @@ -3292,7 +3453,13 @@ async def activate_cluster_deployment(request: ClusterDeploymentRequest): ) 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, @@ -3403,6 +3570,254 @@ async def activate_cluster_deployment(request: ClusterDeploymentRequest): } +@router.post("/deployments") +async def activate_cluster_deployment(request: ClusterDeploymentRequest): + """Recompute, preflight, eagerly load, and prove one distributed model.""" + + return await _activate_and_report(request) + + +class ClusterReplanRequest(BaseModel): + """One-action deactivate → re-plan → reload for a clustered model. + + With no ``approved_placement`` this is a dry run: it renders the plan the + one-action call would launch, signed, with a diff against the running + placement. Posting that signature back performs the whole dance at once. + + ``nodes``/``hosts``/``backend`` default to the current deployment's, so a + budget-only or context-only change needs no host details; a membership + change (a node joining or leaving the model) is expressed by posting the + new explicit ``nodes`` + ``hosts`` lists. ``path_map`` likewise defaults + to the current deployment's per-node paths so a replan does not silently + revert a heterogeneous-path cluster to same-path resolution. + """ + + model_config = ConfigDict(extra="forbid") + + deployment_id: str | None = Field(default=None, max_length=128) + 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["auto", "ring", "jaccl", "jaccl-ring"] | None = None + nodes: list[ClusterPlanNodeRequest] | None = Field( + default=None, min_length=2, max_length=64 + ) + hosts: list[ClusterHostRequest] | None = Field( + default=None, min_length=2, max_length=64 + ) + execution_profile: Literal["interactive", "balanced", "throughput"] = ( + "balanced" + ) + auto_tune: bool = False + sampling_rank_only: bool = True + async_overlap: bool = True + cache_affinity: bool = True + max_kv_size: int | None = Field(default=None, gt=0) + ring_connections_per_ip: int | None = Field(default=None, ge=1, le=32) + tensor_parallel_size: int | None = Field(default=None, ge=1, le=64) + target_context_tokens: int | None = Field( + default=None, ge=1, le=1_048_576 + ) + path_map: dict[str, str] | None = Field(default=None, max_length=64) + approved_placement: str | None = Field(default=None, min_length=16, max_length=64) + + +_REPLAN_STEPS = ( + "deactivate (quiescence-gated unload with verified teardown)", + "re-plan (recomputed server-side and pinned by signature)", + "reload (eager distributed load with readiness canary)", +) + + +@router.post("/replan") +async def replan_cluster_deployment(request: ClusterReplanRequest): + """Collapse deactivate → re-plan → reload into one action. + + The engine-pool quiescence gate (``prepare_cluster_reload``) refuses to + interrupt in-flight requests, and the distributed supervisor's verified + teardown is the memory barrier between the old world and the new one: if + teardown cannot be proven, the old registry record stays and the error + says what survived. + """ + + try: + registry = get_cluster_registry() + except RuntimeError as exc: + raise HTTPException(status_code=503, detail=str(exc)) from exc + + current: ClusterDeployment | None = None + if request.deployment_id: + current = await asyncio.to_thread(registry.get, request.deployment_id) + if current is None: + raise HTTPException( + status_code=404, detail="cluster deployment not found" + ) + elif request.model_path: + current = await asyncio.to_thread( + registry.get_for_model, request.model_path + ) + + if current is None and not ( + request.model_path and request.nodes and request.hosts + ): + raise HTTPException( + status_code=400, + detail=( + "replan needs an existing deployment (deployment_id or a " + "model_path with a registered deployment) or an explicit " + "model_path together with nodes and hosts" + ), + ) + + derived: dict[str, bool] = { + "nodes": False, + "hosts": False, + "backend": False, + "path_map": False, + } + nodes = request.nodes + if nodes is None: + if current is None: + raise HTTPException(status_code=400, detail="nodes are required") + nodes = [ + ClusterPlanNodeRequest(**payload) + for payload in nodes_from_deployment(current) + ] + derived["nodes"] = True + hosts = request.hosts + if hosts is None: + if current is None: + raise HTTPException(status_code=400, detail="hosts are required") + hosts = [ + ClusterHostRequest(**payload) + for payload in hosts_from_deployment(current) + ] + derived["hosts"] = True + backend = request.backend + if backend is None: + if current is None: + raise HTTPException(status_code=400, detail="backend is required") + backend = current.backend + derived["backend"] = True + path_map = request.path_map + if path_map is None and current is not None and current.path_map: + # Per-node paths are part of the deployment contract: a replan that + # dropped them would silently revert workers to the coordinator's + # 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( + deployment_id=request.deployment_id, + model_path=(request.model_path or (current.model if current else "")), + model_source=request.model_source, + model_source_python=request.model_source_python, + backend=backend, + nodes=nodes, + hosts=hosts, + execution_profile=request.execution_profile, + auto_tune=request.auto_tune, + sampling_rank_only=request.sampling_rank_only, + async_overlap=request.async_overlap, + cache_affinity=request.cache_affinity, + max_kv_size=request.max_kv_size, + ring_connections_per_ip=request.ring_connections_per_ip, + tensor_parallel_size=( + request.tensor_parallel_size + if request.tensor_parallel_size is not None + else current.tensor_parallel_size + if current is not None + else 1 + ), + target_context_tokens=( + request.target_context_tokens + if request.target_context_tokens is not None + else current.target_context_tokens + if current is not None + else 8192 + ), + path_map=path_map, + # Not consulted by planning; activation re-checks the real one + # below. Preview callers do not have a signature yet. + approved_placement=request.approved_placement or ("0" * 16), + ) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + try: + deployment, plan = await asyncio.to_thread(_create_deployment, effective) + except (OSError, PlanningError, ValueError) as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + signed_plan = _plan_with_signature(plan) + changes = ( + _plan_changes(placement_view(current), plan) + if current is not None + else None + ) + + if request.approved_placement is None: + return { + "ok": True, + "mode": "preview", + "steps": list(_REPLAN_STEPS), + "derived": derived, + "current": ( + summarize_deployment(current) if current is not None else None + ), + "changes": changes, + "deployment_id": deployment.deployment_id, + "backend": deployment.backend, + "backend_decision": backend_decision, + "plan": signed_plan, + } + + if request.approved_placement.strip() != signed_plan["placement_signature"]: + raise HTTPException( + status_code=409, + detail=( + "This is not the plan the replan preview showed — the budgets, " + "roles or layer split changed in between. Preview again and " + f"approve what it shows. As posted, this request would place: " + f"{_describe_placement(plan)}." + ), + ) + + result = await _activate_and_report(effective) + return result | { + "mode": "applied", + "replan": { + "steps": list(_REPLAN_STEPS), + "derived": derived, + "backend_decision": backend_decision, + "previous": ( + summarize_deployment(current) if current is not None else None + ), + "changes": changes, + }, + } + + @router.delete("/deployments/{deployment_id}") async def deactivate_cluster_deployment(deployment_id: str): """Stop the resident cluster, then disable future distributed loads.""" @@ -3419,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): @@ -3440,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/staging.py b/omlx/cluster/staging.py index 4c4846c93f..2e76ca9470 100644 --- a/omlx/cluster/staging.py +++ b/omlx/cluster/staging.py @@ -162,9 +162,7 @@ def shards_for_stage( wanted = set(range(start_layer, end_layer)) return tuple( - shard - for shard in shards - if (shard.layers & wanted) or shard.has_shared_tensors + shard for shard in shards if (shard.layers & wanted) or shard.has_shared_tensors ) @@ -212,6 +210,11 @@ def _model_identity_digest(model_path: str | Path) -> str: return hasher.hexdigest() +# Public name for the digest; the manifest endpoint and peer comparison in +# ``modelsync.py`` share this exact identity definition with staging. +model_identity_digest = _model_identity_digest + + def _indexed_shards(model_path: str | Path) -> tuple[ShardInfo, ...] | None: """Read the full shard map from the index even on a partially staged rank.""" @@ -307,7 +310,9 @@ def validate_staged_model( indexed = _indexed_shards(root) shards = indexed if indexed is not None else index_shards(root) required = shards_for_stage(shards, start_layer, end_layer) - missing = tuple(shard.name for shard in required if not (root / shard.name).is_file()) + missing = tuple( + shard.name for shard in required if not (root / shard.name).is_file() + ) corrupt: list[str] = [] for shard in required: path = root / shard.name @@ -347,10 +352,7 @@ def model_staging_inventory(model_path: str | Path) -> dict[str, Any]: } for shard in shards ], - "sidecars": { - name: (root / name).stat().st_size - for name in sidecars - }, + "sidecars": {name: (root / name).stat().st_size for name in sidecars}, } @@ -566,9 +568,7 @@ def stage_manifest( for plan in plans: present = present_by_node.get(plan.node_id, {}) missing_sidecars = tuple( - name - for name, size in sidecar_sizes.items() - if present.get(name) != size + name for name, size in sidecar_sizes.items() if present.get(name) != size ) missing_sidecar_bytes = sum(sidecar_sizes[name] for name in missing_sidecars) total_missing_bytes += plan.missing_bytes + missing_sidecar_bytes @@ -583,9 +583,7 @@ def stage_manifest( ) return { "sidecars": list(sidecars), - "source_host": ( - "127.0.0.1" if source_is_local else source_host - ), + "source_host": ("127.0.0.1" if source_is_local else source_host), "nodes": nodes, "total_missing_bytes": total_missing_bytes, "ready": all(node["ready"] for node in nodes), @@ -608,9 +606,7 @@ def stage_manifest( "\nos.replace(temporary,final)" ) _REMOTE_DISCARD_SNIPPET = ( - "import os,sys;" - "\ntry: os.unlink(sys.argv[1])" - "\nexcept FileNotFoundError: pass" + "import os,sys;\ntry: os.unlink(sys.argv[1])\nexcept FileNotFoundError: pass" ) @@ -648,8 +644,7 @@ def _finish_remote_staged_file( ) if result.returncode != 0: raise RuntimeError( - f"could not install staged file on {host}: " - f"{result.stderr.strip()[:200]}" + f"could not install staged file on {host}: {result.stderr.strip()[:200]}" ) @@ -745,9 +740,7 @@ def scp_push( f"{str(Path(destination_dir).expanduser()).rstrip('/')}/" f"{_staging_partial_name()}" ) - final_path = ( - f"{str(Path(destination_dir).expanduser()).rstrip('/')}/{filename}" - ) + final_path = f"{str(Path(destination_dir).expanduser()).rstrip('/')}/{filename}" installed = False try: result = subprocess.run( @@ -786,11 +779,7 @@ def _local_file_sizes(model_dir: str | Path) -> dict[str, int]: root = Path(model_dir).expanduser() if not root.is_dir(): return {} - return { - path.name: path.stat().st_size - for path in root.iterdir() - if path.is_file() - } + return {path.name: path.stat().st_size for path in root.iterdir() if path.is_file()} def scp_copy( @@ -873,9 +862,7 @@ def scp_copy( f"could not create model directory on {destination_host}: " f"{mkdir.stderr.strip()[:200]}" ) - temporary_path = ( - f"{destination_dir.rstrip('/')}/{_staging_partial_name()}" - ) + temporary_path = f"{destination_dir.rstrip('/')}/{_staging_partial_name()}" final_path = f"{destination_dir.rstrip('/')}/{filename}" installed = False try: @@ -946,9 +933,7 @@ def stage_files_from_source( source_dir = ( str(Path(model_path).expanduser()) if is_local_host(source_host) - else remote_model_dir( - source_host, home_relative_model_path(str(model_path)) - ) + else remote_model_dir(source_host, home_relative_model_path(str(model_path))) ) destination_dir = destination_dir or source_dir expected = dict(expected_sizes) @@ -963,9 +948,7 @@ def stage_files_from_source( ): raise RuntimeError("staging source returned an unsafe file inventory") if is_local_host(source_host) and not is_local_host(destination_host): - common = tuple( - name for name in expected if name not in set(plan.required) - ) + common = tuple(name for name in expected if name not in set(plan.required)) return stage_remote_files( plan, model_path=model_path, diff --git a/omlx/cluster/telemetry.py b/omlx/cluster/telemetry.py index 772573b240..d1e892f8dc 100644 --- a/omlx/cluster/telemetry.py +++ b/omlx/cluster/telemetry.py @@ -3,14 +3,17 @@ from __future__ import annotations +import json import logging import math +import os import shutil import threading import time from collections.abc import Iterator from contextlib import contextmanager from dataclasses import dataclass +from pathlib import Path from typing import Any, Protocol from .performance import ExecutionSettings @@ -18,6 +21,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 @@ -70,6 +76,8 @@ 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 = "", ) -> None: if publish_interval < 0: raise ValueError("publish_interval must be non-negative") @@ -108,6 +116,17 @@ 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._last_cancel_epoch = 0 + self._last_cancel_poll_at = float("-inf") def heartbeat(self) -> None: """Refresh the marker with nothing new to say. @@ -118,6 +137,9 @@ 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) with self._lock: self._publish_locked(now, force=True) @@ -227,17 +249,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 @@ -320,6 +340,120 @@ def cancel_uids(self, uids: Any) -> None: if changed: self._publish_locked(now, force=True) + 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 force_cancel_all(self, *, reason: str = "coordinator cancel") -> int: + """Remove every active uid through MLX-LM's own cancel path. + + ``BatchGenerator.remove`` is the same call MLX-LM handlers make on + client disconnect: it is processed by the batch loop at a step + boundary and shared with peer ranks, so both sides of the pipeline + abandon the request together and no collective is severed + mid-request. Returns the number of uids handed to the batch loop. + """ + + with self._lock: + generator = self._batch_generator + uids = [ + uid + for request_id, uid in self._request_to_uid.items() + if request_id in self._requests + ] + if generator is None or not uids: + return 0 + try: + generator.remove(list(uids)) + except Exception as exc: + # A cancel that failed must be loud but must not kill the rank; + # the coordinator falls back to process teardown. + logger.warning("Rank-side force-cancel failed: %s", exc) + return 0 + logger.warning( + "Force-cancelled %d active rank-side request(s): %s", + len(uids), + reason, + ) + return len(uids) + + 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 + epoch = payload.get("epoch") + if not isinstance(epoch, int) or isinstance(epoch, bool): + 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, + "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 + cancelled = self.force_cancel_all( + reason=str(payload.get("reason") or "coordinator cancel") + ) + self._write_cancel_ack(epoch=epoch, cancelled=cancelled) + return cancelled + def observe_batch_step( self, *, @@ -329,6 +463,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: @@ -633,6 +770,7 @@ def install_server_telemetry( ssd_cache_dir: str | None = None, ssd_max_entries: int = 64, prefill_step_size: int = 2048, + control_plane: Any | None = None, ) -> Iterator[RuntimeTelemetry]: """Patch the pinned worker's generator at its rank-local queue boundary. @@ -659,11 +797,24 @@ def install_server_telemetry( original_prompt_cache = mlx_server.LRUPromptCache original_generation_context = mlx_server.GenerationContext 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 "" + ) 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, ) snapshot_ctx = threading.local() @@ -731,6 +882,7 @@ 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]] = {} + telemetry.register_batch_generator(self) def insert_segments(self, *args: Any, **kwargs: Any) -> Any: uids = super().insert_segments(*args, **kwargs) diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index 9f46a0935c..f9db43fdd7 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(): @@ -2333,10 +2333,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/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/language.py b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/language.py index 6f450fced3..e11e0d58c3 100644 --- a/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/language.py +++ b/omlx/patches/mlx_vlm_qwen4_exp_compat/vendor/mlx_vlm/models/qwen4_exp/language.py @@ -1,12 +1,15 @@ from __future__ import annotations import json +import logging import math import mmap import os import struct +import time import weakref from bisect import bisect_right +from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, replace from pathlib import Path from typing import Any, Optional @@ -34,6 +37,8 @@ ) from . import hc_fused +logger = logging.getLogger(__name__) + _PLE_RUNTIME_MODEL_PATH: Path | None = None _PLE_RUNTIME_MODE = "resident" _HYPER_SPLIT_INDICES: dict[tuple[int, int], tuple[mx.array, mx.array]] = {} @@ -1833,6 +1838,18 @@ def _find_nth_prime_after(start: int, count: int) -> int: return prime +# Prefetch unseen pages concurrently to overlap SSD reads; keep mmap as the +# data path. Remembering pages avoids repeating thread-pool work on warm reads. +# os.pread releases the GIL and does not change the shared file position. +_PLE_IO_POOL = ThreadPoolExecutor(max_workers=48, thread_name_prefix="ple-io") +_PLE_PAGE_SIZE = os.sysconf("SC_PAGE_SIZE") +# Slow gathers may indicate page eviction. Allow normal gather overhead and +# rate-limit retries; elapsed time is a heuristic, not a residency check. +_PLE_REARM_FLOOR_SECONDS = 0.0005 +_PLE_REARM_PER_ROW_SECONDS = 2e-6 +_PLE_REARM_MIN_INTERVAL_SECONDS = 60.0 + + class _SafeTensorMMap: """Read selected dense or affine-packed rows without resident weights.""" @@ -1843,6 +1860,11 @@ def __init__(self, path: Path): self._header = json.loads(self._file.read(header_size)) self._data_start = 8 + header_size self._mapping = mmap.mmap(self._file.fileno(), 0, access=mmap.ACCESS_READ) + self._seen_pages = bytearray( + 1 + (max(path.stat().st_size, 1) - 1) // _PLE_PAGE_SIZE + ) + self._last_rearm = 0.0 + self._rearm_count = 0 try: self._mapping.madvise(mmap.MADV_RANDOM) except (AttributeError, OSError): @@ -1871,13 +1893,29 @@ def rows(self, key: str, rows: list[int]) -> mx.array: np_dtype, item_size = dtype_info if len(shape) != 2 or end - start != math.prod(shape) * item_size: raise ValueError(f"Invalid sparse PLE tensor layout for {key}") - view = np.ndarray( - shape, - dtype=np_dtype, - buffer=self._mapping, - offset=self._data_start + start, - ) - copied = np.array(view[np.asarray(rows, dtype=np.intp)], copy=True) + row_indices = np.asarray(rows, dtype=np.intp) + if row_indices.size == 0: + copied = np.empty((0, shape[1]), dtype=np_dtype) + else: + gather_start = None + if row_indices.size > 8: + fully_seen = self._prefetch_missing_pages( + row_indices, + self._data_start + start, + shape[1] * item_size, + ) + gather_start = time.perf_counter() if fully_seen else None + view = np.ndarray( + shape, + dtype=np_dtype, + buffer=self._mapping, + offset=self._data_start + start, + ) + copied = np.array(view[row_indices], copy=True) + if gather_start is not None: + self._rearm_if_slow( + time.perf_counter() - gather_start, row_indices.size + ) if dtype == "BF16": values = (copied.astype(np.uint32) << np.uint32(16)).view(np.float32) return mx.array(values).astype(mx.bfloat16) @@ -1885,6 +1923,55 @@ def rows(self, key: str, rows: list[int]) -> mx.array: return mx.from_fp8(mx.array(copied), dtype=mx.bfloat16) return mx.array(copied) + def _prefetch_missing_pages(self, row_indices, base_offset, row_bytes) -> bool: + """Prefetch unmarked pages; return whether all were already marked.""" + offsets = base_offset + row_indices * row_bytes + needed_pages = np.unique( + np.concatenate( + (offsets // _PLE_PAGE_SIZE, (offsets + row_bytes - 1) // _PLE_PAGE_SIZE) + ) + ) + seen = np.frombuffer(self._seen_pages, dtype=np.uint8) + fresh = needed_pages[seen[needed_pages] == 0] + if fresh.size == 0: + return True + fd = self._file.fileno() + + def touch(page: int) -> None: + offset = int(page) * _PLE_PAGE_SIZE + remaining = _PLE_PAGE_SIZE + while remaining > 0: + chunk = os.pread(fd, remaining, offset + (_PLE_PAGE_SIZE - remaining)) + if not chunk: + break + remaining -= len(chunk) + + list(_PLE_IO_POOL.map(touch, (int(page) for page in fresh.tolist()))) + for page in fresh.tolist(): + self._seen_pages[page] = 1 + return False + + def _rearm_if_slow(self, elapsed: float, row_count: int) -> None: + """Allow another prefetch after a slow gather, at most once per interval.""" + budget = _PLE_REARM_FLOOR_SECONDS + row_count * _PLE_REARM_PER_ROW_SECONDS + if elapsed < budget: + return + now = time.monotonic() + if now - self._last_rearm < _PLE_REARM_MIN_INTERVAL_SECONDS: + return + self._last_rearm = now + self._seen_pages = bytearray(len(self._seen_pages)) + self._rearm_count += 1 + logger.info( + "PLE: warm gather of %d rows took %.1f ms (memcpy budget %.1f ms); " + "eviction suspected, re-armed seen-page bitmap for %s (#%d)", + row_count, + elapsed * 1e3, + budget * 1e3, + self.path.name, + self._rearm_count, + ) + def close(self): if self._mapping is not None: self._mapping.close() diff --git a/omlx/server.py b/omlx/server.py index b7efe31802..507673a821 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -422,6 +422,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 @@ -727,6 +745,19 @@ def _register_cluster_routes() -> None: Depends(require_distributed_inference_enabled), ], ) + # Cluster v2 model-sync manifest: admin-gated like the rest of the + # cluster surface; peers use it to compare model contents before sync. + from .cluster.modelsync import manifest_router as cluster_manifest_router + from .cluster.modelsync import set_modelsync_getters + + set_modelsync_getters(get_engine_pool) + app.include_router( + cluster_manifest_router, + dependencies=[ + Depends(require_admin), + Depends(require_distributed_inference_enabled), + ], + ) # The bootstrap bytes are public but pinned by SHA-256 in an admin-created # command. Claim/source/complete authenticate with one-time enrollment # credentials, not the browser's admin cookie. diff --git a/tests/test_cluster_catalogue.py b/tests/test_cluster_catalogue.py index a343759c41..813217309e 100644 --- a/tests/test_cluster_catalogue.py +++ b/tests/test_cluster_catalogue.py @@ -249,9 +249,7 @@ def _node_payload(capacity_gib, node_id="studio"): def test_the_endpoint_needs_somewhere_to_look(): - response = _client().post( - CATALOGUE, json={"nodes": [_node_payload(128)]} - ) + response = _client().post(CATALOGUE, json={"nodes": [_node_payload(128)]}) assert response.status_code == 400 assert "model_paths or model_dir" in response.json()["detail"] @@ -394,3 +392,103 @@ def test_the_interface_can_grey_out_an_unsplittable_model(): payload = assess_model(layout, _nodes(128, 128), model_id="m").to_dict() assert payload["splittable"] is False assert payload["fits"] is False + + +# --- Fast-link recommendation ----------------------------------------------- + + +def test_prefer_tensor_flips_the_equal_width_tiebreak(): + # 90 GiB across 2x64 GiB fits both ways; pipeline is the safe default... + def shardable(): + layout = _model(90) + # The synthetic helper declares a single attention head group, which + # no TP degree above 1 divides; give it 8 heads so TP=2 is legal. + object.__setattr__(layout, "tensor_parallel_heads", 8) + object.__setattr__(layout, "tensor_parallel_kv_heads", 8) + object.__setattr__(layout, "tensor_parallel_divisors", (8,)) + return layout + + fit = assess_model(shardable(), _nodes(64, 64), model_id="medium") + assert fit.strategy == "pipeline" + # ...but a caller that knows the link is fast gets the tensor split. + fast = assess_model( + shardable(), _nodes(64, 64), model_id="medium", prefer_tensor=True + ) + assert fast.fits + assert fast.strategy == "tensor" + assert fast.tensor_parallel_size == 2 + assert fast.pipeline_stages == 1 + + +def test_prefer_tensor_still_prefers_fewer_nodes_first(): + # A model that fits one Mac stays single-node even on fast links. + fit = assess_model( + _model(20), _nodes(128, 128), model_id="small", prefer_tensor=True + ) + assert fit.strategy == "single node" + + +def test_prefer_tensor_never_offers_tp_to_an_unshardable_model(): + layout = _model(90) + object.__setattr__(layout, "supports_tensor_parallel", False) + fit = assess_model(layout, _nodes(64, 64), model_id="m", prefer_tensor=True) + assert fit.fits + assert fit.strategy == "pipeline" + + +def test_requested_links_fast(tmp_path): + from omlx.cluster import routes as cluster_routes + from omlx.cluster.identity import ( + configure_node_identity, + reset_configured_identity, + ) + from omlx.cluster.registry import ( + configure_device_registry, + reset_configured_device_registry, + ) + + configure_node_identity(tmp_path / "identity.json") + registry = configure_device_registry(tmp_path / "devices.json") + try: + self_id = cluster_routes.get_node_identity().node_id + + def node(node_id): + return cluster_routes.ClusterPlanNodeRequest( + node_id=node_id, + capacity_bytes=64 * GiB, + role="headless", + memory_guard_tier="balanced", + accelerator="metal", + ) + + # A single-node request has no link to judge. + assert cluster_routes._requested_links_fast([node(self_id)]) is False + + # Unpaired peer: fail closed. + assert ( + cluster_routes._requested_links_fast([node(self_id), node("peer1")]) + is False + ) + + # Paired peer without fast-link caps: fail closed. + registry.mark_paired("peer1", caps={"chip": "M", "ram_gb": 64.0}) + assert ( + cluster_routes._requested_links_fast([node(self_id), node("peer1")]) + is False + ) + + # Paired over JACCL/Thunderbolt: tensor becomes the recommendation. + registry.mark_paired("peer2", caps={"jaccl": True, "thunderbolt": True}) + assert ( + cluster_routes._requested_links_fast([node(self_id), node("peer2")]) is True + ) + # One slow peer in a larger pool fails the whole request closed. + assert ( + cluster_routes._requested_links_fast( + [node(self_id), node("peer2"), node("peer1")] + ) + is False + ) + finally: + reset_configured_device_registry() + reset_configured_identity() diff --git a/tests/test_cluster_control_plane.py b/tests/test_cluster_control_plane.py new file mode 100644 index 0000000000..b1b5737eab --- /dev/null +++ b/tests/test_cluster_control_plane.py @@ -0,0 +1,197 @@ +# 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_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() + rogue = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + for _attempt in range(100): + try: + rogue.connect(("127.0.0.1", port)) + break + except ConnectionRefusedError: + 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 3e39d52887..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( @@ -159,6 +195,7 @@ def test_deployment_round_trip_preserves_tensor_parallel_size(): import base64 import json import zlib + compressed = base64.b64decode(encoded, altchars=b"-_") raw = zlib.decompress(compressed) payload = json.loads(raw) @@ -360,9 +397,7 @@ def test_the_role_survives_the_worker_plan_and_the_registry_file(): ) # The registry writes and reloads this. - restored = ClusterDeployment.from_dict( - json.loads(json.dumps(deployment.to_dict())) - ) + restored = ClusterDeployment.from_dict(json.loads(json.dumps(deployment.to_dict()))) # The rank decodes this. _hash, decoded = decode_worker_plan(deployment.encode_worker_plan()) @@ -433,3 +468,30 @@ def test_a_plan_carrying_an_unknown_role_refuses_to_launch(): with pytest.raises(ValueError, match="unknown node role"): _assignment_from_dict(payload) + + +def test_link_local_zone_ids_are_stripped_from_communication_ips(): + """macOS announces Thunderbolt addresses as fe80::…%en10; mlx's address + parser cannot read the zone and the rank died at startup on it.""" + host = ClusterHost( + "node", "peer.local", ("10.0.0.2", "fe80::23:3ee:ec30:9a92%en10") + ) + assert host.ips == ("10.0.0.2", "fe80::23:3ee:ec30:9a92") + + +def test_hostfile_advertises_routable_addresses_before_link_local(): + from omlx.cluster.deployment import _hostfile_ips + + host = ClusterHost( + "node", + "peer.local", + ("fe80::1%en4", "10.0.0.2", "fe80::2%en5"), + ) + assert _hostfile_ips(host) == ["10.0.0.2", "fe80::1", "fe80::2"] + + +def test_a_link_local_only_host_keeps_its_zone_free_fallback(): + from omlx.cluster.deployment import _hostfile_ips + + host = ClusterHost("node", "peer.local", ("fe80::1%en4",)) + assert _hostfile_ips(host) == ["fe80::1"] diff --git a/tests/test_cluster_inference_worker.py b/tests/test_cluster_inference_worker.py index 8eb385a2a2..02af1cc423 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,48 @@ 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) + + +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 +247,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 +259,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 +274,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 +648,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): @@ -637,6 +695,13 @@ def fake_run(host, port, provider): "decode_worker_contract", lambda _plan: ("a" * 64, assignments, (), 1), ) + # The fake plan above is not a real encoded contract, so the path_map + # decoder it feeds must be faked alongside it (empty = legacy behavior). + monkeypatch.setattr( + inference_worker, + "decode_worker_path_map", + lambda _plan: {}, + ) def fake_guard_rank_load(item, *, rank, **kwargs): record["order"].append("guard") @@ -1112,6 +1177,263 @@ 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 _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..1f984b5557 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,9 @@ 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, ) assert argv[0] == "/opt/omlx/bin/python" @@ -71,6 +144,10 @@ 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("--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 +168,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 +276,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 +408,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 +455,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 +467,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 +875,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 +895,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 +969,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 +1345,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." @@ -1621,7 +1763,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 +1831,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 +1955,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 == "ready" + 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_modelsync.py b/tests/test_cluster_modelsync.py new file mode 100644 index 0000000000..b1280562c4 --- /dev/null +++ b/tests/test_cluster_modelsync.py @@ -0,0 +1,695 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Cluster v2 model sync: manifests, path_map resolution, migration, decisions. + +All transports are mocked — no test here opens a socket, runs rsync, or +touches the Hugging Face hub. +""" + +import base64 +import json +import platform +import shlex +import stat +import struct +import subprocess +import zlib +from pathlib import Path +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from omlx.cluster import modelsync +from omlx.cluster.deployment import ( + ClusterDeployment, + ClusterHost, + decode_worker_contract, + decode_worker_path_map, + validate_model_path_map, +) +from omlx.cluster.modelsync import ( + AUTO_RSYNC_THRESHOLD_BYTES, + ModelSyncError, + ModelSyncManager, + allow_patterns_for_shard, + build_manifest, + build_rsync_argv, + compare_manifests, + parse_rsync_progress, +) +from omlx.cluster.planner import PipelineAssignment, ShardPlan, synthetic_model_layout +from omlx.cluster.registry import ClusterRegistry + + +def _write_shard(directory, name, tensors, payload=b"\x00" * 32): + header = { + t: {"dtype": "F16", "shape": [1], "data_offsets": [0, 2]} for t in tensors + } + blob = json.dumps(header).encode() + (directory / name).write_bytes(struct.pack(" ClusterDeployment: + return ClusterDeployment( + deployment_id="sync-test", + model=model, + backend="ring", + hosts=( + ClusterHost("local", "127.0.0.1", ("10.0.0.1",)), + ClusterHost("peer", "user@studio.local", ("10.0.0.2",)), + ), + assignments=( + PipelineAssignment("local", 0, 2, 4, 20, 2, 4, 64), + PipelineAssignment("peer", 1, 0, 2, 10, 2, 4, 32), + ), + plan_hash="e" * 64, + path_map=path_map or {}, + ) + + +# -- manifest ----------------------------------------------------------------- + + +def test_build_manifest_on_fixture_model(tmp_path): + root = _model(tmp_path / "model-a") + + manifest = build_manifest(root, model_id="org/model-a") + + assert manifest.model_id == "org/model-a" + assert manifest.index_sha256 is not None + assert len(manifest.index_sha256) == 64 + assert len(manifest.identity_sha256) == 64 + names = [item.name for item in manifest.files] + assert "model-00000.safetensors" in names + assert "model-shared.safetensors" in names + assert "config.json" in names # sidecars travel with the manifest + assert manifest.total_bytes == sum(item.size_bytes for item in manifest.files) + assert manifest.total_bytes > 0 + # Round-trip through the wire format the endpoint serves. + restored = modelsync.ModelManifest.from_dict(manifest.to_dict()) + assert restored == manifest + + +def test_build_manifest_without_index_still_identifies(tmp_path): + root = _model(tmp_path / "model-b", with_index=False) + + manifest = build_manifest(root) + + assert manifest.index_sha256 is None + assert manifest.identity_sha256 + assert manifest.total_bytes > 0 + + +def test_build_manifest_rejects_non_model_dir(tmp_path): + root = tmp_path / "empty" + root.mkdir() + + with pytest.raises(ValueError, match="no safetensors"): + build_manifest(root) + + +@pytest.fixture +def manifest_client(tmp_path, monkeypatch): + """The manifest router mounted bare, backed by fixture model dirs.""" + + models_root = tmp_path / "models" + _model(models_root / "alpha") + settings = SimpleNamespace(get_effective_model_dirs=lambda: [str(models_root)]) + monkeypatch.setattr(modelsync, "_pool_getter", None) + monkeypatch.setattr(modelsync, "_settings_loader", lambda: settings) + app = FastAPI() + app.include_router(modelsync.manifest_router) + return TestClient(app), models_root + + +def test_manifest_endpoint_serves_known_model(manifest_client): + client, models_root = manifest_client + + response = client.get(f"/api/cluster/models/{models_root}/alpha/manifest") + + assert response.status_code == 200 + payload = response.json() + assert payload["schema_version"] == 1 + assert payload["index_sha256"] + assert payload["total_bytes"] > 0 + names = {item["name"] for item in payload["files"]} + assert "model-shared.safetensors" in names + assert "config.json" in names + + +def test_manifest_endpoint_404_for_unknown_model(manifest_client): + client, _ = manifest_client + + response = client.get("/api/cluster/models/no/such-model/manifest") + + assert response.status_code == 404 + + +def test_manifest_endpoint_refuses_paths_outside_model_dirs(manifest_client, tmp_path): + client, _ = manifest_client + outside = _model(tmp_path / "elsewhere") + + response = client.get(f"/api/cluster/models/{outside}/manifest") + + assert response.status_code == 403 + + +# -- manifest comparison / status ---------------------------------------------- + + +def test_compare_manifests_states(tmp_path): + root = _model(tmp_path / "source") + local = build_manifest(root) + + assert compare_manifests(local, None)["state"] == "missing" + + present = build_manifest(root) + assert compare_manifests(local, present)["state"] == "present" + assert compare_manifests(local, present)["bytes"] == local.total_bytes + + peer_root = _model(tmp_path / "peer") + (peer_root / "model-00002.safetensors").unlink() + partial = build_manifest(peer_root) + result = compare_manifests(local, partial) + assert result["state"] == "partial" + assert result["missing"] == ["model-00002.safetensors"] + assert result["bytes"] == local.total_bytes - sum( + item.size_bytes + for item in local.files + if item.name == "model-00002.safetensors" + ) + + (peer_root / "config.json").write_text(json.dumps({"model_type": "other"})) + mismatch = build_manifest(peer_root) + assert compare_manifests(local, mismatch)["state"] == "mismatch" + + +def test_status_uses_peer_manifest_over_http(tmp_path): + root = _model(tmp_path / "source") + manager = ModelSyncManager( + http_fetch=lambda url, timeout: build_manifest(root, model_id="m").to_dict(), + settings_loader=lambda: SimpleNamespace(get_effective_model_dirs=lambda: []), + ) + + result = manager.status("peer.local:8080", str(root)) + + assert result["state"] == "present" + assert result["bytes"] == result["total_bytes"] + + +def test_status_missing_when_peer_lacks_model(tmp_path): + root = _model(tmp_path / "source") + manager = ModelSyncManager(http_fetch=lambda url, timeout: None) + + result = manager.status("peer.local:8080", str(root)) + + assert result["state"] == "missing" + assert result["bytes"] == 0 + + +def test_peer_manifest_requires_a_port(tmp_path): + manager = ModelSyncManager() + + with pytest.raises(ValueError, match="no port"): + manager.peer_manifest("peer.local", "model") + + +# -- path_map resolution -------------------------------------------------------- + + +def test_path_map_resolution_with_fallback(): + deployment = _deployment( + path_map={"peer": "/Volumes/models/studio-copy"}, + ) + + assert deployment.model_path_for("peer") == "/Volumes/models/studio-copy" + # Unlisted nodes keep the shared coordinator path — pre-v2 behavior. + assert deployment.model_path_for("local") == "/models/shared" + # A deployment with no path_map resolves everywhere to the shared path. + legacy = _deployment() + assert legacy.model_path_for("peer") == "/models/shared" + + +def test_path_map_validation(): + with pytest.raises(ValueError, match="absolute"): + _deployment(path_map={"peer": "relative/dir"}) + with pytest.raises(ValueError, match="outside the deployment"): + _deployment(path_map={"stranger": "/models/x"}) + with pytest.raises(ValueError, match="absolute"): + _deployment(path_map={"peer": "/models/x\nmalformed"}) + assert validate_model_path_map(None) == {} + assert validate_model_path_map({"a": "/m"}, ("a",)) == {"a": "/m"} + + +def test_deployment_v2_round_trip_preserves_path_map(): + deployment = _deployment(path_map={"peer": "/Volumes/models/copy"}) + + restored = ClusterDeployment.from_dict(deployment.to_dict()) + + assert restored == deployment + assert restored.path_map == {"peer": "/Volumes/models/copy"} + assert deployment.to_dict()["schema_version"] == 2 + + +def test_legacy_v1_deployment_decodes_without_path_map(): + payload = _deployment().to_dict() + payload["schema_version"] = 1 + del payload["path_map"] + + restored = ClusterDeployment.from_dict(payload) + + assert restored.path_map == {} + assert restored.model_path_for("peer") == restored.model + + +def test_path_map_rides_the_worker_contract(): + deployment = _deployment(path_map={"peer": "/Volumes/models/copy"}) + + encoded = deployment.encode_worker_plan() + plan_hash, assignments, profiles, tp = decode_worker_contract(encoded) + + assert plan_hash == deployment.plan_hash + assert assignments == deployment.assignments + assert decode_worker_path_map(encoded) == {"peer": "/Volumes/models/copy"} + + +def test_v1_worker_contract_decodes_to_empty_path_map(): + deployment = _deployment() + raw = json.dumps( + { + "schema_version": 1, + "plan_hash": deployment.plan_hash, + "assignments": [ + assignment.to_dict() for assignment in deployment.assignments + ], + "performance_profiles": [], + "tensor_parallel_size": 1, + }, + sort_keys=True, + separators=(",", ":"), + ).encode() + encoded = base64.urlsafe_b64encode(zlib.compress(raw, level=9)).decode() + + assert decode_worker_path_map(encoded) == {} + plan_hash, assignments = decode_worker_contract(encoded)[:2] + assert plan_hash == deployment.plan_hash + assert len(assignments) == 2 + + +def test_plan_to_dict_carries_path_map_without_changing_hash(): + plan = ShardPlan( + model=synthetic_model_layout(total_weight_bytes=1024, layer_count=4), + assignments=( + PipelineAssignment("local", 0, 2, 4, 20, 2, 4, 64), + PipelineAssignment("peer", 1, 0, 2, 10, 2, 4, 32), + ), + plan_hash="f" * 64, + ) + mapped = ShardPlan( + model=plan.model, + assignments=plan.assignments, + plan_hash=plan.plan_hash, + path_map={"peer": "/Volumes/models/copy"}, + ) + + assert "path_map" not in plan.to_dict() + assert mapped.to_dict()["path_map"] == {"peer": "/Volumes/models/copy"} + # The layer split is path-independent: the map is display/staging + # metadata and must not mint a new plan identity. + assert mapped.plan_hash == plan.plan_hash + + +def test_placement_signature_covers_path_map_only_when_present(): + from omlx.cluster import routes + + plan = ShardPlan( + model=synthetic_model_layout(total_weight_bytes=1024, layer_count=4), + assignments=( + PipelineAssignment("local", 0, 2, 4, 20, 2, 4, 64), + PipelineAssignment("peer", 1, 0, 2, 10, 2, 4, 32), + ), + plan_hash="f" * 64, + ).to_dict() + + legacy = routes._placement_signature(plan) + assert routes._placement_signature(dict(plan)) == legacy + mapped = plan | {"path_map": {"peer": "/Volumes/models/copy"}} + assert routes._placement_signature(mapped) != legacy + + +# -- legacy deployments.json migration ------------------------------------------ + + +def _write_legacy_registry(base: Path, deployment: ClusterDeployment) -> Path: + entry = deployment.to_dict() + entry["schema_version"] = 1 + del entry["path_map"] + path = base / "cluster" / "deployments.json" + path.parent.mkdir(parents=True) + path.write_text(json.dumps({"schema_version": 1, "deployments": [entry]}, indent=2)) + return path + + +def test_legacy_deployments_json_migrates_on_load(tmp_path): + model = tmp_path / "model" + model.mkdir() + deployment = _deployment(str(model)) + path = _write_legacy_registry(tmp_path, deployment) + + registry = ClusterRegistry(tmp_path) + + loaded = registry.get_for_model(str(model)) + assert loaded is not None + assert loaded.path_map == {} + assert loaded.model_path_for("peer") == str(model) + assert registry.migrated_from == 1 + # The upgrade is persisted: the file now carries schema v2 and an + # explicit (empty) path_map, at the same private permissions. + on_disk = json.loads(path.read_text()) + assert on_disk["schema_version"] == 2 + assert on_disk["deployments"][0]["schema_version"] == 2 + assert on_disk["deployments"][0]["path_map"] == {} + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + # A v2 file loads cleanly on the next start, with no migration flagged. + assert ClusterRegistry(tmp_path).migrated_from is None + + +def test_registry_round_trip_preserves_path_map(tmp_path): + model = tmp_path / "model" + model.mkdir() + deployment = _deployment(str(model), path_map={"peer": "/Volumes/models/copy"}) + registry = ClusterRegistry(tmp_path) + + registry.upsert(deployment) + restored = ClusterRegistry(tmp_path).get_for_model(str(model)) + + assert restored is not None + assert restored.path_map == {"peer": "/Volumes/models/copy"} + assert restored.model_path_for("peer") == "/Volumes/models/copy" + + +# -- sync decisions -------------------------------------------------------------- + + +def test_auto_method_prefers_rsync_for_large_models_with_ssh_trust(): + manager = ModelSyncManager(ssh_trust=lambda target: True) + + assert manager.decide_method("user@peer", AUTO_RSYNC_THRESHOLD_BYTES + 1) == "rsync" + # At or below 20 GiB each node downloads its own shard files instead. + assert manager.decide_method("user@peer", AUTO_RSYNC_THRESHOLD_BYTES) == "download" + # No enrolled SSH trust: download regardless of size. + untrusted = ModelSyncManager(ssh_trust=lambda target: False) + assert ( + untrusted.decide_method("user@peer", AUTO_RSYNC_THRESHOLD_BYTES * 4) + == "download" + ) + # No SSH target at all: download. + assert manager.decide_method(None, AUTO_RSYNC_THRESHOLD_BYTES * 4) == "download" + + +def test_sync_rsync_invokes_resumable_transport(tmp_path): + root = _model(tmp_path / "source") + runs = [] + + def fake_rsync(argv, on_line): + runs.append(argv) + on_line(" 1,048,576 50% 100.00MB/s 0:00:01") + return 0 + + manager = ModelSyncManager( + ssh_trust=lambda target: True, + rsync_run=fake_rsync, + ) + events = [] + result = manager.sync( + "peer.local:8080", + str(root), + "rsync", + ssh_target="user@peer.local", + destination="/Volumes/models/copy", + on_progress=events.append, + ) + + argv = runs[0] + assert "--partial" in argv and "--append-verify" in argv + assert "BatchMode=yes" in argv[argv.index("-e") + 1] + assert argv[-2].endswith("/") + assert argv[-1] == "user@peer.local:/Volumes/models/copy" + assert result["method"] == "rsync" + transferring = [e for e in events if e.phase == "transferring"] + assert transferring, "rsync progress lines must surface as UI events" + assert transferring[0].bytes_done == 1_048_576 + assert transferring[0].bytes_per_second == pytest.approx(100.0 * 1000**2) + assert transferring[0].eta_seconds == 1.0 + assert events[-1].phase == "done" + # Events are also retained for polling UIs. + assert manager.events[-1].phase == "done" + + +def test_sync_rsync_requires_trust_and_target(tmp_path): + root = _model(tmp_path / "source") + manager = ModelSyncManager(ssh_trust=lambda target: False) + + with pytest.raises(ModelSyncError, match="enrolled SSH trust"): + manager.sync("peer", str(root), "rsync", ssh_target="user@peer") + with pytest.raises(ModelSyncError, match="ssh_target"): + manager.sync("peer", str(root), "rsync", ssh_target=None) + + +def test_sync_download_fetches_only_shard_files(tmp_path): + root = _model(tmp_path / "source") + calls = [] + + def fake_download(*, repo_id, allow_patterns, local_dir): + calls.append((repo_id, tuple(allow_patterns), local_dir)) + + manager = ModelSyncManager(hf_download=fake_download) + destination = tmp_path / "inbound" + + result = manager.sync( + "peer.local:8080", + str(root), + "download", + destination=destination, + repo_id="org/model-a", + start_layer=0, + end_layer=2, + ) + + repo_id, patterns, local_dir = calls[0] + assert repo_id == "org/model-a" + assert Path(local_dir) == destination + # Layers 0-1 live in model-00000; embeddings and sidecars always travel. + assert "model-00000.safetensors" in patterns + assert "model-shared.safetensors" in patterns + assert "config.json" in patterns + assert "model-00002.safetensors" not in patterns, "other stages stay on HF" + assert result["method"] == "download" + assert result["allow_patterns"] == sorted(patterns) + + +def test_sync_download_requires_repo_and_destination(tmp_path): + root = _model(tmp_path / "source") + manager = ModelSyncManager(hf_download=lambda **kw: None) + + with pytest.raises(ModelSyncError, match="repo ID"): + manager.sync("peer", str(root), "download", destination=tmp_path / "x") + with pytest.raises(ModelSyncError, match="destination"): + manager.sync("peer", str(root), "download", repo_id="org/m") + + +def test_sync_failure_emits_error_event(tmp_path): + root = _model(tmp_path / "source") + + def failing_rsync(argv, on_line): + return 23 + + manager = ModelSyncManager( + ssh_trust=lambda target: True, + rsync_run=failing_rsync, + ) + events = [] + + with pytest.raises(ModelSyncError, match="status 23"): + manager.sync( + "peer", + str(root), + "rsync", + ssh_target="user@peer", + on_progress=events.append, + ) + + assert events[-1].phase == "error" + + +def test_sync_auto_selects_rsync_for_large_models(tmp_path): + root = _model(tmp_path / "source") + runs = [] + downloads = [] + manager = ModelSyncManager( + ssh_trust=lambda target: True, + rsync_run=lambda argv, on_line: runs.append(argv) or 0, + hf_download=lambda **kw: downloads.append(kw), + ) + + # The fixture is far below 20 GiB, so auto picks download even with trust. + manager.sync( + "peer", + str(root), + "auto", + ssh_target="user@peer", + destination=tmp_path / "d", + repo_id="org/m", + ) + assert not runs and len(downloads) == 1 + + # Force the decision boundary: a manifest over the threshold picks rsync. + big = ModelSyncManager( + ssh_trust=lambda target: True, + rsync_run=lambda argv, on_line: runs.append(argv) or 0, + ) + import omlx.cluster.modelsync as ms + + original = ms.AUTO_RSYNC_THRESHOLD_BYTES + ms.AUTO_RSYNC_THRESHOLD_BYTES = 1 + try: + big.sync("peer", str(root), "auto", ssh_target="user@peer") + finally: + ms.AUTO_RSYNC_THRESHOLD_BYTES = original + assert len(runs) == 1 + + +# -- rsync helpers ---------------------------------------------------------------- + + +def test_build_rsync_argv_is_resumable_and_noninteractive(): + argv = build_rsync_argv( + "/models/src", + "user@peer.local", + "/Volumes/models/dst", + ssh_identity="~/.ssh/omlx_cluster", + ) + + assert argv[0] == "rsync" + assert "--partial" in argv + assert "--append-verify" in argv + assert "--info=progress2" in argv + ssh = argv[argv.index("-e") + 1] + assert "BatchMode=yes" in ssh and "omlx_cluster" in ssh + assert argv[-2] == "/models/src/" + assert argv[-1] == "user@peer.local:/Volumes/models/dst" + + +def test_build_rsync_argv_protects_remote_paths_and_validates_targets(): + destination = "/Volumes/model copies/$(touch should-not-run)" + argv = build_rsync_argv( + "/models/src", + "user@peer.local", + destination, + ) + + assert argv[-1] == f"user@peer.local:{shlex.quote(destination)}" + with pytest.raises(ValueError, match="SSH target"): + build_rsync_argv("/models/src", "peer;touch-nope", "/models/dst") + with pytest.raises(ValueError, match="single-line"): + build_rsync_argv("/models/src", "peer.local", "/models/dst\nother") + + +def test_parse_rsync_progress_lines(): + assert parse_rsync_progress(" 1,234,567 42% 123.45MB/s 0:01:23") == ( + 1_234_567, + 123.45 * 1000**2, + 83.0, + ) + assert parse_rsync_progress("100 100% 1.00GB/s 1:02:03")[2] == 3723.0 + assert parse_rsync_progress("sending incremental file list") is None + assert parse_rsync_progress("") is None + + +# -- allow-patterns ------------------------------------------------------------ + + +def test_allow_patterns_cover_whole_model_without_layer_range(tmp_path): + root = _model(tmp_path / "source") + + patterns = allow_patterns_for_shard(root) + + assert "model-00000.safetensors" in patterns + assert "model-00002.safetensors" in patterns + assert "model-shared.safetensors" in patterns + assert "config.json" in patterns + + +def test_allow_patterns_reject_inverted_range(tmp_path): + root = _model(tmp_path / "source") + + with pytest.raises(ValueError, match="0 <= start < end"): + allow_patterns_for_shard(root, 3, 3) + + +# -- launch preflight ------------------------------------------------------------- + + +def test_preflight_uses_per_node_model_paths(monkeypatch): + from omlx.cluster.launch import _local_runtime_versions, preflight_remote_hosts + from omlx.cluster.models import CLUSTER_PROTOCOL_VERSION + + versions = _local_runtime_versions() + calls = [] + + def runner(argv, **kwargs): + calls.append(argv) + return subprocess.CompletedProcess( + argv, + 0, + stdout=json.dumps( + versions + | { + "cluster-protocol": CLUSTER_PROTOCOL_VERSION, + "python": platform.python_version(), + "model-exists": True, + "admission-ceiling-bytes": 1024**4, + } + ), + stderr="", + ) + + deployment = _deployment( + "/nonexistent/shared", + path_map={"peer": "/Volumes/models/studio-copy"}, + ) + result = preflight_remote_hosts( + deployment, + python_executable="/opt/omlx/bin/python", + runner=runner, + ) + + assert len(result) == 2 + assert len(calls) == 1 + # The peer is probed at its own path, not the coordinator's. + assert "/Volumes/models/studio-copy" in calls[0][-1] + assert "/nonexistent/shared" not in calls[0][-1] diff --git a/tests/test_cluster_proportional_plan.py b/tests/test_cluster_proportional_plan.py new file mode 100644 index 0000000000..3e71f56f59 --- /dev/null +++ b/tests/test_cluster_proportional_plan.py @@ -0,0 +1,276 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Tests for the RAM-proportional largest-remainder N-node allocator.""" + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from omlx.cluster import routes +from omlx.cluster.planner import ( + ModelLayout, + NodeBudget, + PlanningError, + allocate_layers_proportional, + plan_proportional_pipeline, + plan_unequal_pipeline, +) + +GIB = 1024**3 + + +def _client() -> TestClient: + app = FastAPI() + app.include_router(routes.router) + return TestClient(app) + + +# --------------------------------------------------------------------------- +# allocate_layers_proportional +# --------------------------------------------------------------------------- + + +def test_proportional_split_matches_ram_ratio(): + # exo's reference case: 256 GB + 128 GB splits ≈⅔–⅓. + counts = allocate_layers_proportional(80, [256 * GIB, 128 * GIB]) + + assert counts == (53, 27) + assert sum(counts) == 80 + + +def test_proportional_split_three_equal_nodes(): + counts = allocate_layers_proportional(80, [100, 100, 100]) + + # 26.67 each: two nodes round up, ties break toward earlier position. + assert counts == (27, 27, 26) + assert sum(counts) == 80 + + +def test_proportional_split_guarantees_one_layer_per_node(): + counts = allocate_layers_proportional(10, [1000, 1]) + + assert counts == (9, 1) + + +def test_proportional_split_remainder_goes_to_largest_fraction(): + counts = allocate_layers_proportional(4, [1, 1, 1]) + + assert counts == (2, 1, 1) + + +def test_proportional_split_is_deterministic(): + shares = [37, 91, 55, 12] + + assert allocate_layers_proportional(61, shares) == allocate_layers_proportional( + 61, shares + ) + assert sum(allocate_layers_proportional(61, shares)) == 61 + + +def test_proportional_split_rejects_more_nodes_than_layers(): + with pytest.raises(PlanningError, match="cannot each receive a layer"): + allocate_layers_proportional(2, [1, 1, 1]) + + +@pytest.mark.parametrize("layer_count, shares", [(0, [1]), (-3, [1])]) +def test_proportional_split_rejects_nonpositive_layer_count(layer_count, shares): + with pytest.raises(ValueError): + allocate_layers_proportional(layer_count, shares) + + +@pytest.mark.parametrize("shares", [[0], [10, -1], [10, 0]]) +def test_proportional_split_rejects_nonpositive_shares(shares): + with pytest.raises(ValueError, match="positive"): + allocate_layers_proportional(8, shares) + + +# --------------------------------------------------------------------------- +# plan_proportional_pipeline +# --------------------------------------------------------------------------- + + +def _model(layers=(10, 10, 10, 10), **overrides): + return ModelLayout( + source="synthetic", + fixed_weight_bytes=1, + layer_weight_bytes=tuple(layers), + supports_pipeline=True, + **overrides, + ) + + +def _nodes(*specs): + return [ + NodeBudget( + node_id=node_id, + capacity_bytes=capacity, + reserve_bytes=reserve, + rank=rank, + **extra, + ) + for rank, (node_id, capacity, reserve, extra) in enumerate(specs) + ] + + +def test_proportional_plan_two_unequal_nodes(): + # usable 90 vs 50 → 4 layers split 2.57/1.43 → 3/1 after largest remainder. + plan = plan_proportional_pipeline( + _model(), + _nodes(("large", 100, 10, {}), ("small", 60, 10, {})), + ) + + assert plan.optimization == "ram-proportional" + by_rank = {item.rank: item for item in plan.assignments} + # Highest rank owns the earliest layers (MLX pipeline order). + assert (by_rank[1].start_layer, by_rank[1].end_layer) == (0, 1) + assert by_rank[1].node_id == "small" + assert (by_rank[0].start_layer, by_rank[0].end_layer) == (1, 4) + assert by_rank[0].node_id == "large" + # Full, contiguous coverage. + covered = sorted((item.start_layer, item.end_layer) for item in plan.assignments) + assert covered == [(0, 1), (1, 4)] + + +def test_proportional_plan_three_nodes_covers_every_layer_once(): + plan = plan_proportional_pipeline( + _model(layers=(10,) * 12), + _nodes( + ("a", 200, 10, {}), + ("b", 100, 10, {}), + ("c", 60, 10, {}), + ), + ) + + assert len(plan.assignments) == 3 + covered = sorted((item.start_layer, item.end_layer) for item in plan.assignments) + assert covered[0][0] == 0 + assert covered[-1][1] == 12 + for previous, following in zip(covered, covered[1:]): + assert previous[1] == following[0] + # Shares 190:90:50 → counts ∝ usable RAM, descending by node size. + counts = { + item.node_id: item.end_layer - item.start_layer for item in plan.assignments + } + assert counts["a"] > counts["b"] > counts["c"] + assert sum(counts.values()) == 12 + + +def test_proportional_plan_respects_weight_ceiling(): + with pytest.raises(PlanningError, match="small.*split cap|weight ceiling"): + plan_proportional_pipeline( + _model(), + _nodes( + ("large", 100, 10, {}), + ("small", 60, 10, {"max_weight_bytes": 5}), + ), + ) + + +def test_proportional_plan_validates_kv_fit(): + model = _model(kv_bytes_per_token_per_layer=1) + with pytest.raises(PlanningError, match="KV cache"): + plan_proportional_pipeline( + model, + _nodes(("large", 100, 10, {}), ("small", 60, 10, {})), + context_tokens=1_000_000, + ) + + +def test_proportional_plan_hash_is_stable_and_distinct(): + nodes = _nodes(("large", 100, 10, {}), ("small", 60, 10, {})) + + first = plan_proportional_pipeline(_model(), nodes) + second = plan_proportional_pipeline(_model(), nodes) + balanced = plan_unequal_pipeline(_model(), nodes) + + assert first.plan_hash == second.plan_hash + # The allocator is part of plan identity even when the layer ranges agree. + assert first.plan_hash != balanced.plan_hash + + +def test_proportional_plan_single_node_holds_everything(): + plan = plan_proportional_pipeline( + _model(), + _nodes(("only", 100, 10, {})), + ) + + assert len(plan.assignments) == 1 + assert (plan.assignments[0].start_layer, plan.assignments[0].end_layer) == (0, 4) + + +# --------------------------------------------------------------------------- +# Route-level allocation selection +# --------------------------------------------------------------------------- + + +def test_plan_route_runs_proportional_allocator(monkeypatch): + monkeypatch.setattr( + routes, + "inspect_safetensors_layout", + lambda path: _model(layers=(10,) * 12), + ) + + response = _client().post( + "/admin/api/cluster/plan", + json={ + "model_path": "/models/example", + "allocation": "proportional", + "nodes": [ + {"node_id": "a", "capacity_bytes": 200, "reserve_bytes": 10}, + {"node_id": "b", "capacity_bytes": 100, "reserve_bytes": 10}, + {"node_id": "c", "capacity_bytes": 60, "reserve_bytes": 10}, + ], + }, + ) + + assert response.status_code == 200, response.json() + payload = response.json() + assert payload["optimization"] == "ram-proportional" + assert payload["placement_signature"] + counts = {item["node_id"]: item["layer_count"] for item in payload["assignments"]} + assert counts["a"] > counts["b"] > counts["c"] + + +def test_plan_route_defaults_to_balanced_allocator(monkeypatch): + monkeypatch.setattr( + routes, + "inspect_safetensors_layout", + lambda path: _model(layers=(10,) * 12), + ) + + response = _client().post( + "/admin/api/cluster/plan", + json={ + "model_path": "/models/example", + "nodes": [ + {"node_id": "a", "capacity_bytes": 200, "reserve_bytes": 10}, + {"node_id": "b", "capacity_bytes": 100, "reserve_bytes": 10}, + ], + }, + ) + + assert response.status_code == 200, response.json() + assert response.json()["optimization"] == "memory" + + +def test_plan_route_rejects_proportional_tensor_parallel(monkeypatch): + monkeypatch.setattr( + routes, + "inspect_safetensors_layout", + lambda path: _model(layers=(10,) * 12), + ) + + response = _client().post( + "/admin/api/cluster/plan", + json={ + "model_path": "/models/example", + "allocation": "proportional", + "tensor_parallel_size": 2, + "nodes": [ + {"node_id": "a", "capacity_bytes": 200, "reserve_bytes": 10}, + {"node_id": "b", "capacity_bytes": 100, "reserve_bytes": 10}, + ], + }, + ) + + assert response.status_code == 400 + assert "pipeline-only" in response.json()["detail"] diff --git a/tests/test_cluster_replan.py b/tests/test_cluster_replan.py new file mode 100644 index 0000000000..77972a48e7 --- /dev/null +++ b/tests/test_cluster_replan.py @@ -0,0 +1,574 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Tests for the one-action cluster replan endpoint and its derivation helpers. + +Everything is offline: the engine pool, peer liveness, preflight, and model +layout inspection are doubled, and the registry lives in a tmp_path. +""" + +from dataclasses import replace +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from omlx.cluster import routes +from omlx.cluster.deployment import ClusterDeployment +from omlx.cluster.performance import NodePerformanceProfile +from omlx.cluster.planner import ModelLayout +from omlx.cluster.registry import configure_cluster_registry +from omlx.cluster.replan import ( + hosts_from_deployment, + nodes_from_deployment, + placement_view, + summarize_deployment, +) + +GIB = 1024**3 + + +def _client() -> TestClient: + app = FastAPI() + app.include_router(routes.router) + return TestClient(app) + + +def _layout(path): + return ModelLayout( + source=path, + fixed_weight_bytes=1, + layer_weight_bytes=(10, 10, 10, 10), + supports_pipeline=True, + ) + + +def _install_layout(monkeypatch): + monkeypatch.setattr(routes, "inspect_safetensors_layout", _layout) + monkeypatch.setattr( + routes, + "preflight_remote_hosts", + lambda deployment: [ + {"rank": rank, "node_id": host.node_id} + for rank, host in enumerate(deployment.hosts) + ], + ) + # Route tests establish peer reachability out of band; never let the + # synthetic hosts reach the real SSH liveness probe. + monkeypatch.setattr(routes, "check_peers", lambda *args, **kwargs: ()) + + +def _deployment_payload(model_path, *, capacity_large=100, capacity_small=60): + return { + "model_path": str(model_path), + "backend": "ring", + # The synthetic probe is the real network thing; replan coverage uses + # the memory-only path. + "auto_tune": False, + "nodes": [ + {"node_id": "large", "capacity_bytes": capacity_large, "reserve_bytes": 10}, + {"node_id": "small", "capacity_bytes": capacity_small, "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"]}, + ], + } + + +def _approval_for(payload): + plan = routes._create_cluster_plan( + routes.ClusterPlanRequest( + model_path=payload["model_path"], + nodes=payload["nodes"], + execution_profile=payload.get("execution_profile", "balanced"), + tensor_parallel_size=payload.get("tensor_parallel_size", 1), + target_context_tokens=payload.get("target_context_tokens", 8192), + ) + ) + return routes._placement_signature(plan.to_dict()) + + +class _ReadyEngine: + def __init__(self, deployment): + self.deployment = deployment + + async def generate(self, *_args, **_kwargs): + return SimpleNamespace(completion_tokens=1) + + def cluster_status(self): + return {"phase": "ready", "ranks": []} + + +class _RecordingPool: + """Engine-pool double that records the reload dance.""" + + def __init__(self, model_path): + self.model_path = str(model_path) + self.model_id = "public-model" + self.entry = SimpleNamespace(engine=None) + self.reloads = 0 + + def resolve_cluster_model_id(self, model_path): + assert model_path == self.model_path + return self.model_id + + def register_cluster_model(self, model_path, *, estimated_size): + assert model_path == self.model_path + assert estimated_size > 0 + return self.model_id, True + + def unregister_cluster_model(self, model_id): + assert model_id == self.model_id + return True + + def get_entry(self, model_id): + assert model_id == self.model_id + return self.entry + + async def prepare_cluster_reload(self, model_id): + assert model_id == self.model_id + self.reloads += 1 + self.entry.engine = None + + async def get_engine(self, model_id): + assert model_id == self.model_id + if self.entry.engine is None: + deployment = routes.get_cluster_registry().get_for_model(self.model_path) + self.entry.engine = _ReadyEngine(deployment) + return self.entry.engine + + +class _BusyPool(_RecordingPool): + def __init__(self, model_path): + super().__init__(model_path) + self.busy = False + + async def prepare_cluster_reload(self, model_id): + if self.busy: + from omlx.exceptions import ModelBusyError + + raise ModelBusyError(self.model_id, "replan the distributed cluster") + await super().prepare_cluster_reload(model_id) + + +@pytest.fixture() +def active_deployment(tmp_path, monkeypatch): + """Activate a two-node ring deployment and return its context.""" + + configure_cluster_registry(tmp_path) + model_path = tmp_path / "models" / "nemotron" + model_path.mkdir(parents=True) + _install_layout(monkeypatch) + pool = _RecordingPool(model_path) + monkeypatch.setattr(routes, "_get_engine_pool", lambda: pool) + + body = _deployment_payload(model_path) + body["approved_placement"] = _approval_for(body) + response = _client().post("/admin/api/cluster/deployments", json=body) + assert response.status_code == 200, response.json() + return SimpleNamespace( + model_path=model_path, + pool=pool, + deployment=response.json()["deployment"], + ) + + +def test_nodes_from_deployment_round_trip(active_deployment): + deployment = ClusterDeployment.from_dict(active_deployment.deployment) + + nodes = nodes_from_deployment(deployment) + + assert [node["node_id"] for node in nodes] == ["large", "small"] + assert nodes[0]["capacity_bytes"] == 100 + assert nodes[0]["reserve_bytes"] == 10 + assert nodes[0]["role"] == "headless" + # Split-control preferences are not recoverable from a signed plan. + assert "max_weight_bytes" not in nodes[0] + assert "target_weight_bytes" not in nodes[0] + + +def test_nodes_from_deployment_preserves_signed_performance(active_deployment): + deployment = ClusterDeployment.from_dict(active_deployment.deployment) + profiles = tuple( + NodePerformanceProfile( + node_id=assignment.node_id, + rank=assignment.rank, + decode_weight_bytes_per_second=100.0 - 40.0 * assignment.rank, + prefill_weight_bytes_per_second=90.0 - 30.0 * assignment.rank, + collective_latency_seconds=0.00003, + collective_bandwidth_bytes_per_second=6.2e9, + backend="ring", + measured_at="2026-08-22T00:00:00+00:00", + samples=5, + ) + for assignment in deployment.assignments + ) + deployment = replace(deployment, performance_profiles=profiles) + + nodes = nodes_from_deployment(deployment) + + assert nodes[0]["performance"] == profiles[0].to_dict() + assert nodes[1]["performance"] == profiles[1].to_dict() + + +def test_hosts_from_deployment_round_trip(active_deployment): + deployment = ClusterDeployment.from_dict(active_deployment.deployment) + + hosts = hosts_from_deployment(deployment) + + assert hosts[0]["ssh"] == "127.0.0.1" + assert hosts[1]["ssh"] == "studio.local" + assert hosts[1]["ips"] == ["192.168.5.2"] + + +def test_summarize_and_placement_view(active_deployment): + deployment = ClusterDeployment.from_dict(active_deployment.deployment) + + summary = summarize_deployment(deployment) + assert summary["deployment_id"] == deployment.deployment_id + assert summary["world_size"] == 2 + assert summary["backend"] == "ring" + assert len(summary["assignments"]) == 2 + + # The placement view must feed the same diff machinery a plan dict does. + signature = routes._placement_signature(placement_view(deployment)) + assert len(signature) == 16 + + +def test_replan_preview_derives_current_cluster(active_deployment): + response = _client().post( + "/admin/api/cluster/replan", + json={"deployment_id": active_deployment.deployment["deployment_id"]}, + ) + + assert response.status_code == 200, response.json() + payload = response.json() + assert payload["mode"] == "preview" + assert payload["derived"] == { + "nodes": True, + "hosts": True, + "backend": True, + "path_map": False, + } + assert payload["current"]["world_size"] == 2 + assert payload["changes"]["changed"] is False + assert len(payload["steps"]) == 3 + assert payload["plan"]["placement_signature"] + # A preview must not touch the pool at all. + assert active_deployment.pool.reloads == 1 # only the initial activation + + +def test_replan_inherits_tensor_parallelism_and_context(tmp_path, monkeypatch): + configure_cluster_registry(tmp_path) + model_path = tmp_path / "models" / "nemotron" + model_path.mkdir(parents=True) + _install_layout(monkeypatch) + monkeypatch.setattr( + routes, + "inspect_safetensors_layout", + lambda path: replace( + _layout(path), + tensor_parallel_heads=2, + tensor_parallel_kv_heads=2, + tensor_parallel_divisors=(2,), + supports_tensor_parallel=True, + ), + ) + pool = _RecordingPool(model_path) + monkeypatch.setattr(routes, "_get_engine_pool", lambda: pool) + + body = _deployment_payload(model_path) + body.update(tensor_parallel_size=2, target_context_tokens=32768) + body["approved_placement"] = _approval_for(body) + activation = _client().post("/admin/api/cluster/deployments", json=body) + assert activation.status_code == 200, activation.json() + + deployment_id = activation.json()["deployment"]["deployment_id"] + preview = _client().post( + "/admin/api/cluster/replan", + json={"deployment_id": deployment_id}, + ) + + assert preview.status_code == 200, preview.json() + assert preview.json()["plan"]["tensor_parallel_size"] == 2 + assert preview.json()["plan"]["cluster"]["target_context_tokens"] == 32768 + + +def test_replan_carries_path_map_forward(tmp_path, monkeypatch): + """A replan of a per-node-path deployment must not revert to same-path.""" + + configure_cluster_registry(tmp_path) + model_path = tmp_path / "models" / "nemotron" + model_path.mkdir(parents=True) + _install_layout(monkeypatch) + pool = _RecordingPool(model_path) + monkeypatch.setattr(routes, "_get_engine_pool", lambda: pool) + + path_map = { + "large": str(model_path), + "small": "/Volumes/shared/nemotron", + } + body = _deployment_payload(model_path) + body["path_map"] = path_map + plan = routes._create_cluster_plan( + routes.ClusterPlanRequest( + model_path=body["model_path"], + nodes=body["nodes"], + path_map=path_map, + ) + ) + body["approved_placement"] = routes._placement_signature(plan.to_dict()) + response = _client().post("/admin/api/cluster/deployments", json=body) + assert response.status_code == 200, response.json() + deployment_id = response.json()["deployment"]["deployment_id"] + assert response.json()["deployment"]["path_map"] == path_map + + preview = _client().post( + "/admin/api/cluster/replan", json={"deployment_id": deployment_id} + ) + assert preview.status_code == 200, preview.json() + payload = preview.json() + assert payload["derived"]["path_map"] is True + assert payload["plan"]["path_map"] == path_map + + # An explicit override wins over the carried-forward map. + override = _client().post( + "/admin/api/cluster/replan", + json={"deployment_id": deployment_id, "path_map": {}}, + ) + assert override.status_code == 200, override.json() + assert override.json()["derived"]["path_map"] is False + + +def test_replan_preview_detects_changed_split(active_deployment): + response = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "nodes": [ + {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, + # A bigger reserve on the small node moves layers to the large one. + {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 40}, + ], + }, + ) + + assert response.status_code == 200, response.json() + payload = response.json() + assert payload["derived"]["nodes"] is False + assert payload["derived"]["hosts"] is True + assert payload["changes"]["changed"] is True + + +def test_replan_applied_runs_full_dance(active_deployment): + preview = ( + _client() + .post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "target_context_tokens": 16384, + }, + ) + .json() + ) + + response = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "target_context_tokens": 16384, + "approved_placement": preview["plan"]["placement_signature"], + }, + ) + + assert response.status_code == 200, response.json() + payload = response.json() + assert payload["mode"] == "applied" + assert payload["readiness"]["canary_passed"] is True + assert ( + payload["replan"]["previous"]["deployment_id"] + == (active_deployment.deployment["deployment_id"]) + ) + # One reload for the initial activation, one for the replan. + assert active_deployment.pool.reloads == 2 + engine = active_deployment.pool.entry.engine + assert engine.deployment.target_context_tokens == 16384 + + +def test_replan_rejects_a_stale_approval(active_deployment): + _client().post( + "/admin/api/cluster/replan", + json={"deployment_id": active_deployment.deployment["deployment_id"]}, + ) + + response = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "target_context_tokens": 4096, + "approved_placement": "f" * 16, + }, + ) + + assert response.status_code == 409 + assert "not the plan" in response.json()["detail"] + assert active_deployment.pool.reloads == 1 + + +@pytest.mark.parametrize( + "change", + [{"target_context_tokens": 16384}, {"path_map": {"small": "/models/new"}}], + ids=["context", "path"], +) +def test_replan_refuses_to_interrupt_active_requests(tmp_path, monkeypatch, change): + configure_cluster_registry(tmp_path) + model_path = tmp_path / "models" / "nemotron" + model_path.mkdir(parents=True) + _install_layout(monkeypatch) + pool = _BusyPool(model_path) + monkeypatch.setattr(routes, "_get_engine_pool", lambda: pool) + + body = _deployment_payload(model_path) + body["approved_placement"] = _approval_for(body) + response = _client().post("/admin/api/cluster/deployments", json=body) + assert response.status_code == 200, response.json() + deployment_id = response.json()["deployment"]["deployment_id"] + pool.busy = True + + preview = ( + _client() + .post( + "/admin/api/cluster/replan", + json={ + "deployment_id": deployment_id, + **change, + }, + ) + .json() + ) + response = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": deployment_id, + **change, + "approved_placement": preview["plan"]["placement_signature"], + }, + ) + + assert response.status_code == 409 + assert "serving a request" in response.json()["detail"] + # The old deployment must survive a refused replan. + listed = _client().get("/admin/api/cluster/deployments") + assert listed.json()["deployments"][0]["deployment_id"] == deployment_id + + assert pool.entry.engine.deployment.path_map == {} + assert listed.json()["deployments"][0]["path_map"] == {} + + +def test_replan_unknown_deployment_is_404(tmp_path, monkeypatch): + configure_cluster_registry(tmp_path) + _install_layout(monkeypatch) + monkeypatch.setattr( + routes, "_get_engine_pool", lambda: _RecordingPool(tmp_path / "m") + ) + + response = _client().post( + "/admin/api/cluster/replan", json={"deployment_id": "nope"} + ) + + assert response.status_code == 404 + + +def test_replan_without_context_requires_explicit_cluster(tmp_path, monkeypatch): + configure_cluster_registry(tmp_path) + _install_layout(monkeypatch) + monkeypatch.setattr( + routes, "_get_engine_pool", lambda: _RecordingPool(tmp_path / "m") + ) + + response = _client().post( + "/admin/api/cluster/replan", + json={"model_path": "/models/never-deployed"}, + ) + + assert response.status_code == 400 + assert "nodes and hosts" in response.json()["detail"] + + +def test_replan_membership_change_adds_a_node(active_deployment): + """N-node replan: explicit nodes/hosts express the membership change.""" + + nodes = [ + {"node_id": "large", "capacity_bytes": 100, "reserve_bytes": 10}, + {"node_id": "small", "capacity_bytes": 60, "reserve_bytes": 10}, + {"node_id": "mini", "capacity_bytes": 50, "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"]}, + {"node_id": "mini", "ssh": "mini.local", "ips": ["192.168.5.3"]}, + ] + preview = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "nodes": nodes, + "hosts": hosts, + }, + ) + assert preview.status_code == 200, preview.json() + assert preview.json()["plan"]["assignments"][2]["node_id"] == "mini" + + response = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": active_deployment.deployment["deployment_id"], + "nodes": nodes, + "hosts": hosts, + "approved_placement": preview.json()["plan"]["placement_signature"], + }, + ) + + assert response.status_code == 200, response.json() + payload = response.json() + assert payload["deployment"].get("world_size", True) + assert len(payload["deployment"]["assignments"]) == 3 + assert payload["replan"]["previous"]["world_size"] == 2 + ranks = sorted( + (item["rank"], item["node_id"]) for item in payload["deployment"]["assignments"] + ) + assert ranks == [(0, "large"), (1, "small"), (2, "mini")] + + +@pytest.mark.parametrize( + "old_paths,new_paths", + [ + ({}, {"small": "/models/new"}), + ({"small": "/models/old"}, {"small": "/models/new"}), + ({"small": "/models/old"}, {}), + ({"small": "/models/old"}, {"small": "/models/old"}), + ], + ids=["add", "change", "remove", "unchanged"], +) +def test_replan_path_map_matches_resident_engine( + active_deployment, old_paths, new_paths +): + pool = active_deployment.pool + current = replace(pool.entry.engine.deployment, path_map=old_paths) + pool.entry.engine.deployment = current + registry = routes.get_cluster_registry() + registry.upsert(current) + previous_engine = pool.entry.engine + reloads = pool.reloads + request = {"deployment_id": current.deployment_id, "path_map": new_paths} + client = _client() + preview = client.post("/admin/api/cluster/replan", json=request) + assert preview.status_code == 200, preview.json() + request["approved_placement"] = preview.json()["plan"]["placement_signature"] + applied = client.post("/admin/api/cluster/replan", json=request) + assert applied.status_code == 200, applied.json() + assert pool.reloads == reloads + int(old_paths != new_paths) + assert pool.entry.engine.deployment.path_map == new_paths + assert registry.get(current.deployment_id).path_map == new_paths + assert (pool.entry.engine is previous_engine) == (old_paths == new_paths) 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 425e1235f0..62b3803a08 100644 --- a/tests/test_cluster_seams.py +++ b/tests/test_cluster_seams.py @@ -74,7 +74,17 @@ def test_no_cluster_route_is_unreachable_from_the_dashboard(): both worth knowing about. """ - allowed_without_caller: set[str] = set() + # 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_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_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index e24acfcb66..a6404d9326 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -1257,6 +1257,142 @@ def test_disk_backed_bf16_ple_reads_only_requested_rows(tmp_path): embedding.close() +@pytest.fixture +def disk_ple_reader(tmp_path): + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp import language as ple + + # 166-byte rows exercise reads that straddle page boundaries. + dense = (mx.arange(4096 * 83).reshape(4096, 83) / 3.0).astype(mx.bfloat16) + path = tmp_path / "ple.safetensors" + mx.save_safetensors(str(path), {"weight": dense}) + reader = ple._SafeTensorMMap(path) + try: + yield ple, reader, dense + finally: + reader.close() + + +@pytest.mark.parametrize("short_reads", [False, True]) +def test_disk_backed_ple_page_prefetch_returns_identical_rows( + disk_ple_reader, monkeypatch, short_reads +): + """Read every required page once, retry short reads, and skip warm prefetch.""" + ple, reader, dense = disk_ple_reader + page_size = ple._PLE_PAGE_SIZE + row_bytes = 83 * 2 + base = reader._data_start + reader._header["weight"]["data_offsets"][0] + crossing = next( + row + for row in range(4096) + if (base + row * row_bytes) % page_size + row_bytes > page_size + ) + indices = [crossing, crossing, 0, 1, 1000, 2000, 3000, 4000, 4095] + expected = dense[mx.array(indices, dtype=mx.int32)] + # Enumerate the byte spans independently of the prefetch endpoint formula. + needed_pages = { + offset // page_size + for row in indices + for offset in range(base + row * row_bytes, base + (row + 1) * row_bytes) + } + reads = [] + original_pread = ple.os.pread + + def record_pread(fd, size, offset): + limit = min(size, page_size // 3) if short_reads else size + data = original_pread(fd, limit, offset) + reads.append((offset, len(data))) + return data + + monkeypatch.setattr(ple.os, "pread", record_pread) + assert mx.array_equal(reader.rows("weight", indices), expected).item() + assert {offset // page_size for offset, _ in reads} == needed_pages + file_size = reader.path.stat().st_size + for page in needed_pages: + spans = sorted( + (offset, length) + for offset, length in reads + if offset // page_size == page and length + ) + cursor = page * page_size + for offset, length in spans: + assert offset == cursor + cursor += length + assert cursor == min((page + 1) * page_size, file_size) + assert all(reader._seen_pages[page] for page in needed_pages) + + # Fix the measured time so a busy test host cannot trigger reactivation. + monkeypatch.setattr(ple, "time", SimpleNamespace(perf_counter=lambda: 0.0)) + reads.clear() + assert mx.array_equal(reader.rows("weight", indices), expected).item() + assert reads == [] + + +@pytest.mark.parametrize("row_count", [0, 1, 8]) +def test_disk_backed_ple_small_gathers_skip_prefetch( + disk_ple_reader, monkeypatch, row_count +): + _, reader, dense = disk_ple_reader + prefetch = MagicMock(side_effect=AssertionError("Unexpected prefetch")) + monkeypatch.setattr(reader, "_prefetch_missing_pages", prefetch) + indices = list(range(row_count)) + expected = dense[mx.array(indices, dtype=mx.int32)] + assert mx.array_equal(reader.rows("weight", indices), expected).item() + prefetch.assert_not_called() + + +def test_disk_backed_ple_rearms_seen_bitmap_on_slow_gather( + disk_ple_reader, monkeypatch, caplog +): + """Control both clocks to verify the budget, retry, and interval boundary.""" + ple, reader, dense = disk_ple_reader + indices = list(range(16)) + expected = dense[mx.array(indices, dtype=mx.int32)] + pread = MagicMock(wraps=ple.os.pread) + monkeypatch.setattr(ple.os, "pread", pread) + budget = ( + ple._PLE_REARM_FLOOR_SECONDS + len(indices) * ple._PLE_REARM_PER_ROW_SECONDS + ) + interval = ple._PLE_REARM_MIN_INTERVAL_SECONDS + caplog.set_level("INFO", logger=ple.__name__) + + def gather(elapsed, now): + ticks = iter((0.0, elapsed)) + monkeypatch.setattr( + ple, + "time", + SimpleNamespace(perf_counter=lambda: next(ticks), monotonic=lambda: now), + ) + values = reader.rows("weight", indices) + assert mx.array_equal(values, expected).item() + + gather(0.0, 1000.0) + assert pread.call_count > 0 + pread.reset_mock() + gather(budget / 2, 1000.0) + assert reader._rearm_count == 0 + assert any(reader._seen_pages) + pread.assert_not_called() + + gather(budget * 2, 1000.0) + assert reader._rearm_count == 1 + assert not any(reader._seen_pages) + assert "re-armed seen-page bitmap" in caplog.text + pread.assert_not_called() + + gather(0.0, 1001.0) + assert pread.call_count > 0 + assert any(reader._seen_pages) + pread.reset_mock() + gather(budget * 2, 1000.0 + interval - 1.0) + assert reader._rearm_count == 1 + assert any(reader._seen_pages) + gather(budget * 2, 1000.0 + interval) + assert reader._rearm_count == 2 + assert not any(reader._seen_pages) + pread.assert_not_called() + + @pytest.mark.parametrize("bits", [2, 3, 4, 5, 6, 8]) def test_disk_backed_affine_ple_supports_all_oq_bits(tmp_path, bits): compat.apply_mlx_vlm_qwen4_exp_compat_patch()