From fc69aecacb9927bd4be31ebb2e818f342369385a Mon Sep 17 00:00:00 2001 From: Scott Kim Date: Tue, 8 Sep 2026 12:54:00 +0900 Subject: [PATCH 01/29] fix: use concurrent pread for Qwen4-Exp PLE row lookups (~10x SSD throughput) (#3287) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: use concurrent pread for Qwen4-Exp PLE row lookups _SafeTensorMMap.rows() gathers SSD-backed PLE (n-gram bank) rows with numpy fancy-indexing over an mmap'd buffer opened with MADV_RANDOM. Each row touch that isn't resident blocks synchronously on a page fault, and the gather walks the index array in a single thread, so N row lookups serialize into N blocking page faults with zero overlap. The hardware has plenty of parallelism to hide that latency; the code just never asks for it. Measured on an M4 Max (internal NVMe): 500 random 4KB reads, serial: 9,063 IOPS (110us/read) 500 random 4KB reads, 32 threads: 98,771 IOPS (x10.9) 500 random 4KB reads, 64 threads: 99,626 IOPS (x11.0) This patch replaces the mmap fancy-index gather with a thread pool of os.pread() calls on the same fd (threads, not asyncio/io_uring, because os.pread releases the GIL for the syscall duration). Verified against real PLE shard files that the patched and original code paths return byte-identical output. End-to-end on a 40k-token prompt (cold, no prefix-cache reuse), tested against two independent qwen4_exp checkpoints: jedisct1/Qwen3.8-Flash-Next-oQ4e-MTP-128k (2-3bit PLE, batched engine via a bundled omlx_support shim using the same rows() logic): cold TTFT 216.85s -> 6.54s (x33) warm TTFT 12.63s -> 6.02s (x2.1) generation 43.70 -> 59.92 tok/s Vontra/Qwen3.8-Flash-Next-MLX-oQ4-MTP (4bit PLE, vlm engine, this vendored implementation directly): isolated row-read throughput: 9,166 -> 109,636 rows/s (x12.0) steady-state TTFT: ~6-7.5s (first-ever cold-disk-cache run was an outlier at 108s, not reproducible on subsequent runs) Generation speed improves too because PLE is looked up on every decode step, not just during prefill. Scope: only affects OMLX_QWEN4_PLE_MODE=mmap (or equivalent SSD-backed PLE offload). resident mode doesn't go through this code path. Ran the existing qwen4_exp test suite (tests/test_mlx_vlm_qwen4_exp_compat.py, tests/test_vlm_qwen4_exp_loader.py, tests/test_qwen4_exp_residency.py, tests/test_qwen4_exp_mtp_admin_gate.py) — 41/41 pass, no regressions. * perf(qwen4_exp): gate concurrent PLE prefetch to cold pages, keep warm mmap gather Builds on #3287 by scott-kim-7: the serialized-page-fault root cause and the concurrent os.pread thread pool are theirs. This variant keeps both, but gates the pool with a per-reader seen-page bitmap so only never-touched pages are prefetched concurrently and fully-warm lookups keep the original near-free mmap memcpy gather (measured 0.14us/row vs 22us/row for unconditional per-row pread on warm pages). Includes a byte-identity regression test over a multi-page gather with straddling rows, and handles the short-read nit raised on #3287. * perf(qwen4_exp): re-arm the PLE seen-page bitmap when a warm gather lags memcpy The seen-page bitmap is write-once, so a page the OS evicted after we marked it seen would fall back to a serial minor fault forever. With a 37.5GB table under serving pressure eviction is the steady state (measured ~24% resident after 2.5h), not an edge case. mincore() detects eviction precisely but costs ~4.5ms per shard-span call, so instead every fully-seen gather self-instruments: wall time over a memcpy budget (floor + per-row allowance) is the signature of minor faults, so clear the reader's bitmap and let the next gather re-warm through the concurrent pread path. Re-arm is rate-limited to once per reader per minute and logs one INFO line (elapsed vs budget, per-shard counter) so the event is visible in field logs. Verified: 50 warm gathers worst-case 0.84ms vs an 8.69ms budget (no false re-arm), re-arm itself free, re-warm costs one concurrent pread round (9us/row), steady warm speed resumes at 0.18us/row. --------- Co-authored-by: 谢永梁 <21219102@qq.com> Co-authored-by: Claude Opus 5 --- .../mlx_vlm/models/qwen4_exp/language.py | 132 +++++++++++++++- tests/test_mlx_vlm_qwen4_exp_compat.py | 141 ++++++++++++++++++ 2 files changed, 266 insertions(+), 7 deletions(-) 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..c49886b330 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,37 @@ def _find_nth_prime_after(start: int, count: int) -> int: return prime +# SSD-backed PLE row lookups hit a ~40GB mmap'd table with ~16 scattered +# rows per token. When a page is already resident the mmap gather is a pure +# memcpy; when it is not, the access blocks ~100us on a synchronous page +# fault (MADV_RANDOM is correct here: rows are random, so readahead mostly +# fetches bytes nobody asked for). Only the cold phase needs help: a +# per-reader seen-page bitmap remembers which pages this process already +# pulled in, and the first time a page is needed the whole batch of missing +# pages is pread() concurrently from a thread pool so the SSD controller's +# parallelism overlaps the waits (~4096-row gather: ~12ms parallel vs ~400ms +# serialized page faults measured on Apple Silicon). A fully-warm call pays +# only a bitmap probe and keeps the original memcpy gather speed. +# Eviction honesty: the bitmap is write-once, but memory pressure makes +# eviction the steady state (measured: a 37.5GB PLE table falls to ~24% +# resident after hours of serving). mincore() detects eviction precisely +# but costs ~4.5ms per shard-span call — unpayable on the hot path — so +# instead every fully-seen gather self-instruments: if its wall time blows +# the memcpy budget (a floor plus a per-row allowance, ~1% eviction rate +# trips it, normal warm jitter does not), the bitmap re-arms and the next +# gather treats every page as fresh again, re-warming the evicted ones +# through the same concurrent pread path. Re-arm is rate-limited per +# reader. Threads (not asyncio/io_uring) because os.pread releases the GIL +# for the syscall duration, which is enough here. +_PLE_IO_POOL = ThreadPoolExecutor(max_workers=48, thread_name_prefix="ple-io") +_PLE_PAGE_SIZE = os.sysconf("SC_PAGE_SIZE") +# Warm gather runs at ~0.1us/row; a minor fault costs ~1000x that, so this +# budget trips on real eviction and sleeps through everything else. +_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 +1879,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 +1912,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 +1942,67 @@ 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: + """Warm up pages behind the requested rows. + + Returns True when every needed page was already marked seen (a + fully-warm gather whose wall time is worth timing for eviction). + """ + 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: + """Re-arm the seen-page bitmap when a fully-seen gather lags memcpy. + + A warm gather is a page-cache memcpy at ~0.1us/row; a page the OS + evicted after we marked it seen turns it into serial ~100us minor + faults. Sustained over-budget wall time is exactly that signature, + so clear the bitmap and let the next gather re-warm the evicted + pages through the concurrent pread path. Rate-limited so a reader + re-arms 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/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index e24acfcb66..48607af8b3 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -1257,6 +1257,147 @@ def test_disk_backed_bf16_ple_reads_only_requested_rows(tmp_path): embedding.close() +def test_disk_backed_ple_page_prefetch_returns_identical_rows(tmp_path): + """mincore+pread cold prefetch must not perturb gathered bytes. + + Regression guard for the cold-only prefetch path in _SafeTensorMMap: + 166-byte rows over a multi-page span straddle page boundaries often, + so any page-math mistake surfaces as corrupted rows. + """ + import numpy as np + + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp.language import ( + _PLE_PAGE_SIZE, + DiskBackedShardedEmbedding, + ) + + prefix = ( + "model.language_model.layers.1.ple.ple_embedding.ngram_embedding" + ) + rows, dims = 4096, 83 + dense = ( + mx.arange(rows * dims, dtype=mx.float32).reshape(rows, dims) / 3.0 + ).astype(mx.bfloat16) + filename = "model-00001-of-00001.safetensors" + mx.save_safetensors( + str(tmp_path / filename), + {f"{prefix}.shard_0.weight": dense}, + metadata={"format": "mlx"}, + ) + (tmp_path / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": {f"{prefix}.shard_0.weight": filename}}), + encoding="utf-8", + ) + + embedding = DiskBackedShardedEmbedding( + tmp_path, prefix, num_embeddings=rows, dims=dims, num_shards=1 + ) + try: + reader = next(iter(embedding._readers.values())) + assert reader._seen_pages is not None + rng = np.random.default_rng(7) + idx = np.sort(rng.integers(0, rows, size=512)) + values = embedding(mx.array(idx.reshape(1, -1), dtype=mx.int32)) + expected = dense[mx.array(idx.tolist(), dtype=mx.int32)][None] + assert mx.array_equal(values, expected).item() + # Gathered pages are marked seen so warm repeats skip the pool. + start = reader._data_start + reader._header[ + f"{prefix}.shard_0.weight" + ]["data_offsets"][0] + offs = start + idx * (dims * 2) + needed = np.unique( + np.concatenate( + (offs // _PLE_PAGE_SIZE, (offs + dims * 2 - 1) // _PLE_PAGE_SIZE) + ) + ) + assert all(reader._seen_pages[page] == 1 for page in needed.tolist()) + # Fully-warm repeat call takes the bitmap-hit shortcut. + warm = embedding(mx.array(idx.reshape(1, -1), dtype=mx.int32)) + assert mx.array_equal(warm, expected).item() + finally: + embedding.close() + + +def test_disk_backed_ple_rearms_seen_bitmap_on_slow_gather(tmp_path, caplog): + """A warm gather that lags memcpy must re-arm the bitmap exactly once. + + Regression guard for the eviction re-arm: once every page is marked + seen, only a wall-time over-budget (the signature of evicted pages + turning the gather into serial minor faults) may clear the bitmap, and + the next gather must re-warm and re-mark through the fresh path. + """ + import logging + + import numpy as np + + compat.apply_mlx_vlm_qwen4_exp_compat_patch() + from mlx_vlm.models.qwen4_exp import language as ple + from mlx_vlm.models.qwen4_exp.language import DiskBackedShardedEmbedding + + prefix = ( + "model.language_model.layers.1.ple.ple_embedding.ngram_embedding" + ) + rows, dims = 4096, 83 + dense = ( + mx.arange(rows * dims, dtype=mx.float32).reshape(rows, dims) / 5.0 + ).astype(mx.bfloat16) + filename = "model-00001-of-00001.safetensors" + mx.save_safetensors( + str(tmp_path / filename), + {f"{prefix}.shard_0.weight": dense}, + metadata={"format": "mlx"}, + ) + (tmp_path / "model.safetensors.index.json").write_text( + json.dumps({"weight_map": {f"{prefix}.shard_0.weight": filename}}), + encoding="utf-8", + ) + + embedding = DiskBackedShardedEmbedding( + tmp_path, prefix, num_embeddings=rows, dims=dims, num_shards=1 + ) + try: + reader = next(iter(embedding._readers.values())) + rng = np.random.default_rng(11) + idx = np.sort(rng.integers(0, rows, size=512)) + query = mx.array(idx.reshape(1, -1), dtype=mx.int32) + expected = dense[mx.array(idx.tolist(), dtype=mx.int32)][None] + + # First call marks pages; a warm repeat under the real budget + # (memcpy-fast gather) must leave the bitmap intact. + embedding(query) + embedding(query) + assert sum(reader._seen_pages) > 0 + + old_floor = ple._PLE_REARM_FLOOR_SECONDS + old_per_row = ple._PLE_REARM_PER_ROW_SECONDS + try: + # Force the slow-gather signature: with a zero budget, any warm + # gather re-arms, clears the bitmap once, and the next gather + # re-warms through the fresh path. + ple._PLE_REARM_FLOOR_SECONDS = 0.0 + ple._PLE_REARM_PER_ROW_SECONDS = 0.0 + with caplog.at_level( + logging.INFO, logger="mlx_vlm.models.qwen4_exp.language" + ): + embedding(query) + assert sum(reader._seen_pages) == 0 + assert reader._rearm_count == 1 + assert "re-armed seen-page bitmap" in caplog.text + values = embedding(query) + assert sum(reader._seen_pages) > 0 + assert mx.array_equal(values, expected).item() + # Rate limit: still over budget, but the interval blocks a + # second clear and the freshly-marked pages survive. + embedding(query) + assert sum(reader._seen_pages) > 0 + finally: + ple._PLE_REARM_FLOOR_SECONDS = old_floor + ple._PLE_REARM_PER_ROW_SECONDS = old_per_row + finally: + embedding.close() + + @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() From 7c192abf88d9854746ea6f0a6457965af1167844 Mon Sep 17 00:00:00 2001 From: Jonathan Spangler Date: Mon, 7 Sep 2026 20:56:39 -0700 Subject: [PATCH 02/29] feat(cluster): add qualification, staging, planning, and deployment (#3256) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * cluster v2 Module D checkpoint: path_map schema v2 + modelsync + manifest endpoint - deployment.py: path_map field, model_path_for(), schema v2 (v1 decodes to empty map), path_map rides the worker contract, decode_worker_path_map() - registry.py: deployments.json schema v1->v2 in-memory migration, persisted atomically on load, migrated_from reported - planner.py: ShardPlan.path_map passthrough (excluded from plan_hash) - routes.py: path_map on plan/deployment requests, placement signature folds path_map when present, staging honors per-node destinations - launch.py: preflight probes each node at its own path_map path - inference_worker.py: rank resolves its model path from the signed contract - modelsync.py: ModelSyncManager (status/sync, auto|rsync|download), manifest builder + GET /api/cluster/models/{model_id}/manifest, progress events - tests: 32 new offline tests (manifest fixture, path_map, v1 migration, sync decisions with mocked transports) * fix: route rsync through shared cluster SSH policy; fake path_map decoder in worker test harness - modelsync.build_rsync_argv now builds its -e command from ssh_policy.cluster_ssh_options() (seam test compliance: no literal ssh argv outside the shared policy) - test_cluster_inference_worker harness fakes decode_worker_path_map next to decode_worker_contract; the fake plan string is not a real contract * planner: RAM-proportional largest-remainder allocator for N-node plans allocate_layers_proportional (exact Fraction arithmetic, min one layer per node, deterministic tie-breaks) plus plan_proportional_pipeline, sharing the assignment/fit/hash tail with plan_unequal_pipeline via _finish_pipeline_plan. The balanced planner's hash payload is byte-identical to before. Routes gain an additive allocation field ('balanced' default) on plan/deployment/replan requests; proportional is pipeline-only. * fix(cluster): preserve proportional allocation routing * test: proportional allocator — ratios, min-1, tie-breaks, ceilings, KV fit, route wiring * runtime: one-action POST /admin/api/cluster/replan (deactivate→re-plan→reload) Extract the activation pipeline into _activate_and_report so the replan endpoint and the explicit /deployments approval share one code path. The replan endpoint derives nodes/hosts/backend from the current deployment when not posted, renders a signed preview with a placement diff, and on approval runs the quiescence-gated unload (engine-pool prepare_cluster_ reload) whose distributed supervisor teardown is verified before the registry swap and eager reload. * test: replan endpoint — preview/apply dance, busy refusal, derivation, N-node membership change * test: fix busy-pool replan test — an unchanged plan short-circuits the reload * cluster: thread path_map through the replan endpoint Agent E flagged the seam: ClusterReplanRequest had no path_map and the replan derivation dropped the current deployment's per-node paths, silently reverting a heterogeneous-path cluster to same-path resolution. Add path_map to ClusterReplanRequest, derive it from the current deployment when not posted (tracked in the 'derived' map), and pass it into the effective ClusterDeploymentRequest. Explicit override (including an empty map) wins. Tests updated + carry-forward coverage added. * Preserve measured rank speeds across replans * Preserve TP topology across cluster replans * feat(cluster): recommend tensor on known-fast links in catalogue The catalogue tie-break preferred pipeline at equal width because it survives slow links. When the paired registry shows every requested peer reachable over JACCL/Thunderbolt RDMA, tensor parallelism is the better recommendation — it splits per-token compute across the group. - _splits/assess_model/catalogue_for_cluster gain prefer_tensor (default False: API behavior unchanged for unknown links) - catalogue endpoint derives it from the paired device registry: every non-self requested node must be paired with jaccl/thunderbolt caps; unknown or unpaired peers fail closed to pipeline - 4 new tests; 33 catalogue + 1702 cluster/model tests green * fix(cluster): strip IPv6 zone ids, order routable IPs first in hostfiles macOS announces Thunderbolt interfaces as fe80::…%en10; mlx's address parser cannot read the zone id and ranks died at startup with 'Can't parse address fe80::…%en10:56758'. _validate_ip now strips the zone (machine-local by definition, never valid on the wire) and the hostfile orders routable addresses ahead of link-local fallbacks, so a Mac with configured 10.x Thunderbolt IPs never advertises the ambiguous one first. 3 tests pin the exact failure. * fix(cluster): reconcile portable paths and planning lint * test(cluster): mark backend-first replan seam explicitly * fix(cluster): protect remote rsync paths from shell interpretation --------- Co-authored-by: jonathan308 --- omlx/cluster/catalogue.py | 47 +- omlx/cluster/deployment.py | 170 ++++- omlx/cluster/inference_worker.py | 60 +- omlx/cluster/launch.py | 78 +-- omlx/cluster/modelsync.py | 863 ++++++++++++++++++++++++ omlx/cluster/planner.py | 244 +++++-- omlx/cluster/registry.py | 24 +- omlx/cluster/replan.py | 122 ++++ omlx/cluster/routes.py | 387 ++++++++++- omlx/cluster/staging.py | 55 +- omlx/server.py | 13 + tests/test_cluster_catalogue.py | 104 ++- tests/test_cluster_deployment.py | 32 +- tests/test_cluster_inference_worker.py | 7 + tests/test_cluster_modelsync.py | 695 +++++++++++++++++++ tests/test_cluster_proportional_plan.py | 276 ++++++++ tests/test_cluster_replan.py | 532 +++++++++++++++ tests/test_cluster_seams.py | 4 +- 18 files changed, 3481 insertions(+), 232 deletions(-) create mode 100644 omlx/cluster/modelsync.py create mode 100644 omlx/cluster/replan.py create mode 100644 tests/test_cluster_modelsync.py create mode 100644 tests/test_cluster_proportional_plan.py create mode 100644 tests/test_cluster_replan.py 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/deployment.py b/omlx/cluster/deployment.py index 8f7f637abc..cb14c0a5f2 100644 --- a/omlx/cluster/deployment.py +++ b/omlx/cluster/deployment.py @@ -27,6 +27,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:]+\])$" ) @@ -54,6 +63,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 +75,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 +109,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 +320,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 +344,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,6 +420,15 @@ 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, @@ -347,7 +436,7 @@ def hostfile_dict(self) -> dict[str, Any]: "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 +448,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 +462,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 +507,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 +517,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 +526,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 +536,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 +560,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 +578,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 +609,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..2e3e156bbd 100644 --- a/omlx/cluster/inference_worker.py +++ b/omlx/cluster/inference_worker.py @@ -20,7 +20,7 @@ from types import SimpleNamespace from typing import Any -from .deployment import decode_worker_contract +from .deployment import decode_worker_contract, decode_worker_path_map from .liveness import PeerWatchdog from .memory_guard import ( admission_budget, @@ -666,9 +666,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: " @@ -970,6 +970,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, @@ -1103,25 +1112,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() @@ -1211,9 +1223,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 diff --git a/omlx/cluster/launch.py b/omlx/cluster/launch.py index f3be0d47c0..523ea4ed3f 100644 --- a/omlx/cluster/launch.py +++ b/omlx/cluster/launch.py @@ -227,9 +227,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 +282,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] @@ -690,7 +687,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 +705,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 +856,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 +1128,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 +1457,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 +1468,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 +1480,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 +1513,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 +1576,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 +1647,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, ), ) @@ -1939,9 +1943,7 @@ def _terminate(self) -> None: os.killpg(process_group, signal.SIGTERM) 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 @@ -2104,9 +2106,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 +2116,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 +2147,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 +2160,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 +2170,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/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/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/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..2693e20dcd 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -43,7 +43,12 @@ 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, @@ -84,12 +89,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 +434,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 +483,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 +499,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 +722,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 +830,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 +851,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 +1638,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, @@ -2645,9 +2705,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 +2753,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 +3071,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 +3132,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 +3173,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 +3195,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 +3203,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 +3226,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, @@ -3403,6 +3515,233 @@ 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["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 + 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, + "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, + "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.""" 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/server.py b/omlx/server.py index b7efe31802..f994498c6c 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -727,6 +727,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_deployment.py b/tests/test_cluster_deployment.py index 3e39d52887..58d739c32f 100644 --- a/tests/test_cluster_deployment.py +++ b/tests/test_cluster_deployment.py @@ -159,6 +159,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 +361,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 +432,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..116d424118 100644 --- a/tests/test_cluster_inference_worker.py +++ b/tests/test_cluster_inference_worker.py @@ -637,6 +637,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") 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..d4f1e387a0 --- /dev/null +++ b/tests/test_cluster_replan.py @@ -0,0 +1,532 @@ +# 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 + 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 + + +def test_replan_refuses_to_interrupt_active_requests(tmp_path, monkeypatch): + 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, + "target_context_tokens": 16384, + }, + ) + .json() + ) + response = _client().post( + "/admin/api/cluster/replan", + json={ + "deployment_id": deployment_id, + "target_context_tokens": 16384, + "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 + + +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")] diff --git a/tests/test_cluster_seams.py b/tests/test_cluster_seams.py index 425e1235f0..59716bb2c6 100644 --- a/tests/test_cluster_seams.py +++ b/tests/test_cluster_seams.py @@ -74,7 +74,9 @@ 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"} unreachable = _registered_routes() - _js_called_paths() - allowed_without_caller assert not unreachable, ( f"cluster routes nothing calls: {sorted(unreachable)} — wire them up or " From cd7d5333431c98b6aff8082d97599332e46475d2 Mon Sep 17 00:00:00 2001 From: jundot Date: Tue, 8 Sep 2026 13:01:29 +0900 Subject: [PATCH 03/29] test: tighten PLE prefetch regression coverage (#3287) --- .../mlx_vlm/models/qwen4_exp/language.py | 45 +--- tests/test_mlx_vlm_qwen4_exp_compat.py | 255 +++++++++--------- 2 files changed, 132 insertions(+), 168 deletions(-) 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 c49886b330..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 @@ -1838,32 +1838,13 @@ def _find_nth_prime_after(start: int, count: int) -> int: return prime -# SSD-backed PLE row lookups hit a ~40GB mmap'd table with ~16 scattered -# rows per token. When a page is already resident the mmap gather is a pure -# memcpy; when it is not, the access blocks ~100us on a synchronous page -# fault (MADV_RANDOM is correct here: rows are random, so readahead mostly -# fetches bytes nobody asked for). Only the cold phase needs help: a -# per-reader seen-page bitmap remembers which pages this process already -# pulled in, and the first time a page is needed the whole batch of missing -# pages is pread() concurrently from a thread pool so the SSD controller's -# parallelism overlaps the waits (~4096-row gather: ~12ms parallel vs ~400ms -# serialized page faults measured on Apple Silicon). A fully-warm call pays -# only a bitmap probe and keeps the original memcpy gather speed. -# Eviction honesty: the bitmap is write-once, but memory pressure makes -# eviction the steady state (measured: a 37.5GB PLE table falls to ~24% -# resident after hours of serving). mincore() detects eviction precisely -# but costs ~4.5ms per shard-span call — unpayable on the hot path — so -# instead every fully-seen gather self-instruments: if its wall time blows -# the memcpy budget (a floor plus a per-row allowance, ~1% eviction rate -# trips it, normal warm jitter does not), the bitmap re-arms and the next -# gather treats every page as fresh again, re-warming the evicted ones -# through the same concurrent pread path. Re-arm is rate-limited per -# reader. Threads (not asyncio/io_uring) because os.pread releases the GIL -# for the syscall duration, which is enough here. +# 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") -# Warm gather runs at ~0.1us/row; a minor fault costs ~1000x that, so this -# budget trips on real eviction and sleeps through everything else. +# 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 @@ -1943,11 +1924,7 @@ def rows(self, key: str, rows: list[int]) -> mx.array: return mx.array(copied) def _prefetch_missing_pages(self, row_indices, base_offset, row_bytes) -> bool: - """Warm up pages behind the requested rows. - - Returns True when every needed page was already marked seen (a - fully-warm gather whose wall time is worth timing for eviction). - """ + """Prefetch unmarked pages; return whether all were already marked.""" offsets = base_offset + row_indices * row_bytes needed_pages = np.unique( np.concatenate( @@ -1975,15 +1952,7 @@ def touch(page: int) -> None: return False def _rearm_if_slow(self, elapsed: float, row_count: int) -> None: - """Re-arm the seen-page bitmap when a fully-seen gather lags memcpy. - - A warm gather is a page-cache memcpy at ~0.1us/row; a page the OS - evicted after we marked it seen turns it into serial ~100us minor - faults. Sustained over-budget wall time is exactly that signature, - so clear the bitmap and let the next gather re-warm the evicted - pages through the concurrent pread path. Rate-limited so a reader - re-arms at most once per interval. - """ + """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 diff --git a/tests/test_mlx_vlm_qwen4_exp_compat.py b/tests/test_mlx_vlm_qwen4_exp_compat.py index 48607af8b3..a6404d9326 100644 --- a/tests/test_mlx_vlm_qwen4_exp_compat.py +++ b/tests/test_mlx_vlm_qwen4_exp_compat.py @@ -1257,145 +1257,140 @@ def test_disk_backed_bf16_ple_reads_only_requested_rows(tmp_path): embedding.close() -def test_disk_backed_ple_page_prefetch_returns_identical_rows(tmp_path): - """mincore+pread cold prefetch must not perturb gathered bytes. - - Regression guard for the cold-only prefetch path in _SafeTensorMMap: - 166-byte rows over a multi-page span straddle page boundaries often, - so any page-math mistake surfaces as corrupted rows. - """ - import numpy as np - +@pytest.fixture +def disk_ple_reader(tmp_path): compat.apply_mlx_vlm_qwen4_exp_compat_patch() - from mlx_vlm.models.qwen4_exp.language import ( - _PLE_PAGE_SIZE, - DiskBackedShardedEmbedding, - ) - - prefix = ( - "model.language_model.layers.1.ple.ple_embedding.ngram_embedding" - ) - rows, dims = 4096, 83 - dense = ( - mx.arange(rows * dims, dtype=mx.float32).reshape(rows, dims) / 3.0 - ).astype(mx.bfloat16) - filename = "model-00001-of-00001.safetensors" - mx.save_safetensors( - str(tmp_path / filename), - {f"{prefix}.shard_0.weight": dense}, - metadata={"format": "mlx"}, - ) - (tmp_path / "model.safetensors.index.json").write_text( - json.dumps({"weight_map": {f"{prefix}.shard_0.weight": filename}}), - encoding="utf-8", - ) + from mlx_vlm.models.qwen4_exp import language as ple - embedding = DiskBackedShardedEmbedding( - tmp_path, prefix, num_embeddings=rows, dims=dims, num_shards=1 - ) + # 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: - reader = next(iter(embedding._readers.values())) - assert reader._seen_pages is not None - rng = np.random.default_rng(7) - idx = np.sort(rng.integers(0, rows, size=512)) - values = embedding(mx.array(idx.reshape(1, -1), dtype=mx.int32)) - expected = dense[mx.array(idx.tolist(), dtype=mx.int32)][None] - assert mx.array_equal(values, expected).item() - # Gathered pages are marked seen so warm repeats skip the pool. - start = reader._data_start + reader._header[ - f"{prefix}.shard_0.weight" - ]["data_offsets"][0] - offs = start + idx * (dims * 2) - needed = np.unique( - np.concatenate( - (offs // _PLE_PAGE_SIZE, (offs + dims * 2 - 1) // _PLE_PAGE_SIZE) - ) - ) - assert all(reader._seen_pages[page] == 1 for page in needed.tolist()) - # Fully-warm repeat call takes the bitmap-hit shortcut. - warm = embedding(mx.array(idx.reshape(1, -1), dtype=mx.int32)) - assert mx.array_equal(warm, expected).item() + yield ple, reader, dense finally: - embedding.close() - + reader.close() -def test_disk_backed_ple_rearms_seen_bitmap_on_slow_gather(tmp_path, caplog): - """A warm gather that lags memcpy must re-arm the bitmap exactly once. - - Regression guard for the eviction re-arm: once every page is marked - seen, only a wall-time over-budget (the signature of evicted pages - turning the gather into serial minor faults) may clear the bitmap, and - the next gather must re-warm and re-mark through the fresh path. - """ - import logging - import numpy as np +@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() - compat.apply_mlx_vlm_qwen4_exp_compat_patch() - from mlx_vlm.models.qwen4_exp import language as ple - from mlx_vlm.models.qwen4_exp.language import DiskBackedShardedEmbedding - prefix = ( - "model.language_model.layers.1.ple.ple_embedding.ngram_embedding" - ) - rows, dims = 4096, 83 - dense = ( - mx.arange(rows * dims, dtype=mx.float32).reshape(rows, dims) / 5.0 - ).astype(mx.bfloat16) - filename = "model-00001-of-00001.safetensors" - mx.save_safetensors( - str(tmp_path / filename), - {f"{prefix}.shard_0.weight": dense}, - metadata={"format": "mlx"}, - ) - (tmp_path / "model.safetensors.index.json").write_text( - json.dumps({"weight_map": {f"{prefix}.shard_0.weight": filename}}), - encoding="utf-8", - ) +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() - embedding = DiskBackedShardedEmbedding( - tmp_path, prefix, num_embeddings=rows, dims=dims, num_shards=1 - ) - try: - reader = next(iter(embedding._readers.values())) - rng = np.random.default_rng(11) - idx = np.sort(rng.integers(0, rows, size=512)) - query = mx.array(idx.reshape(1, -1), dtype=mx.int32) - expected = dense[mx.array(idx.tolist(), dtype=mx.int32)][None] - - # First call marks pages; a warm repeat under the real budget - # (memcpy-fast gather) must leave the bitmap intact. - embedding(query) - embedding(query) - assert sum(reader._seen_pages) > 0 - - old_floor = ple._PLE_REARM_FLOOR_SECONDS - old_per_row = ple._PLE_REARM_PER_ROW_SECONDS - try: - # Force the slow-gather signature: with a zero budget, any warm - # gather re-arms, clears the bitmap once, and the next gather - # re-warms through the fresh path. - ple._PLE_REARM_FLOOR_SECONDS = 0.0 - ple._PLE_REARM_PER_ROW_SECONDS = 0.0 - with caplog.at_level( - logging.INFO, logger="mlx_vlm.models.qwen4_exp.language" - ): - embedding(query) - assert sum(reader._seen_pages) == 0 - assert reader._rearm_count == 1 - assert "re-armed seen-page bitmap" in caplog.text - values = embedding(query) - assert sum(reader._seen_pages) > 0 - assert mx.array_equal(values, expected).item() - # Rate limit: still over budget, but the interval blocks a - # second clear and the freshly-marked pages survive. - embedding(query) - assert sum(reader._seen_pages) > 0 - finally: - ple._PLE_REARM_FLOOR_SECONDS = old_floor - ple._PLE_REARM_PER_ROW_SECONDS = old_per_row - finally: - embedding.close() + 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]) From 9fb488c2b24bc53fa58fc03d02db66e443575299 Mon Sep 17 00:00:00 2001 From: jundot Date: Tue, 8 Sep 2026 13:04:18 +0900 Subject: [PATCH 04/29] fix(cluster): reload deployments when model paths change --- omlx/cluster/routes.py | 1 + tests/test_cluster_replan.py | 52 ++++++++++++++++++++++++++++++++---- 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index 2693e20dcd..c592e95298 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -3387,6 +3387,7 @@ async def _activate_and_report( 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) diff --git a/tests/test_cluster_replan.py b/tests/test_cluster_replan.py index d4f1e387a0..77972a48e7 100644 --- a/tests/test_cluster_replan.py +++ b/tests/test_cluster_replan.py @@ -132,8 +132,9 @@ async def prepare_cluster_reload(self, model_id): async def get_engine(self, model_id): assert model_id == self.model_id - deployment = routes.get_cluster_registry().get_for_model(self.model_path) - self.entry.engine = _ReadyEngine(deployment) + 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 @@ -415,7 +416,12 @@ def test_replan_rejects_a_stale_approval(active_deployment): assert active_deployment.pool.reloads == 1 -def test_replan_refuses_to_interrupt_active_requests(tmp_path, monkeypatch): +@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) @@ -436,7 +442,7 @@ def test_replan_refuses_to_interrupt_active_requests(tmp_path, monkeypatch): "/admin/api/cluster/replan", json={ "deployment_id": deployment_id, - "target_context_tokens": 16384, + **change, }, ) .json() @@ -445,7 +451,7 @@ def test_replan_refuses_to_interrupt_active_requests(tmp_path, monkeypatch): "/admin/api/cluster/replan", json={ "deployment_id": deployment_id, - "target_context_tokens": 16384, + **change, "approved_placement": preview["plan"]["placement_signature"], }, ) @@ -456,6 +462,9 @@ def test_replan_refuses_to_interrupt_active_requests(tmp_path, monkeypatch): 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) @@ -530,3 +539,36 @@ def test_replan_membership_change_adds_a_node(active_deployment): (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) From e9a89d5d4f7b3bc2f48eaa8653dd2343354836b4 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Mon, 17 Aug 2026 20:35:40 -0700 Subject: [PATCH 05/29] distributed: verified teardown with SIGKILL retry, rank-marker sweep, and launch-manifest reaper DistributedJobSupervisor._terminate ignored the result of the final _wait_for_process_group_exit after SIGKILL, so a rank surviving the kill (unkillable Metal/JACCL wait, D-state, PermissionError-on-killpg) kept its unified memory resident while engine_pool had already released the model's budget (G1). killpg also only reaches the local process group, leaving remote ranks to a fragile SSH-teardown chain (G2), and all teardown lived in the coordinator process, so a crashed omlx-server orphaned everything with no reaper anywhere (G8). - _terminate now verifies the post-SIGKILL group exit, retries the kill once, then sweeps leftover rank processes by their runtime-marker pids (local via read_runtime_markers + marker_owner_is_live, remote via read_remote_marker + an SSH kill of the recorded pid). Unverified teardown raises DistributedTeardownError and keeps the process reference so a later stop() retries instead of dropping state. - start() writes an on-disk launch manifest (job id, pgid, coordinator pid, rank hosts, marker dir) removed only after verified group exit; reap_orphaned_launches() consumes manifests whose coordinator is dead and reaps their ranks. It runs at server startup (lifespan) and at the top of every supervisor start(). - engine_pool._unload_engine's distributed retry path now actually sees teardown failures because the supervisor raises them. - start()'s failure path no longer lets a teardown error mask the launch error. --- omlx/cluster/launch.py | 463 ++++++++++++++++++++++++++++++++++++++++- omlx/engine_pool.py | 9 +- omlx/server.py | 18 ++ 3 files changed, 483 insertions(+), 7 deletions(-) diff --git a/omlx/cluster/launch.py b/omlx/cluster/launch.py index 523ea4ed3f..75c6054687 100644 --- a/omlx/cluster/launch.py +++ b/omlx/cluster/launch.py @@ -31,9 +31,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 @@ -51,6 +57,19 @@ 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 CudaFabricProbeHost: """One CUDA worker and its direct-link NCCL endpoint.""" @@ -123,6 +142,333 @@ 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 _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 + + +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") + if plan_hash is not None and recorded is not None and recorded != plan_hash: + return False + return True + + +def _sweep_rank_processes( + deployment_id: str, + hosts: list[dict[str, Any]], + *, + state_dir: str | Path, + plan_hash: str | 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] = [] + local_root = Path(state_dir).expanduser() + remote_root = str(state_dir).rstrip("/") or "." + 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 _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: + failures.append(f"rank {rank} ({node_id}) marker unreadable: {error}") + 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" + ) + return failures + + +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]: @@ -1761,6 +2107,17 @@ 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( @@ -1807,6 +2164,7 @@ def start(self) -> dict[str, Any]: env=environment, start_new_session=True, ) + self._write_launch_manifest() self._start_readers() event = self._wait_for_ready() self._wait_for_listener() @@ -1814,7 +2172,16 @@ def start(self) -> dict[str, Any]: 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: @@ -1933,7 +2300,66 @@ 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, *, 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, + 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 @@ -1951,10 +2377,38 @@ def _terminate(self) -> None: # 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): + 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", + ) with suppress(ProcessLookupError): os.killpg(process_group, signal.SIGKILL) - _wait_for_process_group_exit(process_group, 2.0) + 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() + if 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"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) @@ -1973,6 +2427,7 @@ def _terminate(self) -> None: self.rank_ready_events.clear() self.failure_event = None self._phase = "stopped" + self._remove_launch_manifest() if self._temporary is not None: self._temporary.cleanup() self._temporary = None diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index 9f46a0935c..7b74f4f6d2 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -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/server.py b/omlx/server.py index f994498c6c..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 From c33117dd87062a07f4a11bef93ac6c455a986dc5 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Mon, 17 Aug 2026 20:59:09 -0700 Subject: [PATCH 06/29] distributed: unit tests for verified teardown, rank sweep, and launch-manifest reaper Covers: SIGKILL retry round, DistributedTeardownError with state kept for retry, manifest write/removal around verified stop, marker-pid sweep of local and remote leftover ranks, foreign-deployment marker immunity, and reap_orphaned_launches reaping a dead coordinator's job while leaving active jobs alone. The two pre-existing stop tests now stub the rank sweep (it would otherwise SSH to the fake 'studio' host). --- tests/test_cluster_launch.py | 386 +++++++++++++++++++++++++++++++++++ 1 file changed, 386 insertions(+) diff --git a/tests/test_cluster_launch.py b/tests/test_cluster_launch.py index 95d994bfaf..0edbe1bc26 100644 --- a/tests/test_cluster_launch.py +++ b/tests/test_cluster_launch.py @@ -312,6 +312,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 +359,11 @@ def poll(self): "killpg", lambda pgid, sig: signals.append((pgid, sig)), ) + monkeypatch.setattr( + launch.DistributedJobSupervisor, + "_sweep_rank_leftovers", + lambda self, **_kw: [], + ) supervisor.stop() @@ -1809,3 +1821,377 @@ 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) + # 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) + 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 failures == ["rank 0 (local) pid 424242 survived SIGKILL"] + + +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) + # 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() From 854804300bbb734fe9333928d279f5694f9d16a6 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Mon, 17 Aug 2026 22:18:14 -0700 Subject: [PATCH 07/29] distributed: rank-side force-cancel hook driven by a coordinator cancel file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RuntimeTelemetry gains a force-cancel surface: the coordinator drops -cancel.json next to the runtime markers; the rank's telemetry heartbeat (and each batch step, throttled to 1s) consumes new epochs and cancels every active uid through BatchGenerator.remove — the same call MLX-LM handlers make on disconnect, applied by the batch loop at a step boundary and shared with peer ranks, so cancellation never severs a collective mid-request. An ack file records each consumed epoch. This is the rank-side backstop for a handler wedged in a collective that never reaches its disconnect finally (G3), wired through the existing telemetry.cancel_uids hook point. --- omlx/cluster/telemetry.py | 154 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) diff --git a/omlx/cluster/telemetry.py b/omlx/cluster/telemetry.py index 772573b240..00f37e694d 100644 --- a/omlx/cluster/telemetry.py +++ b/omlx/cluster/telemetry.py @@ -11,13 +11,20 @@ from collections.abc import Iterator from contextlib import contextmanager from dataclasses import dataclass +from pathlib import Path from typing import Any, Protocol +import json +import os + from .performance import ExecutionSettings from .planner import PipelineAssignment 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 +77,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 +117,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 +138,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) @@ -320,6 +343,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 +466,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: @@ -659,11 +799,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 +884,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) From ff7b1ca29abb848bab0323cedc7a8d94f3916c3e Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Mon, 17 Aug 2026 22:18:14 -0700 Subject: [PATCH 08/29] distributed: require rank-side quiescence evidence in pool unload gate _entry_has_active_requests now consults rank_side_active_requests() when the engine provides it: a distributed entry whose coordinator counter drained but whose rank-0 telemetry still reports active requests is not quiescent, closing the gap where abort_all_requests reported success while ranks kept generating (G5, audit hook #7). Missing marker evidence falls through to the supervisor failure paths. --- omlx/engine_pool.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index 7b74f4f6d2..8f6e0aa694 100644 --- a/omlx/engine_pool.py +++ b/omlx/engine_pool.py @@ -1223,9 +1223,24 @@ def _entry_has_active_requests(entry: EngineEntry) -> bool: if not callable(has_active_requests): return False try: - return has_active_requests() is True + if has_active_requests() is True: + return True except Exception: return True + # Distributed engines: the coordinator counter draining only proves + # the httpx side closed. Rank-side telemetry reporting active + # requests means the ranks are still generating and the entry is NOT + # quiescent (G5); no marker evidence (None) falls through, since a + # dead rank's marker is handled by the supervisor failure paths. + rank_side = getattr(engine, "rank_side_active_requests", None) + if callable(rank_side): + try: + remaining = rank_side() + except Exception: + remaining = None + if remaining: + return True + return False def _entry_is_busy(self, entry: EngineEntry) -> bool: return entry.in_use > 0 or self._entry_has_active_requests(entry) From 03d83f5d811fb9a574acdd4f1b7e23ec12b9f483 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Mon, 17 Aug 2026 22:51:08 -0700 Subject: [PATCH 09/29] distributed: surface abort (not transport error) when a closed stream raises abort_request() closes the request's response, so the SSE iterator can raise an httpx stream error before the loop-top flag check; check the abort flag first in the streaming HTTPError handlers. --- omlx/engine/distributed.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/omlx/engine/distributed.py b/omlx/engine/distributed.py index 60818ce568..8e695d6626 100644 --- a/omlx/engine/distributed.py +++ b/omlx/engine/distributed.py @@ -926,6 +926,9 @@ async def stream_chat( except httpx.ReadTimeout as exc: raise self._read_timeout_error(stream=True) from exc except httpx.HTTPError as exc: + # abort_request() closed this response; surface the abort, not a + # spurious transport failure. + self._raise_if_aborted(request_id) raise await self._transport_failure_error( exc, stream=True, @@ -1183,6 +1186,9 @@ async def stream_generate( except httpx.ReadTimeout as exc: raise self._read_timeout_error(stream=True) from exc except httpx.HTTPError as exc: + # abort_request() closed this response; surface the abort, not a + # spurious transport failure. + self._raise_if_aborted(request_id) raise await self._transport_failure_error( exc, stream=True, From b3873ac4c3a7ca85bdd56d2c4a156ee6533f3a45 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Mon, 17 Aug 2026 23:54:56 -0700 Subject: [PATCH 10/29] =?UTF-8?q?distributed:=20graduated=20PeerWatchdog?= =?UTF-8?q?=20response=20=E2=80=94=20abort=20before=20exit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A confirmed peer loss used to fire on_lost (marker + os._exit(1)) immediately. The watchdog now runs a graduated ladder once the failure tolerance is reached: log, fire the new on_abort hook (request cancellation at a step boundary), then re-probe for up to abort_grace seconds — a peer flap that recovers inside the window no longer suicides the healthy rank. on_lost remains the last stage. Defaults preserve the existing detection timing (same 2-strike tolerance); with on_abort unset or abort_grace=0 the behavior is byte-for-byte the old one. --- omlx/cluster/liveness.py | 54 +++++++++++++++- tests/test_cluster_liveness.py | 111 +++++++++++++++++++++++++++++++++ 2 files changed, 164 insertions(+), 1 deletion(-) diff --git a/omlx/cluster/liveness.py b/omlx/cluster/liveness.py index f8c10d0b91..188634de60 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". @@ -456,6 +459,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,6 +478,14 @@ 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 @@ -527,6 +540,45 @@ 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/tests/test_cluster_liveness.py b/tests/test_cluster_liveness.py index 893256a934..45690ecb08 100644 --- a/tests/test_cluster_liveness.py +++ b/tests/test_cluster_liveness.py @@ -563,3 +563,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 From ba652737d3f1b8212c4180c833b36df5e12da936 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Mon, 17 Aug 2026 23:54:56 -0700 Subject: [PATCH 11/29] distributed: widen launcher watchdog, wire abort stages on both watchdogs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit _watch_launcher_parent now also watches an optional launcher/coordinator lease file (env OMLX_CLUSTER_LAUNCHER_LEASE; off by default, and a lease that never appeared yet is not 'stale'), catching a launcher that is alive but wedged — invisible to the PPID check alone. Both the launcher watchdog and the rank-0 peer watchdog fire an abort stage before os._exit: writing -cancel.json into the runtime state dir, which the rank's telemetry heartbeat consumes to force-cancel in-flight requests through BatchGenerator.remove at a step boundary (the cancel-file contract is consumed by the telemetry hook in pr/distributed-request-abort; merge that branch first). The peer watchdog's abort grace is configurable via OMLX_CLUSTER_PEER_ABORT_GRACE (default 5.0s). --- omlx/cluster/inference_worker.py | 131 +++++++++++++++++++++++-- tests/test_cluster_inference_worker.py | 107 ++++++++++++++++++++ 2 files changed, 230 insertions(+), 8 deletions(-) diff --git a/omlx/cluster/inference_worker.py b/omlx/cluster/inference_worker.py index 2e3e156bbd..de9e0bc225 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 @@ -42,6 +43,8 @@ _EVENT_PREFIX = "OMLX_CLUSTER_EVENT:" +logger = logging.getLogger(__name__) + def _emit_event(payload: dict[str, Any]) -> None: print( @@ -489,15 +492,58 @@ def interrupt(_signum: int, _frame: Any) -> None: 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, ) -> None: """Fail fast if MLX's launcher exits without reaping this rank. @@ -505,22 +551,50 @@ 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 before the process disappears. """ + 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}) exit_process(1) return @@ -594,11 +668,27 @@ def on_lost(reason: str) -> None: _emit_event({"type": "peer_lost", "reason": 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 +697,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, ) @@ -996,7 +1111,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. diff --git a/tests/test_cluster_inference_worker.py b/tests/test_cluster_inference_worker.py index 116d424118..46b3435760 100644 --- a/tests/test_cluster_inference_worker.py +++ b/tests/test_cluster_inference_worker.py @@ -3,7 +3,9 @@ import contextlib import json +import os import threading +import time from types import SimpleNamespace from typing import Any @@ -19,6 +21,7 @@ _validate_loaded_stage, _validate_measured_weight_bytes, _watch_launcher_parent, + _write_cancel_request, build_parser, ) from omlx.cluster.planner import PipelineAssignment @@ -1316,3 +1319,107 @@ def _make_logits_processors(args): with inference_worker._install_thinking_budget_support(server, Tokenizer()): assert server._make_logits_processors(None) == ["base-processor"] assert server._make_logits_processors is FakeServer._make_logits_processors +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] = [] + 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, + ) + + 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 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 StopLoop(Exception): + pass + + def wait(_seconds): + polls[0] += 1 + if polls[0] >= 3: + raise StopLoop + + with pytest.raises(StopLoop): + _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 StopLoop(Exception): + pass + + def wait(_seconds): + polls[0] += 1 + if polls[0] >= 3: + raise StopLoop + + with pytest.raises(StopLoop): + _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" From 8062c7b1b26c644f11a08659e7bb3f0f86b804d2 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Tue, 18 Aug 2026 17:11:16 -0700 Subject: [PATCH 12/29] runtime: jaccl-if-all-rdma_ctl-else-ring selection; N-node manifest + ring verified-teardown tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit omlx/cluster/backends.py: select_cluster_backend (binary fail-safe rule with named blockers) and members_from_host_records. Routes: POST /admin/api/cluster/backend-selection for the plan view, and backend='auto' on /replan resolved from posted host records. Tests prove the ring backend runs through the same DistributedJobSupervisor verified teardown (TERM→KILL×2 escalation raising DistributedTeardownError, marker-pid rank sweep over all N hosts) and that the launch manifest records every host of a 3-node ring. --- omlx/cluster/backends.py | 164 +++++++++++++ omlx/cluster/routes.py | 69 +++++- tests/test_cluster_runtime_v2.py | 397 +++++++++++++++++++++++++++++++ 3 files changed, 629 insertions(+), 1 deletion(-) create mode 100644 omlx/cluster/backends.py create mode 100644 tests/test_cluster_runtime_v2.py diff --git a/omlx/cluster/backends.py b/omlx/cluster/backends.py new file mode 100644 index 0000000000..95d3c7544d --- /dev/null +++ b/omlx/cluster/backends.py @@ -0,0 +1,164 @@ +# 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 dataclasses import dataclass, field +from typing import Any, Iterable + + +@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 " + f"{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/routes.py b/omlx/cluster/routes.py index c592e95298..9c282f8ea2 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -37,6 +37,11 @@ preflight_issues, tp_groups_spanning_slow_links, ) +from .backends import ( + MemberFabric, + members_from_host_records, + select_cluster_backend, +) from .catalogue import ModelFit, assess_model, catalogue_for_cluster from .collective import ( CollectiveSmokeError, @@ -2626,6 +2631,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]}" @@ -3544,7 +3590,7 @@ class ClusterReplanRequest(BaseModel): model_path: str | None = Field(default=None, max_length=4096) model_source: str | None = Field(default=None, max_length=255) model_source_python: str | None = Field(default=None, max_length=4096) - backend: Literal["ring", "jaccl", "jaccl-ring"] | None = None + backend: Literal["auto", "ring", "jaccl", "jaccl-ring"] | None = None nodes: list[ClusterPlanNodeRequest] | None = Field( default=None, min_length=2, max_length=64 ) @@ -3652,6 +3698,25 @@ async def replan_cluster_deployment(request: ClusterReplanRequest): # shared path. Carry them forward unless the caller overrides. path_map = dict(current.path_map) derived["path_map"] = True + if backend == "auto": + # rdma_ctl on every member → jaccl; any member without it pulls the + # whole cluster onto the TCP ring. Derived from the posted host + # records; launch preflight re-verifies the live state. + try: + selection = select_cluster_backend(members_from_host_records(hosts)) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + backend_decision: dict[str, Any] = selection.to_dict() + backend = selection.backend + else: + backend_decision = { + "backend": backend, + "reason": "operator-selected backend", + "blockers": [], + "members": [ + member.to_dict() for member in members_from_host_records(hosts) + ], + } try: _validate_cluster_hosts(hosts) effective = ClusterDeploymentRequest( @@ -3715,6 +3780,7 @@ async def replan_cluster_deployment(request: ClusterReplanRequest): "changes": changes, "deployment_id": deployment.deployment_id, "backend": deployment.backend, + "backend_decision": backend_decision, "plan": signed_plan, } @@ -3735,6 +3801,7 @@ async def replan_cluster_deployment(request: ClusterReplanRequest): "replan": { "steps": list(_REPLAN_STEPS), "derived": derived, + "backend_decision": backend_decision, "previous": ( summarize_deployment(current) if current is not None else None ), diff --git a/tests/test_cluster_runtime_v2.py b/tests/test_cluster_runtime_v2.py new file mode 100644 index 0000000000..fce2d2c946 --- /dev/null +++ b/tests/test_cluster_runtime_v2.py @@ -0,0 +1,397 @@ +# 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 From 716591f8925c9dc088ae9cad5fae8f49a13b2485 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Fri, 21 Aug 2026 20:22:21 -0700 Subject: [PATCH 13/29] =?UTF-8?q?fix(cluster):=20close=20thundermlx=20stab?= =?UTF-8?q?ility=20gaps=20=E2=80=94=20unwire=20before=20kill,=20MLX/JACCL?= =?UTF-8?q?=20env=20guards?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Rank SIGTERM/SIGINT handlers now release wired Metal memory (set_wired_limit(0) + clear_cache) under a 10s alarm escape hatch before the graceful KeyboardInterrupt path; launcher-watchdog and peer-watchdog force-exit paths release before os._exit. A SIGKILL cannot unwire — this closes the 'wedged rank strands wired memory until reboot' class (ported from thundermlx run_with_watchdog.py) - Rank env defaults in the launch hostfile: MLX_MAX_OPS_PER_BUFFER=16 / MLX_MAX_MB_PER_BUFFER=512 (bounds Metal command buffers under the GPU driver's ~10s execution timeout — the SIGABRT/orphan crash class) and JACCL_PROGRESS_TIMEOUT_MS=30000 / JACCL_TIMEOUT_ACTION=teardown-exit (explicit ProgressGuard pairing). All yield to operator-set env - 6 new worker tests + env-default tests; 1447 cluster tests green --- omlx/cluster/deployment.py | 36 ++- omlx/cluster/inference_worker.py | 73 ++++- tests/test_cluster_deployment.py | 38 ++- tests/test_cluster_inference_worker.py | 366 ++++++++++++++++++------- 4 files changed, 405 insertions(+), 108 deletions(-) diff --git a/omlx/cluster/deployment.py b/omlx/cluster/deployment.py index cb14c0a5f2..773e993227 100644 --- a/omlx/cluster/deployment.py +++ b/omlx/cluster/deployment.py @@ -8,6 +8,7 @@ import ipaddress import json import math +import os import re import zlib from dataclasses import dataclass, field @@ -44,6 +45,39 @@ _MAX_MODEL_ID_BYTES = 16 * 1024 _MAX_PLAN_BYTES = 256 * 1024 +# Rank-environment defaults carried by the mlx launch hostfile. Each value +# yields to the coordinator's own environment: an operator who pinned a knob +# keeps their value, and everyone else gets the tuned default. +# +# MLX_MAX_OPS_PER_BUFFER / MLX_MAX_MB_PER_BUFFER bound how much work lands in +# one Metal command buffer. An unbounded buffer overruns the GPU driver's +# ~10 s execution timeout (kIOGPUCommandBufferCallbackErrorTimeout), which the +# driver answers with SIGABRT and stranded wired memory — the crash class +# ThunderMLX root-caused to missing caps. +# +# JACCL_PROGRESS_TIMEOUT_MS / JACCL_TIMEOUT_ACTION pair with the ProgressGuard +# and emergency-teardown symbols compiled into the serving wheel's libjaccl +# (``progress_timeout_ms()`` and the ``teardown-exit`` action calling +# ``emergency_teardown()``): an RDMA polling loop that sees no completion for +# 30 s unwinds and exits instead of spinning forever with memory wired. The +# wheel ships compiled defaults; pinning them here keeps the posture explicit +# and identical across every rank. +_RANK_ENV_DEFAULTS = ( + ("MLX_METAL_FAST_SYNCH", "1"), + ("MLX_MAX_OPS_PER_BUFFER", "16"), + ("MLX_MAX_MB_PER_BUFFER", "512"), + ("JACCL_PROGRESS_TIMEOUT_MS", "30000"), + ("JACCL_TIMEOUT_ACTION", "teardown-exit"), +) + + +def _hostfile_envs() -> list[str]: + return [ + f"{name}={os.environ.get(name) or default}" + for name, default in _RANK_ENV_DEFAULTS + ] + + RDMAPath = str | tuple[str, ...] | None @@ -432,7 +466,7 @@ def model_path_for(self, node_id: str) -> str: def hostfile_dict(self) -> dict[str, Any]: return { "backend": self.backend, - "envs": ["MLX_METAL_FAST_SYNCH=1"], + "envs": _hostfile_envs(), "hosts": [ { "ssh": host.ssh, diff --git a/omlx/cluster/inference_worker.py b/omlx/cluster/inference_worker.py index de9e0bc225..351d87bdac 100644 --- a/omlx/cluster/inference_worker.py +++ b/omlx/cluster/inference_worker.py @@ -484,8 +484,64 @@ 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) @@ -544,6 +600,7 @@ def _watch_launcher_parent( 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. @@ -558,7 +615,10 @@ def _watch_launcher_parent( 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 before the process disappears. + 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 @@ -596,6 +656,10 @@ def _watch_launcher_parent( 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 @@ -666,6 +730,11 @@ 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: diff --git a/tests/test_cluster_deployment.py b/tests/test_cluster_deployment.py index 58d739c32f..8ce6357b16 100644 --- a/tests/test_cluster_deployment.py +++ b/tests/test_cluster_deployment.py @@ -83,10 +83,46 @@ def test_deployment_round_trip_and_worker_plan_are_json_only(): assert restored == deployment assert plan_hash == deployment.plan_hash assert assignments == deployment.assignments - assert deployment.hostfile_dict()["envs"] == ["MLX_METAL_FAST_SYNCH=1"] + assert "MLX_METAL_FAST_SYNCH=1" in deployment.hostfile_dict()["envs"] assert deployment.distributed_init_backend == "jaccl" +def test_hostfile_envs_carry_stability_defaults(monkeypatch): + for name in ( + "MLX_MAX_OPS_PER_BUFFER", + "MLX_MAX_MB_PER_BUFFER", + "JACCL_PROGRESS_TIMEOUT_MS", + "JACCL_TIMEOUT_ACTION", + ): + monkeypatch.delenv(name, raising=False) + deployment = _deployment() + + envs = deployment.hostfile_dict()["envs"] + + # Metal command-buffer caps: an unbounded buffer overruns the GPU + # driver's ~10 s timeout, which answers with SIGABRT and orphaned wired + # memory. JACCL knobs pin the wheel's ProgressGuard/teardown-exit posture. + assert "MLX_MAX_OPS_PER_BUFFER=16" in envs + assert "MLX_MAX_MB_PER_BUFFER=512" in envs + assert "JACCL_PROGRESS_TIMEOUT_MS=30000" in envs + assert "JACCL_TIMEOUT_ACTION=teardown-exit" in envs + + +def test_hostfile_envs_respect_operator_overrides(monkeypatch): + monkeypatch.setenv("MLX_MAX_OPS_PER_BUFFER", "32") + monkeypatch.setenv("JACCL_PROGRESS_TIMEOUT_MS", "60000") + deployment = _deployment() + + envs = deployment.hostfile_dict()["envs"] + + assert "MLX_MAX_OPS_PER_BUFFER=32" in envs + assert "MLX_MAX_OPS_PER_BUFFER=16" not in envs + assert "JACCL_PROGRESS_TIMEOUT_MS=60000" in envs + # Untouched knobs keep their tuned defaults. + assert "MLX_MAX_MB_PER_BUFFER=512" in envs + assert "JACCL_TIMEOUT_ACTION=teardown-exit" in envs + + def test_deployment_round_trip_preserves_the_selected_context(): deployment = _deployment() deployment = ClusterDeployment( diff --git a/tests/test_cluster_inference_worker.py b/tests/test_cluster_inference_worker.py index 46b3435760..fb389358c6 100644 --- a/tests/test_cluster_inference_worker.py +++ b/tests/test_cluster_inference_worker.py @@ -4,6 +4,8 @@ import contextlib import json import os +import signal +import sys import threading import time from types import SimpleNamespace @@ -202,6 +204,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)) ) @@ -213,6 +216,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 == [ @@ -227,6 +231,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] @@ -1122,6 +1129,261 @@ 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 StopLoop(Exception): + pass + + def wait(_seconds): + polls[0] += 1 + if polls[0] >= 3: + raise StopLoop + + with pytest.raises(StopLoop): + _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 StopLoop(Exception): + pass + + def wait(_seconds): + polls[0] += 1 + if polls[0] >= 3: + raise StopLoop + + with pytest.raises(StopLoop): + _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 @@ -1319,107 +1581,3 @@ def _make_logits_processors(args): with inference_worker._install_thinking_budget_support(server, Tokenizer()): assert server._make_logits_processors(None) == ["base-processor"] assert server._make_logits_processors is FakeServer._make_logits_processors -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] = [] - 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, - ) - - 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 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 StopLoop(Exception): - pass - - def wait(_seconds): - polls[0] += 1 - if polls[0] >= 3: - raise StopLoop - - with pytest.raises(StopLoop): - _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 StopLoop(Exception): - pass - - def wait(_seconds): - polls[0] += 1 - if polls[0] >= 3: - raise StopLoop - - with pytest.raises(StopLoop): - _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" From a90f17fb0bfaa1ed07607fc9385c1d2b4507ad2d Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Sat, 22 Aug 2026 10:08:38 -0700 Subject: [PATCH 14/29] Let rank-ready markers own the load barrier --- omlx/cluster/progressive_loading.py | 14 ++- tests/test_cluster_progressive_loading.py | 116 ++++++++++++++++++++++ 2 files changed, 122 insertions(+), 8 deletions(-) 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/tests/test_cluster_progressive_loading.py b/tests/test_cluster_progressive_loading.py index 567468aa66..5f1e338c87 100644 --- a/tests/test_cluster_progressive_loading.py +++ b/tests/test_cluster_progressive_loading.py @@ -406,3 +406,119 @@ def reject_tokenizer(_path, config, **_kwargs): ) assert calls == [("tokenizer", {"trust_remote_code": False})] + + +def test_tensor_load_does_not_pin_pre_sharded_layer_arrays(monkeypatch): + """The layer-snapshot list must not survive into the sharding pass. + + Regression: ``flat`` pinned every pre-shard array for the whole strategy + run, so each materialized layer stayed resident in full next to its + shard — a TP=2 rank grew toward ~1.5x the whole model until the load + watchdog killed it (163 GiB against an 84 GiB plan), and a 128 GB node + ran out of memory entirely. The pre-shard arrays must be unreachable the + moment the strategy starts swapping in sharded slices. + """ + import gc + import weakref + + class Arr: + def __init__(self, name): + self.name = name + + class FakeModel: + model_type = "native_test" + + def __init__(self): + self.params = { + "embed.weight": Arr("embed"), + "lm_head.weight": Arr("head"), + "mtp.0.weight": Arr("mtp"), + "model.layers.0.weight": Arr("layer-0"), + "model.layers.1.weight": Arr("layer-1"), + } + self.shard = lambda group: None + + def parameters(self): + return self.params + + model = FakeModel() + originals = { + key: weakref.ref(value) + for key, value in model.params.items() + if ".layers." in key + } + embed_ref = weakref.ref(model.params["embed.weight"]) + head_ref = weakref.ref(model.params["lm_head.weight"]) + mtp_ref = weakref.ref(model.params["mtp.0.weight"]) + + def fake_strategy(shard_model, group, *, mx_module, progress=None): + # A large output projection must remain lazy until it can be sliced; + # evaluating it in the replicated fixed phase causes the avoidable + # full-head memory spike this loader is designed to prevent. + assert "head" not in mx_module.evaluated + assert "mtp" not in mx_module.evaluated + for key in list(shard_model.params): + if ".layers." in key: + shard_model.params[key] = Arr(key + " shard") + shard_model.params["lm_head.weight"] = Arr("head shard") + shard_model.params["mtp.0.weight"] = Arr("mtp shard") + gc.collect() + # Checked *inside* the strategy: after this point a pinned original + # would sit next to its materialized shard for the rest of the load. + assert all(ref() is None for ref in originals.values()) + assert head_ref() is None + assert mtp_ref() is None + return "native" + + monkeypatch.setattr( + "omlx.cluster.progressive_loading.apply_tensor_strategy", fake_strategy + ) + + class FakeMX: + cpu = object() + distributed = SimpleNamespace( + all_sum=lambda *_args, **_kwargs: (_ for _ in ()).throw( + AssertionError("launcher rank_ready markers own the load barrier") + ) + ) + + def __init__(self): + self.evaluated = [] + + def array(self, value): + return value + + def eval(self, *values): + self.evaluated.extend( + value.name for value in values if isinstance(value, Arr) + ) + + def clear_cache(self): + pass + + fake_utils = SimpleNamespace( + _download=lambda repo, allow_patterns=None: repo, + load_config=lambda path: {}, + load_tokenizer=lambda path, config, eos_token_ids=None: "tokenizer", + load_model=lambda path, **kwargs: (model, {}), + tree_flatten=lambda params: list(params.items()), + ) + + fake_mx = FakeMX() + loaded, tokenizer = progressive_sharded_load( + "fake-repo", + tensor_group=SimpleNamespace(), + utils_module=fake_utils, + mx_module=fake_mx, + ) + + assert loaded is model + assert tokenizer == "tokenizer" + gc.collect() + assert all(ref() is None for ref in originals.values()) + assert embed_ref() is not None + assert head_ref() is None + assert mtp_ref() is None + assert fake_mx.evaluated[:1] == ["embed"] + assert "head shard" in fake_mx.evaluated + assert "mtp shard" in fake_mx.evaluated From 5f8f0f9bbbfe58a9a33730bdae369f3669c866f7 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Sat, 22 Aug 2026 10:16:06 -0700 Subject: [PATCH 15/29] Gate serving on every rank-ready marker --- omlx/cluster/inference_worker.py | 51 ++++++++++++ omlx/cluster/launch.py | 105 +++++++++++++++++++++++++ tests/test_cluster_inference_worker.py | 50 +++++++++++- tests/test_cluster_launch.py | 30 +++++++ 4 files changed, 235 insertions(+), 1 deletion(-) diff --git a/omlx/cluster/inference_worker.py b/omlx/cluster/inference_worker.py index 351d87bdac..6134d2895a 100644 --- a/omlx/cluster/inference_worker.py +++ b/omlx/cluster/inference_worker.py @@ -53,6 +53,51 @@ 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. @@ -1396,6 +1441,12 @@ def run_worker(args: argparse.Namespace) -> int: "optimizations": optimizations, } ) + _wait_for_serve_release( + args.state_dir, + args.deployment_id, + plan_hash, + world_size, + ) with ( install_server_telemetry( marker, diff --git a/omlx/cluster/launch.py b/omlx/cluster/launch.py index 75c6054687..d9e1318b13 100644 --- a/omlx/cluster/launch.py +++ b/omlx/cluster/launch.py @@ -167,6 +167,94 @@ def _launch_manifest_path(state_dir: str | Path, deployment_id: str) -> Path: ) +def _launcher_log_path(state_dir: str | Path, deployment_id: str) -> Path: + """Private, durable output from every rank relayed by ``mlx.launch``.""" + + return Path(state_dir).expanduser() / f"{deployment_id}-launcher.log" + + +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, @@ -2124,6 +2212,10 @@ def start(self) -> dict[str, Any]: 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" @@ -2167,6 +2259,17 @@ def start(self) -> dict[str, Any]: 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 @@ -2428,6 +2531,8 @@ def _terminate(self) -> None: 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 diff --git a/tests/test_cluster_inference_worker.py b/tests/test_cluster_inference_worker.py index fb389358c6..4e19f0b9ae 100644 --- a/tests/test_cluster_inference_worker.py +++ b/tests/test_cluster_inference_worker.py @@ -20,6 +20,7 @@ _execution_settings, _install_distributed_model_protocol, _server_arguments, + _wait_for_serve_release, _validate_loaded_stage, _validate_measured_weight_bytes, _watch_launcher_parent, @@ -31,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, ): @@ -605,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): diff --git a/tests/test_cluster_launch.py b/tests/test_cluster_launch.py index 0edbe1bc26..b929ea187b 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,35 @@ def _deployment(model: str = "org/model") -> ClusterDeployment: ) +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) From 0e73850b7c95f3a6a2d403bde85f673b5425bf2d Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Sat, 22 Aug 2026 10:42:30 -0700 Subject: [PATCH 16/29] Separate rank control from tensor collectives --- omlx/cluster/control_plane.py | 208 ++++++++++++++++++++++++++++ omlx/cluster/inference_worker.py | 35 ++++- omlx/cluster/launch.py | 45 ++++++ omlx/cluster/telemetry.py | 1 + tests/test_cluster_control_plane.py | 73 ++++++++++ tests/test_cluster_launch.py | 5 + 6 files changed, 365 insertions(+), 2 deletions(-) create mode 100644 omlx/cluster/control_plane.py create mode 100644 tests/test_cluster_control_plane.py diff --git a/omlx/cluster/control_plane.py b/omlx/cluster/control_plane.py new file mode 100644 index 0000000000..d94707d132 --- /dev/null +++ b/omlx/cluster/control_plane.py @@ -0,0 +1,208 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Small reliable rank-control channel kept separate from tensor collectives.""" + +from __future__ import annotations + +import pickle +import socket +import struct +import time +import zlib +from contextlib import AbstractContextManager +from typing import Any + +_HANDSHAKE_MAGIC = b"OC2H" +_MESSAGE_MAGIC = b"OC2M" +_VERSION = 1 +_HANDSHAKE = struct.Struct("!4sII64s") +_HEADER = struct.Struct("!4sIIII") +_MAX_OBJECT_BYTES = 256 * 1024 * 1024 + + +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._sequence = 0 + + def __enter__(self) -> "RankControlPlane": + if self.rank == 0: + self._accept_workers() + else: + self._connect_to_coordinator() + 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 _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 + self._configure(stream) + try: + magic, version, rank, token = _HANDSHAKE.unpack( + _recv_exact(stream, _HANDSHAKE.size) + ) + if ( + magic != _HANDSHAKE_MAGIC + or version != _VERSION + or not 0 < rank < self.world_size + or rank in self._peers + or token != self._token + ): + raise RuntimeError("rank-control handshake is invalid") + self._peers[rank] = stream + except Exception: + stream.close() + raise + + def _connect_to_coordinator(self) -> None: + 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) + stream.sendall( + _HANDSHAKE.pack( + _HANDSHAKE_MAGIC, + _VERSION, + self.rank, + self._token, + ) + ) + self._stream = stream + return + 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") + header = _HEADER.pack( + _MESSAGE_MAGIC, + _VERSION, + self._sequence, + len(payload), + zlib.crc32(payload), + ) + 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 = _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") + return pickle.loads(payload) if payload else None + + def close(self) -> None: + for stream in self._peers.values(): + try: + stream.close() + except OSError: + pass + self._peers.clear() + if self._stream is not None: + try: + self._stream.close() + except OSError: + pass + self._stream = None + if self._listener is not None: + try: + self._listener.close() + except OSError: + pass + self._listener = None + + def __exit__(self, *_exc: Any) -> None: + self.close() + + +__all__ = ["RankControlPlane"] diff --git a/omlx/cluster/inference_worker.py b/omlx/cluster/inference_worker.py index 6134d2895a..30412af192 100644 --- a/omlx/cluster/inference_worker.py +++ b/omlx/cluster/inference_worker.py @@ -14,14 +14,18 @@ import threading import time from collections.abc import Sequence -from contextlib import contextmanager, suppress +from contextlib import contextmanager, nullcontext, suppress from datetime import UTC, datetime from functools import wraps from pathlib import Path from types import SimpleNamespace from typing import Any -from .deployment import decode_worker_contract, decode_worker_path_map +from .control_plane import RankControlPlane +from .deployment import ( + decode_worker_contract, + decode_worker_path_map, +) from .liveness import PeerWatchdog from .memory_guard import ( admission_budget, @@ -1447,7 +1451,19 @@ def run_worker(args: argparse.Namespace) -> int: 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, @@ -1466,6 +1482,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, @@ -1546,6 +1563,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", @@ -1580,6 +1600,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/launch.py b/omlx/cluster/launch.py index d9e1318b13..b002cb05af 100644 --- a/omlx/cluster/launch.py +++ b/omlx/cluster/launch.py @@ -602,6 +602,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: @@ -730,6 +747,8 @@ 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, ) -> list[str]: """Build an argument vector without a user-controlled shell fragment. @@ -757,6 +776,15 @@ 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") + if (control_host is None) != (control_port is None): + raise ValueError("rank-control host and port 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") if cwd is not None and not cwd.is_absolute(): raise ValueError("distributed working directory must be absolute") @@ -829,6 +857,17 @@ def build_mlx_launch_argv( deployment.execution.tuning_reason, ] ) + if control_host is not None and control_port is not None: + argv.extend( + [ + "--control-host", + control_host, + "--control-port", + str(control_port), + "--control-token", + deployment.plan_hash, + ] + ) if deployment.execution.prompt_cache_bytes is not None: argv.extend( [ @@ -2178,6 +2217,7 @@ 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.ready_event: dict[str, Any] | None = None self.rank_ready_events: dict[int, dict[str, Any]] = {} self.failure_event: dict[str, Any] | None = None @@ -2229,6 +2269,8 @@ 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) argv = build_mlx_launch_argv( self.deployment, hostfile=hostfile, @@ -2237,6 +2279,8 @@ 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, ) self._phase = "loading" try: @@ -2526,6 +2570,7 @@ def _terminate(self) -> None: self.process = None self.port = None self.collective_port = None + self.control_port = None self.ready_event = None self.rank_ready_events.clear() self.failure_event = None diff --git a/omlx/cluster/telemetry.py b/omlx/cluster/telemetry.py index 00f37e694d..1a0b9fec9c 100644 --- a/omlx/cluster/telemetry.py +++ b/omlx/cluster/telemetry.py @@ -773,6 +773,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. diff --git a/tests/test_cluster_control_plane.py b/tests/test_cluster_control_plane.py new file mode 100644 index 0000000000..3b159751d7 --- /dev/null +++ b/tests/test_cluster_control_plane.py @@ -0,0 +1,73 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Reliable TCP control plane kept independent of MLX/JACCL collectives.""" + +import socket +import threading + +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") diff --git a/tests/test_cluster_launch.py b/tests/test_cluster_launch.py index b929ea187b..ac487a3eac 100644 --- a/tests/test_cluster_launch.py +++ b/tests/test_cluster_launch.py @@ -94,6 +94,8 @@ 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, ) assert argv[0] == "/opt/omlx/bin/python" @@ -101,6 +103,9 @@ 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] == 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" From c05925696fd0ad3d1bb915f55b717554cd58335a Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Sat, 22 Aug 2026 10:46:44 -0700 Subject: [PATCH 17/29] Use sustained cluster readiness canary --- omlx/cluster/routes.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index 9c282f8ea2..dafae50eaf 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -3451,7 +3451,13 @@ async def _activate_and_report( ) canary = await engine.generate( "__omlx_cluster_readiness__", - max_tokens=1, + # A one-token GenerationBatch still pipelines and then + # discards a successor graph. That terminal-only boundary can + # leave a peer inside its final JACCL all-reduce even though + # rank zero already produced a valid response. Four tokens + # exercise sustained synchronized decode and make readiness a + # stronger, representative proof. + max_tokens=4, temperature=0.0, top_p=1.0, top_k=0, From df0d1a02538306b1a8722f3895240fa3f12418d6 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Sun, 23 Aug 2026 04:08:29 -0700 Subject: [PATCH 18/29] Clear stale cluster engines after reused PGIDs --- omlx/cluster/launch.py | 78 +++++++++++++++++++++++++++--------- tests/test_cluster_launch.py | 38 ++++++++++++++++++ 2 files changed, 97 insertions(+), 19 deletions(-) diff --git a/omlx/cluster/launch.py b/omlx/cluster/launch.py index b002cb05af..529ad723aa 100644 --- a/omlx/cluster/launch.py +++ b/omlx/cluster/launch.py @@ -2511,9 +2511,26 @@ def _terminate(self) -> None: 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())) @@ -2523,32 +2540,55 @@ def _terminate(self) -> None: # that rank orphaned (PPID 1) and its unified-memory allocation # resident. Stop is complete only when the entire launch process # group has disappeared. - remaining = max(0.0, deadline - time.monotonic()) - 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", - ) - with suppress(ProcessLookupError): - os.killpg(process_group, signal.SIGKILL) - group_gone = _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() - if not group_gone and not _process_group_alive(process_group): + 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"process group {process_group} survived SIGKILL twice" + ( + 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( diff --git a/tests/test_cluster_launch.py b/tests/test_cluster_launch.py index ac487a3eac..2ace83bf58 100644 --- a/tests/test_cluster_launch.py +++ b/tests/test_cluster_launch.py @@ -406,6 +406,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() From 5706dbf18eedb82fafe44811e94c767332395a08 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Sat, 22 Aug 2026 12:28:07 -0700 Subject: [PATCH 19/29] Ignore cluster control JSON in runtime marker reader --- omlx/cluster/runtime.py | 13 ++++++++++++- tests/test_cluster_runtime.py | 16 ++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) 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/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(), From 763b547464f0d120110b5f1e5aeb15f532158c13 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Mon, 24 Aug 2026 02:20:52 -0700 Subject: [PATCH 20/29] Bootstrap JACCL through resilient side channel --- omlx/cluster/inference_worker.py | 4 +- omlx/cluster/jaccl_side_channel.py | 223 +++++++++++++++++++++++++++++ omlx/cluster/performance_worker.py | 9 +- tests/test_jaccl_side_channel.py | 89 ++++++++++++ 4 files changed, 323 insertions(+), 2 deletions(-) create mode 100644 omlx/cluster/jaccl_side_channel.py create mode 100644 tests/test_jaccl_side_channel.py diff --git a/omlx/cluster/inference_worker.py b/omlx/cluster/inference_worker.py index 30412af192..c6964e30ef 100644 --- a/omlx/cluster/inference_worker.py +++ b/omlx/cluster/inference_worker.py @@ -1192,7 +1192,9 @@ 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) + 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): diff --git a/omlx/cluster/jaccl_side_channel.py b/omlx/cluster/jaccl_side_channel.py new file mode 100644 index 0000000000..3b7686f61b --- /dev/null +++ b/omlx/cluster/jaccl_side_channel.py @@ -0,0 +1,223 @@ +# 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 sys +import threading +import time +from collections.abc import Callable + + +_RANK_BYTES = struct.Struct("!I") +_DEFAULT_BOOTSTRAP_TIMEOUT_SECONDS = 20.0 +_DEFAULT_CONNECT_RETRY_SECONDS = 0.05 + + +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 _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 jaccl_all_gather_factory(rank: int, size: int) -> Callable[[bytes, int], bytes]: + """Return JACCL's supported metadata all-gather callable for one rank.""" + + return _SocketAllGather(rank, size) + + +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 = getattr(mx, "distributed") + selected = backend + if selected is None and os.environ.get("MLX_JACCL_COORDINATOR"): + selected = "jaccl" + if selected == "jaccl" and _enabled(): + return distributed.init( + backend="jaccl", + strict=strict, + all_gather_factory=jaccl_all_gather_factory, + ) + if selected is None: + return distributed.init(strict=strict) + return distributed.init(backend=selected, strict=strict) diff --git a/omlx/cluster/performance_worker.py b/omlx/cluster/performance_worker.py index a1c11ba779..0854b5549b 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 @@ -62,7 +63,13 @@ def _collective_measurements( 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) diff --git a/tests/test_jaccl_side_channel.py b/tests/test_jaccl_side_channel.py new file mode 100644 index 0000000000..e62921f54c --- /dev/null +++ b/tests/test_jaccl_side_channel.py @@ -0,0 +1,89 @@ +# 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") + 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", + } + + +@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" + + 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} From 0a205c4e693ef837e7adbb00594a18a6c9e6c674 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Mon, 24 Aug 2026 02:31:39 -0700 Subject: [PATCH 21/29] Route JACCL bootstrap through macOS sidecar --- omlx/cluster/jaccl_side_channel.py | 261 ++++++++++++++++++++++++++++- tests/test_jaccl_side_channel.py | 47 ++++++ 2 files changed, 303 insertions(+), 5 deletions(-) diff --git a/omlx/cluster/jaccl_side_channel.py b/omlx/cluster/jaccl_side_channel.py index 3b7686f61b..429d807e2a 100644 --- a/omlx/cluster/jaccl_side_channel.py +++ b/omlx/cluster/jaccl_side_channel.py @@ -13,8 +13,10 @@ from __future__ import annotations import os +from pathlib import Path import socket import struct +import subprocess import sys import threading import time @@ -24,6 +26,121 @@ _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: @@ -83,6 +200,21 @@ def _recv_exact(sock: socket.socket, n_bytes: int) -> bytes: 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 = getattr(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: @@ -189,12 +321,129 @@ def __call__(self, src: bytes, n_bytes: int) -> bytes: 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 = getattr(distributed, "init") + return "all_gather_factory" in (getattr(init, "__doc__", "") or "") + + def init_cluster_group( mx: object, *, @@ -213,11 +462,13 @@ def init_cluster_group( if selected is None and os.environ.get("MLX_JACCL_COORDINATOR"): selected = "jaccl" if selected == "jaccl" and _enabled(): - return distributed.init( - backend="jaccl", - strict=strict, - all_gather_factory=jaccl_all_gather_factory, - ) + 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/tests/test_jaccl_side_channel.py b/tests/test_jaccl_side_channel.py index e62921f54c..366534cc64 100644 --- a/tests/test_jaccl_side_channel.py +++ b/tests/test_jaccl_side_channel.py @@ -25,6 +25,7 @@ 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() @@ -57,6 +58,35 @@ def rank_zero() -> None: } +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) + getattr(first, "close")() + getattr(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) @@ -72,6 +102,8 @@ def init(self, **kwargs): calls.append(kwargs) return "group" + Distributed.init.__doc__ = "init(..., *, all_gather_factory: Callable = None)" + class MX: distributed = Distributed() @@ -87,3 +119,18 @@ class MX: 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}] From ca2690d18c9a0343ca05b4e1576b12b12394cf4e Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Mon, 24 Aug 2026 12:15:35 -0700 Subject: [PATCH 22/29] Hold a process lease for JACCL RDMA --- docs/distributed-cluster.md | 5 ++ omlx/cluster/inference_worker.py | 11 +++ omlx/cluster/jaccl_lease.py | 116 +++++++++++++++++++++++++++++ omlx/cluster/performance_worker.py | 18 ++++- tests/test_cluster_jaccl_lease.py | 47 ++++++++++++ 5 files changed, 196 insertions(+), 1 deletion(-) create mode 100644 omlx/cluster/jaccl_lease.py create mode 100644 tests/test_cluster_jaccl_lease.py 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/inference_worker.py b/omlx/cluster/inference_worker.py index c6964e30ef..d63b42cfd1 100644 --- a/omlx/cluster/inference_worker.py +++ b/omlx/cluster/inference_worker.py @@ -26,6 +26,7 @@ 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, @@ -1192,6 +1193,14 @@ def run_worker(args: argparse.Namespace) -> int: ) execution = _execution_settings(args) init_backend = "jaccl" if args.backend.startswith("jaccl") else "ring" + 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) @@ -1517,6 +1526,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 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/performance_worker.py b/omlx/cluster/performance_worker.py index 0854b5549b..355c8dd7df 100644 --- a/omlx/cluster/performance_worker.py +++ b/omlx/cluster/performance_worker.py @@ -60,7 +60,7 @@ 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 from .jaccl_side_channel import init_cluster_group @@ -110,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/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() From 633e48ec193d3a16ac13725590874d13bb4aaa35 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Tue, 25 Aug 2026 20:58:41 -0700 Subject: [PATCH 23/29] fix(cluster): verify rank exit on unload --- omlx/cluster/launch.py | 119 +++++++++++++++++++++++++++++++++++ omlx/cluster/routes.py | 110 ++++++++++++++++++++++++++++++++ tests/test_cluster_launch.py | 42 +++++++++++++ tests/test_cluster_routes.py | 34 ++++++++++ 4 files changed, 305 insertions(+) diff --git a/omlx/cluster/launch.py b/omlx/cluster/launch.py index 529ad723aa..061e54dca9 100644 --- a/omlx/cluster/launch.py +++ b/omlx/cluster/launch.py @@ -496,6 +496,125 @@ def _sweep_rank_processes( return 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", *, diff --git a/omlx/cluster/routes.py b/omlx/cluster/routes.py index dafae50eaf..da57bf22d6 100644 --- a/omlx/cluster/routes.py +++ b/omlx/cluster/routes.py @@ -65,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, @@ -3832,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): @@ -3853,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/tests/test_cluster_launch.py b/tests/test_cluster_launch.py index 2ace83bf58..51ce33e54b 100644 --- a/tests/test_cluster_launch.py +++ b/tests/test_cluster_launch.py @@ -53,6 +53,48 @@ 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 = [] diff --git a/tests/test_cluster_routes.py b/tests/test_cluster_routes.py index 941dc0d3f8..a953e2617e 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 @@ -875,6 +889,26 @@ def test_cluster_deployment_recomputes_plan_and_preflights(tmp_path, monkeypatch 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 From 0e38d5c7036759a6857f4482817b853b49a983c9 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Wed, 26 Aug 2026 03:56:31 -0700 Subject: [PATCH 24/29] fix(cluster): keep control transport on the runtime layer --- omlx/cluster/control_plane.py | 33 +++++++++++++++++++++++++++++++++ omlx/engine/distributed.py | 6 ------ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/omlx/cluster/control_plane.py b/omlx/cluster/control_plane.py index d94707d132..f9f58ca1f1 100644 --- a/omlx/cluster/control_plane.py +++ b/omlx/cluster/control_plane.py @@ -11,6 +11,12 @@ from contextlib import AbstractContextManager from typing import Any +from .system_socket_proxy import ( + SystemSocketProxy, + open_system_tcp_proxy, + should_proxy_control_socket, +) + _HANDSHAKE_MAGIC = b"OC2H" _MESSAGE_MAGIC = b"OC2M" _VERSION = 1 @@ -67,6 +73,7 @@ def __init__( 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": @@ -115,6 +122,29 @@ def _accept_workers(self) -> None: raise 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) + stream.sendall( + _HANDSHAKE.pack( + _HANDSHAKE_MAGIC, + _VERSION, + self.rank, + self._token, + ) + ) + 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: @@ -194,6 +224,9 @@ def close(self) -> None: except OSError: pass self._stream = None + if self._stream_proxy is not None: + self._stream_proxy.close() + self._stream_proxy = None if self._listener is not None: try: self._listener.close() diff --git a/omlx/engine/distributed.py b/omlx/engine/distributed.py index 8e695d6626..60818ce568 100644 --- a/omlx/engine/distributed.py +++ b/omlx/engine/distributed.py @@ -926,9 +926,6 @@ async def stream_chat( except httpx.ReadTimeout as exc: raise self._read_timeout_error(stream=True) from exc except httpx.HTTPError as exc: - # abort_request() closed this response; surface the abort, not a - # spurious transport failure. - self._raise_if_aborted(request_id) raise await self._transport_failure_error( exc, stream=True, @@ -1186,9 +1183,6 @@ async def stream_generate( except httpx.ReadTimeout as exc: raise self._read_timeout_error(stream=True) from exc except httpx.HTTPError as exc: - # abort_request() closed this response; surface the abort, not a - # spurious transport failure. - self._raise_if_aborted(request_id) raise await self._transport_failure_error( exc, stream=True, From 85680c88f503b7953d14d5b517e15676d43f9828 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Wed, 26 Aug 2026 04:03:17 -0700 Subject: [PATCH 25/29] fix(cluster): fail closed when rank exit cannot be proven --- omlx/cluster/backends.py | 16 +- omlx/cluster/control_plane.py | 20 +- omlx/cluster/inference_worker.py | 13 +- omlx/cluster/jaccl_side_channel.py | 29 +- omlx/cluster/launch.py | 306 ++++++++++++++++++++-- omlx/cluster/liveness.py | 16 +- omlx/cluster/telemetry.py | 15 +- omlx/engine_pool.py | 19 +- tests/test_cluster_inference_worker.py | 24 +- tests/test_cluster_launch.py | 105 +++++--- tests/test_cluster_liveness.py | 119 ++++++--- tests/test_cluster_progressive_loading.py | 116 -------- tests/test_cluster_routes.py | 213 ++++++++------- tests/test_cluster_runtime_v2.py | 48 ++-- tests/test_jaccl_side_channel.py | 4 +- 15 files changed, 642 insertions(+), 421 deletions(-) diff --git a/omlx/cluster/backends.py b/omlx/cluster/backends.py index 95d3c7544d..cf96a561ab 100644 --- a/omlx/cluster/backends.py +++ b/omlx/cluster/backends.py @@ -22,8 +22,9 @@ from __future__ import annotations +from collections.abc import Iterable from dataclasses import dataclass, field -from typing import Any, Iterable +from typing import Any @dataclass(frozen=True) @@ -37,9 +38,7 @@ class MemberFabric: 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))) - ) + object.__setattr__(self, "rdma_devices", tuple(sorted(set(self.rdma_devices)))) @property def jaccl_ready(self) -> bool: @@ -88,17 +87,12 @@ def select_cluster_backend(members: Iterable[MemberFabric]) -> BackendSelection: 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 - ) + 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 " - f"{len(members)} members" + f"rdma_ctl is enabled with RDMA devices on all {len(members)} members" ), members=members, ) diff --git a/omlx/cluster/control_plane.py b/omlx/cluster/control_plane.py index f9f58ca1f1..699180220c 100644 --- a/omlx/cluster/control_plane.py +++ b/omlx/cluster/control_plane.py @@ -8,7 +8,7 @@ import struct import time import zlib -from contextlib import AbstractContextManager +from contextlib import AbstractContextManager, suppress from typing import Any from .system_socket_proxy import ( @@ -76,7 +76,7 @@ def __init__( self._stream_proxy: SystemSocketProxy | None = None self._sequence = 0 - def __enter__(self) -> "RankControlPlane": + def __enter__(self) -> RankControlPlane: if self.rank == 0: self._accept_workers() else: @@ -167,9 +167,7 @@ def _connect_to_coordinator(self) -> None: last_error = exc stream.close() time.sleep(0.05) - raise TimeoutError( - f"rank-control coordinator was unreachable: {last_error}" - ) + 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.""" @@ -213,25 +211,19 @@ def broadcast_object(self, obj: Any) -> Any: def close(self) -> None: for stream in self._peers.values(): - try: + with suppress(OSError): stream.close() - except OSError: - pass self._peers.clear() if self._stream is not None: - try: + with suppress(OSError): self._stream.close() - except OSError: - pass self._stream = None if self._stream_proxy is not None: self._stream_proxy.close() self._stream_proxy = None if self._listener is not None: - try: + with suppress(OSError): self._listener.close() - except OSError: - pass self._listener = None def __exit__(self, *_exc: Any) -> None: diff --git a/omlx/cluster/inference_worker.py b/omlx/cluster/inference_worker.py index d63b42cfd1..807582e9da 100644 --- a/omlx/cluster/inference_worker.py +++ b/omlx/cluster/inference_worker.py @@ -77,10 +77,7 @@ def _wait_for_serve_release( them and atomically writes this local release marker on every host. """ - path = ( - Path(state_dir).expanduser() - / f"{deployment_id}-serve.json" - ) + path = Path(state_dir).expanduser() / f"{deployment_id}-serve.json" deadline = float(clock()) + max(0.0, float(timeout)) while True: try: @@ -628,9 +625,7 @@ def _write_cancel_request( 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 - ) + 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) @@ -798,9 +793,7 @@ def on_abort(reason: str) -> None: plan_hash=marker.payload.get("plan_hash"), ) - abort_grace = float( - os.environ.get("OMLX_CLUSTER_PEER_ABORT_GRACE", "5.0") or 0.0 - ) + 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, diff --git a/omlx/cluster/jaccl_side_channel.py b/omlx/cluster/jaccl_side_channel.py index 429d807e2a..a5f35fbfd7 100644 --- a/omlx/cluster/jaccl_side_channel.py +++ b/omlx/cluster/jaccl_side_channel.py @@ -13,7 +13,6 @@ from __future__ import annotations import os -from pathlib import Path import socket import struct import subprocess @@ -21,7 +20,7 @@ import threading import time from collections.abc import Callable - +from pathlib import Path _RANK_BYTES = struct.Struct("!I") _DEFAULT_BOOTSTRAP_TIMEOUT_SECONDS = 20.0 @@ -32,7 +31,7 @@ # 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''' +_SIDECAR_PROGRAM = r""" import socket, struct, sys, time RANK = struct.Struct("!I") @@ -140,7 +139,7 @@ def 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: @@ -161,7 +160,9 @@ def _enabled() -> bool: upstream comparison and incident recovery. """ - return os.environ.get("OMLX_JACCL_PYTHON_SIDE_CHANNEL", "1").strip().lower() not in { + return os.environ.get( + "OMLX_JACCL_PYTHON_SIDE_CHANNEL", "1" + ).strip().lower() not in { "0", "false", "no", @@ -205,7 +206,7 @@ def _read_exact_stream(stream: object, n_bytes: int) -> bytes: chunks: list[bytes] = [] remaining = n_bytes - read = getattr(stream, "read") + read = stream.read while remaining: chunk = read(remaining) if not chunk: @@ -269,9 +270,13 @@ def _accept_peers(self, host: str, port: int) -> list[socket.socket]: peer, _address = server.accept() try: peer.settimeout(self.timeout) - peer_rank = _RANK_BYTES.unpack(_recv_exact(peer, _RANK_BYTES.size))[0] + 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") + raise RuntimeError( + "JACCL side channel received an invalid peer rank" + ) except BaseException: peer.close() raise @@ -383,9 +388,7 @@ def __init__(self, rank: int, size: int) -> None: stderr=subprocess.PIPE, bufsize=0, ) - _trace( - f"sidecar started rank={rank} size={size} coordinator={host}:{port}" - ) + _trace(f"sidecar started rank={rank} size={size} coordinator={host}:{port}") def _failure(self) -> RuntimeError: status = self._process.poll() @@ -440,7 +443,7 @@ def _mlx_supports_all_gather_factory(distributed: object) -> bool: JACCL load from looking like a fabric failure. """ - init = getattr(distributed, "init") + init = distributed.init return "all_gather_factory" in (getattr(init, "__doc__", "") or "") @@ -457,7 +460,7 @@ def init_cluster_group( control channel; collectives immediately thereafter remain RDMA/JACCL. """ - distributed = getattr(mx, "distributed") + distributed = mx.distributed selected = backend if selected is None and os.environ.get("MLX_JACCL_COORDINATOR"): selected = "jaccl" diff --git a/omlx/cluster/launch.py b/omlx/cluster/launch.py index 061e54dca9..6db7b1140a 100644 --- a/omlx/cluster/launch.py +++ b/omlx/cluster/launch.py @@ -51,6 +51,10 @@ _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): @@ -70,6 +74,129 @@ class DistributedTeardownError(DistributedLaunchError): """ +@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.""" @@ -162,8 +289,7 @@ def _pid_alive(pid: int) -> bool: def _launch_manifest_path(state_dir: str | Path, deployment_id: str) -> Path: return ( - Path(state_dir).expanduser() - / f"{_LAUNCH_MANIFEST_PREFIX}{deployment_id}.json" + Path(state_dir).expanduser() / f"{_LAUNCH_MANIFEST_PREFIX}{deployment_id}.json" ) @@ -191,8 +317,7 @@ def _serve_release_path(state_dir: str | Path, deployment_id: str) -> Path: ) _REMOTE_CLEAR_SERVE_MARKER_SCRIPT = ( - "import pathlib,sys;" - "pathlib.Path(sys.argv[1]).expanduser().unlink(missing_ok=True)" + "import pathlib,sys;pathlib.Path(sys.argv[1]).expanduser().unlink(missing_ok=True)" ) @@ -201,7 +326,7 @@ def _set_serve_release( state_dir: str | Path, payload: dict[str, Any] | None, *, - runner: "SSHRunner" = subprocess.run, + runner: SSHRunner = subprocess.run, ) -> None: """Atomically publish or clear the post-load serve gate on every rank.""" @@ -384,6 +509,65 @@ def _kill_remote_pid( 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, *, @@ -396,9 +580,9 @@ def _rank_marker_matches( if marker.get("deployment_id") != deployment_id or marker.get("rank") != rank: return False recorded = marker.get("plan_hash") - if plan_hash is not None and recorded is not None and recorded != plan_hash: - return False - return True + return not ( + plan_hash is not None and recorded is not None and recorded != plan_hash + ) def _sweep_rank_processes( @@ -407,6 +591,7 @@ def _sweep_rank_processes( *, 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]: @@ -417,8 +602,17 @@ def _sweep_rank_processes( """ 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", []): @@ -448,6 +642,28 @@ def _sweep_rank_processes( 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", @@ -457,9 +673,7 @@ def _sweep_rank_processes( deployment_id, ) else: - failures.append( - f"rank {rank} ({node_id}) pid {pid} survived SIGKILL" - ) + 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( @@ -467,7 +681,27 @@ def _sweep_rank_processes( f"{remote_root}/{filename}", ) if error: - failures.append(f"rank {rank} ({node_id}) marker unreadable: {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, @@ -493,7 +727,38 @@ def _sweep_rank_processes( failures.append( f"remote rank {rank} ({node_id}) pid {pid} could not be killed" ) - return failures + + # 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( @@ -520,10 +785,9 @@ def stop_deployment_processes( 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} - ): + 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"]) @@ -2589,7 +2853,12 @@ def _remove_launch_manifest(self) -> None: self.deployment.deployment_id, ).unlink(missing_ok=True) - def _sweep_rank_leftovers(self, *, kill_grace: float = 3.0) -> list[str]: + 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. @@ -2603,6 +2872,7 @@ def _sweep_rank_leftovers(self, *, kill_grace: float = 3.0) -> list[str]: ], state_dir=self.state_dir, plan_hash=self.deployment.plan_hash, + process_group=process_group, kill_grace=kill_grace, ) diff --git a/omlx/cluster/liveness.py b/omlx/cluster/liveness.py index 188634de60..f51776509a 100644 --- a/omlx/cluster/liveness.py +++ b/omlx/cluster/liveness.py @@ -79,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: @@ -289,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 @@ -487,9 +491,7 @@ def __init__( 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: @@ -552,9 +554,7 @@ def run(self, *, sleep: Callable[[float], None] = time.sleep) -> None: try: self._on_abort(reason) except Exception: - logger.warning( - "Peer watchdog abort stage failed", exc_info=True - ) + 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 diff --git a/omlx/cluster/telemetry.py b/omlx/cluster/telemetry.py index 1a0b9fec9c..d1e892f8dc 100644 --- a/omlx/cluster/telemetry.py +++ b/omlx/cluster/telemetry.py @@ -3,8 +3,10 @@ from __future__ import annotations +import json import logging import math +import os import shutil import threading import time @@ -14,9 +16,6 @@ from pathlib import Path from typing import Any, Protocol -import json -import os - from .performance import ExecutionSettings from .planner import PipelineAssignment @@ -250,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 diff --git a/omlx/engine_pool.py b/omlx/engine_pool.py index 8f6e0aa694..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(): @@ -1223,24 +1223,9 @@ def _entry_has_active_requests(entry: EngineEntry) -> bool: if not callable(has_active_requests): return False try: - if has_active_requests() is True: - return True + return has_active_requests() is True except Exception: return True - # Distributed engines: the coordinator counter draining only proves - # the httpx side closed. Rank-side telemetry reporting active - # requests means the ranks are still generating and the entry is NOT - # quiescent (G5); no marker evidence (None) falls through, since a - # dead rank's marker is handled by the supervisor failure paths. - rank_side = getattr(engine, "rank_side_active_requests", None) - if callable(rank_side): - try: - remaining = rank_side() - except Exception: - remaining = None - if remaining: - return True - return False def _entry_is_busy(self, entry: EngineEntry) -> bool: return entry.in_use > 0 or self._entry_has_active_requests(entry) diff --git a/tests/test_cluster_inference_worker.py b/tests/test_cluster_inference_worker.py index 4e19f0b9ae..02af1cc423 100644 --- a/tests/test_cluster_inference_worker.py +++ b/tests/test_cluster_inference_worker.py @@ -20,9 +20,9 @@ _execution_settings, _install_distributed_model_protocol, _server_arguments, - _wait_for_serve_release, _validate_loaded_stage, _validate_measured_weight_bytes, + _wait_for_serve_release, _watch_launcher_parent, _write_cancel_request, build_parser, @@ -1221,15 +1221,15 @@ def test_launcher_watchdog_ignores_a_fresh_lease(tmp_path): polls = [0] - class StopLoop(Exception): + class StopLoopError(Exception): pass def wait(_seconds): polls[0] += 1 if polls[0] >= 3: - raise StopLoop + raise StopLoopError - with pytest.raises(StopLoop): + with pytest.raises(StopLoopError): _watch_launcher_parent( 42, marker, @@ -1251,15 +1251,15 @@ def test_launcher_watchdog_ignores_a_lease_that_never_appeared(tmp_path): polls = [0] - class StopLoop(Exception): + class StopLoopError(Exception): pass def wait(_seconds): polls[0] += 1 if polls[0] >= 3: - raise StopLoop + raise StopLoopError - with pytest.raises(StopLoop): + with pytest.raises(StopLoopError): _watch_launcher_parent( 42, marker, @@ -1275,7 +1275,9 @@ def wait(_seconds): 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) + _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 @@ -1360,9 +1362,7 @@ def test_release_metal_memory_without_mlx_is_a_noop(monkeypatch): def test_sigterm_handler_releases_metal_before_interrupt(monkeypatch): releases: list[str] = [] - monkeypatch.setattr( - inference_worker, "_release_metal_memory", releases.append - ) + 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) @@ -1432,6 +1432,8 @@ def run(self): 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_launch.py b/tests/test_cluster_launch.py index 51ce33e54b..fd8631489b 100644 --- a/tests/test_cluster_launch.py +++ b/tests/test_cluster_launch.py @@ -81,9 +81,7 @@ def sweep(deployment_id, hosts, **kwargs): assert calls[0][2]["plan_hash"] == deployment.plan_hash -def test_stop_deployment_processes_refuses_unverified_rank_exit( - tmp_path, monkeypatch -): +def test_stop_deployment_processes_refuses_unverified_rank_exit(tmp_path, monkeypatch): deployment = _deployment() monkeypatch.setattr( launch, @@ -257,7 +255,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] == [ @@ -856,9 +854,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(): @@ -878,9 +874,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, @@ -951,8 +948,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 ) @@ -1328,9 +1324,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." @@ -1748,7 +1742,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() @@ -1814,7 +1810,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() @@ -1936,6 +1934,8 @@ def fake_ssh(ssh_target, command, **kwargs): finally: victim.kill() victim.wait() + + def _fake_launcher(pid: int = 43210): class Launcher: stdout = None @@ -2054,9 +2054,7 @@ def test_supervisor_stop_raises_and_keeps_state_when_group_survives( assert launch._launch_manifest_path(tmp_path, "cluster-test").exists() -def test_supervisor_stop_raises_on_unkillable_leftover_rank( - tmp_path, monkeypatch -): +def test_supervisor_stop_raises_on_unkillable_leftover_rank(tmp_path, monkeypatch): supervisor = launch.DistributedJobSupervisor( _deployment(), preflight=False, @@ -2121,9 +2119,7 @@ def test_verified_stop_writes_then_removes_launch_manifest(tmp_path, monkeypatch assert supervisor.status().phase == "stopped" -def test_teardown_sweep_kills_leftover_local_rank_by_marker_pid( - tmp_path, monkeypatch -): +def test_teardown_sweep_kills_leftover_local_rank_by_marker_pid(tmp_path, monkeypatch): supervisor = launch.DistributedJobSupervisor( _deployment(), preflight=False, @@ -2139,6 +2135,23 @@ def fake_kill(pid, sig): 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, @@ -2170,6 +2183,19 @@ def test_teardown_sweep_reports_an_unkillable_rank(tmp_path, monkeypatch): 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( @@ -2180,7 +2206,8 @@ def test_teardown_sweep_reports_an_unkillable_rank(tmp_path, monkeypatch): failures = supervisor._sweep_rank_leftovers(kill_grace=0.01) - assert failures == ["rank 0 (local) pid 424242 survived SIGKILL"] + 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): @@ -2202,8 +2229,7 @@ class Result: monkeypatch.setattr( launch, "_run_cluster_ssh", - lambda target, command, **kw: commands.append((target, command)) - or Result(), + lambda target, command, **kw: commands.append((target, command)) or Result(), ) failures = supervisor._sweep_rank_leftovers(kill_grace=0.01) @@ -2267,12 +2293,31 @@ def fake_kill(pid, sig): ) )["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), + 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) @@ -2298,9 +2343,7 @@ def test_reap_orphaned_launches_leaves_an_active_job_alone(tmp_path, monkeypatch 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.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) diff --git a/tests/test_cluster_liveness.py b/tests/test_cluster_liveness.py index 45690ecb08..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 diff --git a/tests/test_cluster_progressive_loading.py b/tests/test_cluster_progressive_loading.py index 5f1e338c87..567468aa66 100644 --- a/tests/test_cluster_progressive_loading.py +++ b/tests/test_cluster_progressive_loading.py @@ -406,119 +406,3 @@ def reject_tokenizer(_path, config, **_kwargs): ) assert calls == [("tokenizer", {"trust_remote_code": False})] - - -def test_tensor_load_does_not_pin_pre_sharded_layer_arrays(monkeypatch): - """The layer-snapshot list must not survive into the sharding pass. - - Regression: ``flat`` pinned every pre-shard array for the whole strategy - run, so each materialized layer stayed resident in full next to its - shard — a TP=2 rank grew toward ~1.5x the whole model until the load - watchdog killed it (163 GiB against an 84 GiB plan), and a 128 GB node - ran out of memory entirely. The pre-shard arrays must be unreachable the - moment the strategy starts swapping in sharded slices. - """ - import gc - import weakref - - class Arr: - def __init__(self, name): - self.name = name - - class FakeModel: - model_type = "native_test" - - def __init__(self): - self.params = { - "embed.weight": Arr("embed"), - "lm_head.weight": Arr("head"), - "mtp.0.weight": Arr("mtp"), - "model.layers.0.weight": Arr("layer-0"), - "model.layers.1.weight": Arr("layer-1"), - } - self.shard = lambda group: None - - def parameters(self): - return self.params - - model = FakeModel() - originals = { - key: weakref.ref(value) - for key, value in model.params.items() - if ".layers." in key - } - embed_ref = weakref.ref(model.params["embed.weight"]) - head_ref = weakref.ref(model.params["lm_head.weight"]) - mtp_ref = weakref.ref(model.params["mtp.0.weight"]) - - def fake_strategy(shard_model, group, *, mx_module, progress=None): - # A large output projection must remain lazy until it can be sliced; - # evaluating it in the replicated fixed phase causes the avoidable - # full-head memory spike this loader is designed to prevent. - assert "head" not in mx_module.evaluated - assert "mtp" not in mx_module.evaluated - for key in list(shard_model.params): - if ".layers." in key: - shard_model.params[key] = Arr(key + " shard") - shard_model.params["lm_head.weight"] = Arr("head shard") - shard_model.params["mtp.0.weight"] = Arr("mtp shard") - gc.collect() - # Checked *inside* the strategy: after this point a pinned original - # would sit next to its materialized shard for the rest of the load. - assert all(ref() is None for ref in originals.values()) - assert head_ref() is None - assert mtp_ref() is None - return "native" - - monkeypatch.setattr( - "omlx.cluster.progressive_loading.apply_tensor_strategy", fake_strategy - ) - - class FakeMX: - cpu = object() - distributed = SimpleNamespace( - all_sum=lambda *_args, **_kwargs: (_ for _ in ()).throw( - AssertionError("launcher rank_ready markers own the load barrier") - ) - ) - - def __init__(self): - self.evaluated = [] - - def array(self, value): - return value - - def eval(self, *values): - self.evaluated.extend( - value.name for value in values if isinstance(value, Arr) - ) - - def clear_cache(self): - pass - - fake_utils = SimpleNamespace( - _download=lambda repo, allow_patterns=None: repo, - load_config=lambda path: {}, - load_tokenizer=lambda path, config, eos_token_ids=None: "tokenizer", - load_model=lambda path, **kwargs: (model, {}), - tree_flatten=lambda params: list(params.items()), - ) - - fake_mx = FakeMX() - loaded, tokenizer = progressive_sharded_load( - "fake-repo", - tensor_group=SimpleNamespace(), - utils_module=fake_utils, - mx_module=fake_mx, - ) - - assert loaded is model - assert tokenizer == "tokenizer" - gc.collect() - assert all(ref() is None for ref in originals.values()) - assert embed_ref() is not None - assert head_ref() is None - assert mtp_ref() is None - assert fake_mx.evaluated[:1] == ["embed"] - assert "head shard" in fake_mx.evaluated - assert "mtp shard" in fake_mx.evaluated diff --git a/tests/test_cluster_routes.py b/tests/test_cluster_routes.py index a953e2617e..c96b69cc21 100644 --- a/tests/test_cluster_routes.py +++ b/tests/test_cluster_routes.py @@ -536,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 @@ -622,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(): @@ -837,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) @@ -879,19 +882,14 @@ 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" - ) + 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 @@ -900,9 +898,7 @@ def test_cluster_deployment_recomputes_plan_and_preflights(tmp_path, monkeypatch 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" - ) + 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 @@ -949,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) @@ -1008,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) @@ -1056,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) @@ -1226,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) @@ -1260,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(): @@ -1276,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) @@ -1376,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, @@ -2071,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_v2.py b/tests/test_cluster_runtime_v2.py index fce2d2c946..a424387b56 100644 --- a/tests/test_cluster_runtime_v2.py +++ b/tests/test_cluster_runtime_v2.py @@ -101,8 +101,11 @@ def test_backend_selection_endpoint(): "/admin/api/cluster/backend-selection", json={ "members": [ - {"node_id": "studio", "rdma_ctl_enabled": True, - "rdma_devices": ["rdma_en5"]}, + { + "node_id": "studio", + "rdma_ctl_enabled": True, + "rdma_devices": ["rdma_en5"], + }, {"node_id": "macbook", "rdma_ctl_enabled": False}, ] }, @@ -120,10 +123,16 @@ def test_backend_selection_endpoint_all_rdma_picks_jaccl(): "/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"]}, + { + "node_id": "a", + "rdma_ctl_enabled": True, + "rdma_devices": ["rdma_en1"], + }, + { + "node_id": "b", + "rdma_ctl_enabled": True, + "rdma_devices": ["rdma_en5"], + }, ] }, ) @@ -164,10 +173,18 @@ def test_replan_auto_selects_jaccl_from_complete_matrix(tmp_path, monkeypatch): {"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]}, + { + "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( @@ -204,8 +221,7 @@ def test_replan_auto_falls_back_to_ring(tmp_path, monkeypatch): ], "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": "small", "ssh": "studio.local", "ips": ["192.168.5.2"]}, ], }, ) @@ -384,14 +400,10 @@ def test_ring_teardown_reports_unkillable_leftover_rank(monkeypatch): monkeypatch.setattr( launch, "_sweep_rank_processes", - lambda *args, **kwargs: [ - "rank 2 (mini): pid 999 survived SIGKILL" - ], + lambda *args, **kwargs: ["rank 2 (mini): pid 999 survived SIGKILL"], ) - with pytest.raises( - launch.DistributedTeardownError, match="rank 2 \\(mini\\)" - ): + with pytest.raises(launch.DistributedTeardownError, match="rank 2 \\(mini\\)"): supervisor.stop() assert supervisor.process is not None diff --git a/tests/test_jaccl_side_channel.py b/tests/test_jaccl_side_channel.py index 366534cc64..1f51bd5f11 100644 --- a/tests/test_jaccl_side_channel.py +++ b/tests/test_jaccl_side_channel.py @@ -79,8 +79,8 @@ def rank_zero() -> None: thread.start() results["client"] = second(b"bb", 2) thread.join(3) - getattr(first, "close")() - getattr(second, "close")() + first.close() + second.close() assert not thread.is_alive() assert not errors From c02055ecfc1288f621c78e8e137f7f7370571ce4 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Wed, 26 Aug 2026 04:35:38 -0700 Subject: [PATCH 26/29] test(cluster): mark runtime-first UI seams explicitly --- omlx/cluster/launch.py | 6 ------ tests/test_cluster_seams.py | 8 ++++++++ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/omlx/cluster/launch.py b/omlx/cluster/launch.py index 6db7b1140a..73985ed65a 100644 --- a/omlx/cluster/launch.py +++ b/omlx/cluster/launch.py @@ -293,12 +293,6 @@ def _launch_manifest_path(state_dir: str | Path, deployment_id: str) -> Path: ) -def _launcher_log_path(state_dir: str | Path, deployment_id: str) -> Path: - """Private, durable output from every rank relayed by ``mlx.launch``.""" - - return Path(state_dir).expanduser() / f"{deployment_id}-launcher.log" - - def _serve_release_path(state_dir: str | Path, deployment_id: str) -> Path: """Coordinator-owned gate that releases loaded ranks into serving.""" diff --git a/tests/test_cluster_seams.py b/tests/test_cluster_seams.py index 59716bb2c6..62b3803a08 100644 --- a/tests/test_cluster_seams.py +++ b/tests/test_cluster_seams.py @@ -77,6 +77,14 @@ def test_no_cluster_route_is_unreachable_from_the_dashboard(): # The backend PR intentionally lands before the Cluster v2 dashboard. The # UI follow-up will call replan after the deployment contract settles. allowed_without_caller: set[str] = {"/admin/api/cluster/replan"} + # Runtime lifecycle APIs land before the Cluster v2 dashboard follow-up. + allowed_without_caller.update( + { + "/admin/api/cluster/backend-selection", + "/admin/api/cluster/deployments/{parameter}/load", + "/admin/api/cluster/deployments/{parameter}/unload", + } + ) unreachable = _registered_routes() - _js_called_paths() - allowed_without_caller assert not unreachable, ( f"cluster routes nothing calls: {sorted(unreachable)} — wire them up or " From 0ff823751fbff6616661e91dab8903cafb59c421 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Wed, 26 Aug 2026 04:56:47 -0700 Subject: [PATCH 27/29] fix(cluster): authenticate rank-control admission without listener DoS --- omlx/cluster/control_plane.py | 42 +++++++++++--- tests/test_cluster_control_plane.py | 85 +++++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 9 deletions(-) diff --git a/omlx/cluster/control_plane.py b/omlx/cluster/control_plane.py index 699180220c..a1206f81bc 100644 --- a/omlx/cluster/control_plane.py +++ b/omlx/cluster/control_plane.py @@ -3,6 +3,7 @@ from __future__ import annotations +import hmac import pickle import socket import struct @@ -18,9 +19,11 @@ ) _HANDSHAKE_MAGIC = b"OC2H" +_HANDSHAKE_ACK_MAGIC = b"OC2A" _MESSAGE_MAGIC = b"OC2M" _VERSION = 1 _HANDSHAKE = struct.Struct("!4sII64s") +_HANDSHAKE_ACK = struct.Struct("!4sI") _HEADER = struct.Struct("!4sIIII") _MAX_OBJECT_BYTES = 256 * 1024 * 1024 @@ -77,10 +80,14 @@ def __init__( self._sequence = 0 def __enter__(self) -> RankControlPlane: - if self.rank == 0: - self._accept_workers() - else: - self._connect_to_coordinator() + 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: @@ -103,7 +110,8 @@ def _accept_workers(self) -> None: stream, _address = listener.accept() except TimeoutError: continue - self._configure(stream) + remaining = max(0.1, deadline - time.monotonic()) + stream.settimeout(min(5.0, remaining)) try: magic, version, rank, token = _HANDSHAKE.unpack( _recv_exact(stream, _HANDSHAKE.size) @@ -113,13 +121,16 @@ def _accept_workers(self) -> None: or version != _VERSION or not 0 < rank < self.world_size or rank in self._peers - or token != self._token + or not hmac.compare_digest(token, self._token) ): - raise RuntimeError("rank-control handshake is invalid") + stream.close() + continue + self._configure(stream) + stream.sendall(_HANDSHAKE_ACK.pack(_HANDSHAKE_ACK_MAGIC, _VERSION)) self._peers[rank] = stream - except Exception: + except (OSError, TimeoutError, ConnectionError, struct.error): stream.close() - raise + continue def _connect_to_coordinator(self) -> None: if should_proxy_control_socket(self.host): @@ -139,6 +150,11 @@ def _connect_to_coordinator(self) -> None: self._token, ) ) + ack_magic, ack_version = _HANDSHAKE_ACK.unpack( + _recv_exact(stream, _HANDSHAKE_ACK.size) + ) + if ack_magic != _HANDSHAKE_ACK_MAGIC or ack_version != _VERSION: + raise RuntimeError("rank-control handshake was not acknowledged") except BaseException: proxy.close() raise @@ -161,8 +177,16 @@ def _connect_to_coordinator(self) -> None: self._token, ) ) + ack_magic, ack_version = _HANDSHAKE_ACK.unpack( + _recv_exact(stream, _HANDSHAKE_ACK.size) + ) + if ack_magic != _HANDSHAKE_ACK_MAGIC or ack_version != _VERSION: + raise RuntimeError("rank-control handshake was not acknowledged") self._stream = stream return + except RuntimeError: + stream.close() + raise except OSError as exc: last_error = exc stream.close() diff --git a/tests/test_cluster_control_plane.py b/tests/test_cluster_control_plane.py index 3b159751d7..4f8ea78799 100644 --- a/tests/test_cluster_control_plane.py +++ b/tests/test_cluster_control_plane.py @@ -2,8 +2,11 @@ """Reliable TCP control plane kept independent of MLX/JACCL collectives.""" import socket +import struct import threading +import pytest + from omlx.cluster.control_plane import RankControlPlane @@ -71,3 +74,85 @@ def test_rank_control_plane_rejects_invalid_identity(): 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: + stream.recv(struct.calcsize("!4sII64s")) + stream.sendall(struct.pack("!4sI", b"NOPE", 1)) + + 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() From 1d7428b0382b329dd0a696e62d8bd7599b49e658 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Wed, 26 Aug 2026 04:58:59 -0700 Subject: [PATCH 28/29] fix(cluster): replace public plan hash with launch-scoped control secret --- omlx/cluster/launch.py | 30 ++++++++++++++++++++++++++---- tests/test_cluster_launch.py | 28 ++++++++++++++++++++++++++-- 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/omlx/cluster/launch.py b/omlx/cluster/launch.py index 73985ed65a..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 @@ -1126,6 +1127,7 @@ def build_mlx_launch_argv( 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. @@ -1153,8 +1155,11 @@ 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") - if (control_host is None) != (control_port is None): - raise ValueError("rank-control host and port must be provided together") + 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)) @@ -1162,6 +1167,12 @@ def build_mlx_launch_argv( 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") @@ -1234,7 +1245,11 @@ def build_mlx_launch_argv( deployment.execution.tuning_reason, ] ) - if control_host is not None and control_port is not None: + if ( + control_host is not None + and control_port is not None + and control_token is not None + ): argv.extend( [ "--control-host", @@ -1242,7 +1257,7 @@ def build_mlx_launch_argv( "--control-port", str(control_port), "--control-token", - deployment.plan_hash, + control_token, ] ) if deployment.execution.prompt_cache_bytes is not None: @@ -2595,6 +2610,7 @@ def __init__( 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 @@ -2648,6 +2664,10 @@ def start(self) -> dict[str, Any]: 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, @@ -2658,6 +2678,7 @@ def start(self) -> dict[str, Any]: state_dir=self.state_dir, control_host=control_host, control_port=self.control_port, + control_token=self.control_token, ) self._phase = "loading" try: @@ -2994,6 +3015,7 @@ def _terminate(self) -> 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 diff --git a/tests/test_cluster_launch.py b/tests/test_cluster_launch.py index fd8631489b..1f984b5557 100644 --- a/tests/test_cluster_launch.py +++ b/tests/test_cluster_launch.py @@ -136,6 +136,7 @@ def test_launcher_argv_keeps_model_as_one_argument(tmp_path): cwd=Path("/opt/omlx"), control_host="10.0.0.1", control_port=32140, + control_token="e" * 64, ) assert argv[0] == "/opt/omlx/bin/python" @@ -145,7 +146,8 @@ def test_launcher_argv_keeps_model_as_one_argument(tmp_path): 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] == deployment.plan_hash + 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" @@ -166,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 = {} @@ -2206,7 +2227,10 @@ def test_teardown_sweep_reports_an_unkillable_rank(tmp_path, monkeypatch): 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( + "pid 424242" in failure and "survived SIGKILL" in failure + for failure in failures + ) assert any("Reboot this Mac" in failure for failure in failures) From e3eac115ef4728f0ecfc94d2c234e452b124da78 Mon Sep 17 00:00:00 2001 From: jonathan308 Date: Wed, 26 Aug 2026 05:09:37 -0700 Subject: [PATCH 29/29] fix(cluster): mutually authenticate rank-control sessions and payloads --- omlx/cluster/control_plane.py | 141 +++++++++++++++++++++------- tests/test_cluster_control_plane.py | 59 ++++++++++-- 2 files changed, 156 insertions(+), 44 deletions(-) diff --git a/omlx/cluster/control_plane.py b/omlx/cluster/control_plane.py index a1206f81bc..9f0aee35b1 100644 --- a/omlx/cluster/control_plane.py +++ b/omlx/cluster/control_plane.py @@ -3,8 +3,10 @@ from __future__ import annotations +import hashlib import hmac import pickle +import secrets import socket import struct import time @@ -19,13 +21,19 @@ ) _HANDSHAKE_MAGIC = b"OC2H" +_HANDSHAKE_CHALLENGE_MAGIC = b"OC2C" _HANDSHAKE_ACK_MAGIC = b"OC2A" _MESSAGE_MAGIC = b"OC2M" _VERSION = 1 -_HANDSHAKE = struct.Struct("!4sII64s") -_HANDSHAKE_ACK = struct.Struct("!4sI") -_HEADER = struct.Struct("!4sIIII") +_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: @@ -95,6 +103,14 @@ def _configure(self, stream: socket.socket) -> None: 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) @@ -113,25 +129,84 @@ def _accept_workers(self) -> None: remaining = max(0.1, deadline - time.monotonic()) stream.settimeout(min(5.0, remaining)) try: - magic, version, rank, token = _HANDSHAKE.unpack( + 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(token, self._token) + or not hmac.compare_digest(observed_tag, expected_tag) ): stream.close() continue self._configure(stream) - stream.sendall(_HANDSHAKE_ACK.pack(_HANDSHAKE_ACK_MAGIC, _VERSION)) + 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( @@ -142,19 +217,7 @@ def _connect_to_coordinator(self) -> None: stream = proxy.stream try: self._configure(stream) - stream.sendall( - _HANDSHAKE.pack( - _HANDSHAKE_MAGIC, - _VERSION, - self.rank, - self._token, - ) - ) - ack_magic, ack_version = _HANDSHAKE_ACK.unpack( - _recv_exact(stream, _HANDSHAKE_ACK.size) - ) - if ack_magic != _HANDSHAKE_ACK_MAGIC or ack_version != _VERSION: - raise RuntimeError("rank-control handshake was not acknowledged") + self._authenticate_worker_stream(stream) except BaseException: proxy.close() raise @@ -169,19 +232,7 @@ def _connect_to_coordinator(self) -> None: stream.settimeout(min(1.0, self._connect_timeout)) stream.connect((self.host, self.port)) self._configure(stream) - stream.sendall( - _HANDSHAKE.pack( - _HANDSHAKE_MAGIC, - _VERSION, - self.rank, - self._token, - ) - ) - ack_magic, ack_version = _HANDSHAKE_ACK.unpack( - _recv_exact(stream, _HANDSHAKE_ACK.size) - ) - if ack_magic != _HANDSHAKE_ACK_MAGIC or ack_version != _VERSION: - raise RuntimeError("rank-control handshake was not acknowledged") + self._authenticate_worker_stream(stream) self._stream = stream return except RuntimeError: @@ -201,12 +252,26 @@ def broadcast_object(self, obj: Any) -> Any: 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), - zlib.crc32(payload), + checksum, + tag, ) packet = header + payload for rank in range(1, self.world_size): @@ -216,7 +281,7 @@ def broadcast_object(self, obj: Any) -> Any: stream = self._stream if stream is None: raise RuntimeError("rank-control worker is not connected") - magic, version, sequence, size, checksum = _HEADER.unpack( + magic, version, sequence, size, checksum, observed_tag = _HEADER.unpack( _recv_exact(stream, _HEADER.size) ) if magic != _MESSAGE_MAGIC or version != _VERSION: @@ -231,6 +296,14 @@ def broadcast_object(self, obj: Any) -> Any: 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: diff --git a/tests/test_cluster_control_plane.py b/tests/test_cluster_control_plane.py index 4f8ea78799..b1b5737eab 100644 --- a/tests/test_cluster_control_plane.py +++ b/tests/test_cluster_control_plane.py @@ -1,9 +1,11 @@ # 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 @@ -138,21 +140,58 @@ def fake_coordinator(): ready.set() stream, _ = listener.accept() with stream: - stream.recv(struct.calcsize("!4sII64s")) - stream.sendall(struct.pack("!4sI", b"NOPE", 1)) + 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, + 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()