Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
33932f2
feat(cluster): harden rank control, teardown, and recovery (#3257)
jonathan308 Sep 8, 2026
42b92bc
fix(cluster): honor the load timeout while waiting for ranks
jundot Sep 8, 2026
b908f56
perf(cache): remove duplicate restore work and expose exact stream TT…
jonathan308 Sep 8, 2026
020d031
distributed: per-request abort, drain-confirmed abort_all, orphan-gen…
jonathan308 Aug 18, 2026
2652b01
distributed: tests for request abort, drain confirmation, and the orp…
jonathan308 Aug 18, 2026
e67ee3f
fix(distributed): preserve request identity through targeted aborts
jonathan308 Aug 26, 2026
556f6bd
feat(cluster): add request-scoped cancellation control
jonathan308 Aug 26, 2026
39b4e53
Make cluster cancellation and rank failure request-safe
jonathan308 Aug 23, 2026
1838e5f
fix(cluster): bind public disconnects to rank-scoped aborts
jonathan308 Aug 26, 2026
55f29ea
Bound distributed prefill cancellation to one chunk
jonathan308 Aug 23, 2026
b4e528d
Fence distributed cancellation before batch mutation
jonathan308 Aug 24, 2026
9ed9d94
fix(cluster): synchronize cancellation before batch mutation
jonathan308 Aug 26, 2026
30d3592
Persist distributed prompt snapshots across rank restarts
jonathan308 Aug 23, 2026
82ddba7
feat(cluster): persist reusable prompt snapshots across rank restarts
jonathan308 Aug 26, 2026
d0e8c90
Clear distributed prompt caches on every rank
jonathan308 Aug 24, 2026
5c73d71
Reach direct distributed engines during cache clear
jonathan308 Aug 24, 2026
bac6e5e
Run remote cache clear with cluster SSH runner
jonathan308 Aug 24, 2026
2c45a34
Acknowledge peer cache clears through rank markers
jonathan308 Aug 24, 2026
5a207f0
fix(cache): clear unloaded cluster peers
jonathan308 Aug 26, 2026
99fd1c7
fix(cluster): run rank cache maintenance through enrolled SSH
jonathan308 Aug 26, 2026
6135fd9
Synchronize pipeline prompt-cache plans
jonathan308 Aug 22, 2026
fd9a61c
Normalize rank response tokens at server boundary
jonathan308 Aug 22, 2026
dcb7189
fix(cluster): close cache and cancellation integration seams
jonathan308 Aug 26, 2026
fd547df
fix(cluster): restore distributed serving integration paths
jonathan308 Sep 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/distributed-cluster.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
194 changes: 188 additions & 6 deletions omlx/admin/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
import logging
import os
import re
import shlex
import shutil
import signal
import subprocess
import sys
import time
from collections import deque
Expand Down Expand Up @@ -63,6 +65,87 @@
PRESET_REMOTE_URL = "https://omlx.ai/assets/omlx_preset.json"


def _clear_cold_remote_cluster_cache_roots(
roots: tuple[Path, ...],
*,
runner: Any = subprocess.run,
) -> tuple[int, int]:
"""Remove unloaded cluster snapshots from every configured peer Mac.

Loaded ranks clear through their live cache managers. With no resident
engine, the normal SSD-clear action still has to reach peer-local snapshot
trees; deleting only the coordinator root makes the next load silently
restore data the user explicitly cleared.
"""

from ..cluster.launch import _run_cluster_ssh
from ..cluster.registry import get_cluster_registry

try:
deployments = get_cluster_registry().list()
except RuntimeError:
return 0, 0
if not deployments:
return 0, 0

allowed = {"cluster-prompt-snapshots", "prompt-cache-ssd"}
if any(path.expanduser().name not in allowed for path in roots):
raise RuntimeError("refusing to clear an unexpected cluster cache root")

node_ids: set[str] = set()
remote_targets: set[str] = set()
for deployment in deployments:
for rank, host in enumerate(deployment.hosts):
node_ids.add(host.node_id)
if rank > 0:
remote_targets.add(host.ssh)

# Resolve settings on the peer. Sending the coordinator's expanded
# /Users/<name>/... roots breaks as soon as the Macs use different login
# names, data roots, or SSD-cache locations.
script = r"""
import shutil
from pathlib import Path
from omlx.settings import GlobalSettings
settings = GlobalSettings.load()
roots = [
settings.cache.get_ssd_cache_dir(settings.base_path) / 'cluster-prompt-snapshots',
Path(settings.base_path) / 'cluster/runtime/prompt-cache-ssd',
]
allowed = {'cluster-prompt-snapshots', 'prompt-cache-ssd'}
if any(root.name not in allowed for root in roots):
raise SystemExit(3)
deleted = 0
for root in roots:
if not root.exists():
continue
deleted += sum(1 for item in root.rglob('*') if item.is_file())
shutil.rmtree(root)
print(deleted)
""".strip()
command = shlex.join(["python3", "-c", script])
deleted = 0
for target in sorted(remote_targets):
completed = _run_cluster_ssh(
target,
command,
timeout=45.0,
runner=runner,
)
if completed.returncode != 0:
detail = completed.stderr.strip() or completed.stdout.strip()
raise RuntimeError(
f"cold cluster SSD clear failed on {target}: {detail[:300]}"
)
try:
deleted += max(0, int(completed.stdout.strip() or "0"))
except ValueError as exc:
raise RuntimeError(
f"cold cluster SSD clear returned invalid output on {target}"
) from exc
return deleted, len(node_ids)


# =============================================================================
# Pydantic Models
# =============================================================================
Expand Down Expand Up @@ -5604,8 +5687,8 @@ async def clear_alltime_stats(is_admin: bool = Depends(require_admin)):
return {"status": "ok"}


def _iter_loaded_scheduler_records():
"""Yield (model_id, scheduler, core) for each loaded model.
def _iter_loaded_engine_records():
"""Yield (model_id, scheduler-or-None, core) for each loaded model.

Traverses the internal engine hierarchy: pool entry → async engine →
core engine → scheduler.
Expand All @@ -5620,9 +5703,26 @@ def _iter_loaded_scheduler_records():
entry = engine_pool._entries.get(model_id)
if entry is None or entry.engine is None:
continue
async_core = getattr(entry.engine, "_engine", None)
core = getattr(async_core, "engine", None) if async_core is not None else None
# DistributedBatchedEngine is stored directly in the pool; local
# batched engines retain the historical async-wrapper chain.
direct = entry.engine
async_core = getattr(direct, "_engine", None)
core = (
direct
if callable(getattr(direct, "clear_prompt_caches", None))
else getattr(async_core, "engine", None)
if async_core is not None
else None
)
scheduler = getattr(core, "scheduler", None) if core is not None else None
if core is not None:
yield model_id, scheduler, core


def _iter_loaded_scheduler_records():
"""Yield local scheduler records, excluding distributed proxy engines."""

for model_id, scheduler, core in _iter_loaded_engine_records():
if scheduler is not None:
yield model_id, scheduler, core

Expand All @@ -5645,8 +5745,24 @@ async def clear_ssd_cache(is_admin: bool = Depends(require_admin)):
is loaded.
"""
total_deleted = 0
distributed_ranks = 0
distributed_failures = []

for model_id, scheduler in _iter_loaded_schedulers():
for model_id, scheduler, core in _iter_loaded_engine_records():
distributed_clear = getattr(core, "clear_prompt_caches", None)
if callable(distributed_clear):
try:
report = await distributed_clear(ssd=True)
total_deleted += int(report.get("ssd_deleted", 0))
distributed_ranks += len(report.get("ranks", ()))
except Exception as exc:
logger.warning(
"Failed to clear distributed SSD cache for model '%s': %s",
model_id,
exc,
)
distributed_failures.append(f"{model_id}: {exc}")
continue
ssd_manager = getattr(scheduler, "paged_ssd_cache_manager", None)
if ssd_manager is not None:
try:
Expand Down Expand Up @@ -5679,7 +5795,50 @@ async def clear_ssd_cache(is_admin: bool = Depends(require_admin)):
except Exception as exc:
logger.warning("Failed to clean SSD cache directory: %s", exc)

return {"status": "ok", "total_deleted": total_deleted}
# When no distributed engine is resident, no rank-local maintenance
# endpoint exists. Clear the coordinator's cold cluster trees directly
# and ask every configured peer to resolve and clear its own paths.
if distributed_ranks == 0:
cluster_roots = (
cache_dir / "cluster-prompt-snapshots",
Path(global_settings.base_path)
/ "cluster/runtime/prompt-cache-ssd",
)
for cluster_root in cluster_roots:
if not cluster_root.exists():
continue
try:
total_deleted += sum(
1 for item in cluster_root.rglob("*") if item.is_file()
)
shutil.rmtree(cluster_root)
except Exception as exc:
logger.warning(
"Failed to clean distributed SSD cache directory %s: %s",
cluster_root,
exc,
)
try:
remote_deleted, configured_ranks = await asyncio.to_thread(
_clear_cold_remote_cluster_cache_roots,
cluster_roots,
)
total_deleted += remote_deleted
distributed_ranks = configured_ranks
except Exception as exc:
logger.warning("Failed to clean cold peer SSD cache: %s", exc)
distributed_failures.append(f"cold cluster peers: {exc}")

if distributed_failures:
raise HTTPException(
status_code=503,
detail="; ".join(distributed_failures)[:1000],
)
return {
"status": "ok",
"total_deleted": total_deleted,
"distributed_ranks": distributed_ranks,
}


@router.post("/api/hot-cache/clear")
Expand All @@ -5699,7 +5858,24 @@ async def clear_hot_cache(is_admin: bool = Depends(require_admin)):

footprint_before = get_phys_footprint()
total_cleared = 0
distributed_ranks = 0
distributed_failures = []
reclaim_targets = []
for model_id, scheduler, core in _iter_loaded_engine_records():
distributed_clear = getattr(core, "clear_prompt_caches", None)
if not callable(distributed_clear):
continue
try:
report = await distributed_clear(hot=True)
total_cleared += int(report.get("hot_cleared", 0))
distributed_ranks += len(report.get("ranks", ()))
except Exception as exc:
logger.warning(
"Failed to clear distributed hot cache for model '%s': %s",
model_id,
exc,
)
distributed_failures.append(f"{model_id}: {exc}")
for model_id, scheduler, core in _iter_loaded_scheduler_records():
ssd_manager = getattr(scheduler, "paged_ssd_cache_manager", None)
if ssd_manager is not None and hasattr(ssd_manager, "clear_hot_cache"):
Expand Down Expand Up @@ -5756,10 +5932,16 @@ async def clear_hot_cache(is_admin: bool = Depends(require_admin)):
await loop.run_in_executor(get_mlx_executor(), _sync_and_clear_cache)
bytes_reclaimed = max(0, footprint_before - get_phys_footprint())

if distributed_failures:
raise HTTPException(
status_code=503,
detail="; ".join(distributed_failures)[:1000],
)
return {
"status": "ok",
"total_cleared": total_cleared,
"bytes_reclaimed": bytes_reclaimed,
"distributed_ranks": distributed_ranks,
}


Expand Down
5 changes: 5 additions & 0 deletions omlx/api/openai_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,11 @@ class Usage(BaseUsage):
# Timing metrics (oMLX extension, seconds)
model_load_duration: Optional[float] = None
time_to_first_token: Optional[float] = None
# Chat streaming only, measured from stream_chat_completion entry (not HTTP
# endpoint arrival): first nonempty reasoning/content/structured-tool SSE
# delta after all output filters. This may be later than model TTFT for tool
# envelopes; Responses/Completions do not currently populate it.
time_to_first_visible_token: Optional[float] = None
total_time: Optional[float] = None
prompt_eval_duration: Optional[float] = None
generation_duration: Optional[float] = None
Expand Down
Loading