diff --git a/runtime/common/engine_adapter.py b/runtime/common/engine_adapter.py index 9cfa5345..83fbe110 100644 --- a/runtime/common/engine_adapter.py +++ b/runtime/common/engine_adapter.py @@ -22,12 +22,18 @@ from abc import ABC, abstractmethod from dataclasses import dataclass +import json from pathlib import PurePosixPath from typing import Any +import urllib.parse from runtime.common import libsircl, parallel_groups, stock_image, transport from runtime.common.container_spec import Bind, ContainerSpec +HEALTH_URL_ENV = "SPARKRING_HEALTH_URL" +DROP_CACHES_ENV = "SPARKRING_DROP_CACHES" +ENGINE_LABEL = "io.sparkring.engine" + @dataclass(frozen=True) class NcclInjectionPlan: @@ -59,6 +65,37 @@ class HealthVerdict: fatal: bool = False +@dataclass(frozen=True) +class HealthProbeSpec: + """How host recovery and status probe liveness/readiness for an engine deployment.""" + + engine: str + mode: str + endpoints: tuple[HealthEndpoint, ...] = () + health_url: str | None = None + fatal_status_codes: tuple[int, ...] = () + fatal_body_markers: tuple[str, ...] = () + bare_503_is_fatal: bool = False + silence_timeout_s: int = 300 + + +@dataclass(frozen=True) +class MemorySettleContract: + """How ``runtime.host.memory_settle`` evaluates pre-start unified memory for an engine.""" + + engine: str + display_name: str + drop_caches: bool = True + enforce_utilization: bool = True + utilization_flags: tuple[str, ...] = () + kv_cache_bytes_flags: tuple[str, ...] = () + supports_sparkcache: bool = False + requested_utilization: float | None = None + requested_kv_cache_bytes: int | None = None + pinned_bytes: int = 0 + skip_reason: str | None = None + + @dataclass(frozen=True) class ParallelValidation: """Result of validating a runtime's parallelism widths against ``parallel_groups``.""" @@ -78,11 +115,158 @@ def ok(self) -> bool: return not self.problems +def _flag_value(command: list[str] | tuple[str, ...] | None, *flags: str) -> str | None: + """Return the last value passed for any flag in ``flags`` (supporting ``--flag val`` and ``--flag=val``).""" + if not command: + return None + tokens = [str(token) for token in command] + found: str | None = None + for index, token in enumerate(tokens): + flag, equals, value = token.partition("=") + if flag in flags: + found = value if equals else (tokens[index + 1] if index + 1 < len(tokens) else None) + return found + + +def _float_flag(command: list[str] | tuple[str, ...] | None, *flags: str) -> float | None: + raw = _flag_value(command, *flags) + if not raw: + return None + try: + return float(raw) + except ValueError: + return None + + +def _int_flag(command: list[str] | tuple[str, ...] | None, *flags: str) -> int | None: + raw = _flag_value(command, *flags) + if not raw: + return None + try: + return int(raw) + except ValueError: + return None + + +def _vllm_pinned_bytes(command: list[str] | tuple[str, ...] | None) -> int: + """Pinned host memory, in bytes, allocated by a vLLM SparkCache connector beside vLLM's share.""" + raw = _flag_value(command, "--kv-transfer-config") + if not raw: + return 0 + try: + extra = json.loads(raw).get("kv_connector_extra_config") or {} + except (ValueError, AttributeError): + return 0 + total = 0 + if extra.get("spark_cache_async_page_capture"): + total += int(extra.get("spark_cache_async_page_capture_slot_bytes") or 0) * int( + extra.get("spark_cache_async_page_capture_slot_count") or 2 + ) + if extra.get("spark_cache_cuda_restore"): + budget = extra.get("spark_cache_cuda_restore_arena_budget_bytes") + total += int(budget) if budget else 2 * int(extra.get("spark_cache_cuda_placement_arena_bytes") or 0) + return total + + +def _base_url(api_url: str) -> str: + return api_url.removesuffix("/").removesuffix("/v1") + + +def _positive_int(value: Any) -> int | None: + if isinstance(value, bool) or value is None: + return None + try: + parsed = int(value) + except (TypeError, ValueError): + return None + return parsed if parsed > 0 else None + + +def _extract_parallelism( + deployment: dict[str, Any] | None, + status: dict[str, Any] | None, + *, + default_tp_from_count: bool = True, +) -> dict[str, Any]: + """Extract TP/PP/DP/EP/DCP widths from status/deployment metadata and compute a concise summary.""" + deployment = deployment or {} + status = status or {} + launch = deployment.get("launch") if isinstance(deployment.get("launch"), dict) else {} + settings = status.get("settings") if isinstance(status.get("settings"), dict) else {} + parallel = deployment.get("parallelism") if isinstance(deployment.get("parallelism"), dict) else {} + command = deployment.get("command") if isinstance(deployment.get("command"), (list, tuple)) else () + positions = deployment.get("positions") + ranks = (deployment.get("site") or {}).get("ranks") if isinstance(deployment.get("site"), dict) else None + count = ( + len(positions) + if isinstance(positions, (list, tuple)) and positions + else len(ranks) + if isinstance(ranks, (list, tuple)) and ranks + else None + ) + + def pick(key: str, *cmd_flags: str, setting_key: str | None = None) -> int | None: + for candidate in ( + status.get(key), + settings.get(setting_key) if setting_key else None, + parallel.get(key), + launch.get(key), + _int_flag(command, *cmd_flags) if cmd_flags else None, + ): + parsed = _positive_int(candidate) + if parsed is not None: + return parsed + return None + + tp = pick("tp", "--tensor-parallel-size", "-tp", "--tp-size", "--tp") + pp = pick("pp", "--pipeline-parallel-size", "-pp", "--pp-size") + dp = pick("dp", "--data-parallel-size", "-dp", "--dp-size") + ep = pick("ep", "--ep-size", "--expert-parallel-size", "--ep") + dcp = pick("dcp", "--decode-context-parallel-size", "-dcp", setting_key="decode_context_parallel_size") + + if ep is None and command and stock_image._has_flag(command, "--enable-expert-parallel", "-ep"): + ep = tp or count + if tp is None and default_tp_from_count and count is not None: + divisor = (pp or 1) * (dp or 1) + tp = count // divisor if divisor > 0 and count % divisor == 0 else count + + parts = [] + if tp is not None: + parts.append(f"TP{tp}") + if ep is not None and ep > 1: + parts.append(f"EP{ep}") + if dcp is not None and dcp > 1: + parts.append(f"DCP{dcp}") + if pp is not None and pp > 1: + parts.append(f"PP{pp}") + if dp is not None and dp > 1: + parts.append(f"DP{dp}") + if not parts: + if count is not None: + parts.append(f"{count} rank" if count == 1 else f"{count} ranks") + else: + parts.append("single") + return { + "tp": tp, + "pp": pp, + "dp": dp, + "ep": ep, + "dcp": dcp, + "world_size": count, + "summary": " / ".join(parts), + } + + class EngineAdapter(ABC): - """Protocol/ABC for engine-specific launch, NCCL injection, health, and parallelism checks.""" + """Protocol/ABC for engine-specific launch, NCCL injection, health, memory settle, and parallelism checks.""" name: str + display_name: str nccl_so_path_var: str | None = None + profile_args_key: str = "vllm_args" + api_kind: str = "openai" + supports_metrics: bool = True + supports_runtime_status: bool = False @abstractmethod def build_rank_command( @@ -132,9 +316,58 @@ def health_endpoints( """Return HTTP health/readiness endpoints for ``rank`` (empty for headless workers).""" @abstractmethod - def classify_health_response(self, status_code: int, body: str = "") -> HealthVerdict: + def health_probe_spec( + self, + *, + host: str = "127.0.0.1", + port: int | None = None, + rank: int = 0, + api_url: str | None = None, + health_url: str | None = None, + environment: dict[str, str] | None = None, + ) -> HealthProbeSpec: + """Describe how recovery/status probes this engine (HTTP endpoints vs process liveness).""" + + @abstractmethod + def classify_health_response( + self, + status_code: int, + body: str = "", + *, + assume_running: bool = False, + ) -> HealthVerdict: """Classify an HTTP health check response into healthy/starting/unhealthy/dead.""" + @abstractmethod + def memory_settle_contract( + self, + command: list[str] | tuple[str, ...] | None = None, + *, + environment: dict[str, str] | None = None, + ) -> MemorySettleContract: + """Describe how ``runtime.host.memory_settle`` validates pre-start unified memory for this engine.""" + + def dashboard_summary( + self, + deployment: dict[str, Any] | None = None, + status: dict[str, Any] | None = None, + ) -> dict[str, Any]: + """Engine display metadata (badge, API kind, metrics/status capability, TP/PP/EP summary).""" + parallelism = _extract_parallelism( + deployment, + status, + default_tp_from_count=self.name != "generic", + ) + return { + "engine": self.name, + "label": self.display_name, + "badge": self.display_name, + "api_kind": self.api_kind, + "supports_metrics": self.supports_metrics, + "supports_runtime_status": self.supports_runtime_status, + "parallelism": parallelism, + } + def nccl_injection_plan( self, image: dict[str, Any], @@ -272,6 +505,7 @@ def build_container_spec( "io.sparkring.stock-plan": name, "io.sparkring.rank": str(rank), "io.sparkring.status": libsircl.STATUS, + ENGINE_LABEL: self.name, }, ) @@ -280,8 +514,13 @@ class VllmAdapter(EngineAdapter): """Adapter for vLLM serving runtimes (``vllm serve``, ``VLLM_PLUGINS``, ``--headless``).""" name = "vllm" + display_name = "vLLM" nccl_so_path_var = "VLLM_NCCL_SO_PATH" profile_args_key = "vllm_args" + api_kind = "openai" + supports_metrics = True + supports_runtime_status = True + fatal_health_markers = ("EngineDeadError", "EngineCore encountered an issue") managed_flags = ( "--nnodes", "--node-rank", @@ -373,15 +612,57 @@ def health_endpoints( HealthEndpoint(path="/v1/models", url=f"http://{host}:{port}/v1/models", role="api"), ) - def classify_health_response(self, status_code: int, body: str = "") -> HealthVerdict: + def health_probe_spec( + self, + *, + host: str = "127.0.0.1", + port: int | None = stock_image.API_PORT, + rank: int = 0, + api_url: str | None = None, + health_url: str | None = None, + environment: dict[str, str] | None = None, + ) -> HealthProbeSpec: + if rank != 0: + return HealthProbeSpec(engine=self.name, mode="process", endpoints=()) + if api_url: + base = _base_url(api_url) + endpoints = ( + HealthEndpoint(path="/health", url=f"{base}/health", role="liveness"), + HealthEndpoint(path="/v1/models", url=f"{base}/v1/models", role="api"), + ) + else: + endpoints = self.health_endpoints(host=host, port=port, rank=rank) + return HealthProbeSpec( + engine=self.name, + mode="http" if endpoints else "process", + endpoints=endpoints, + health_url=endpoints[0].url if endpoints else None, + fatal_status_codes=(503,), + fatal_body_markers=self.fatal_health_markers, + bare_503_is_fatal=True, + ) + + def classify_health_response( + self, + status_code: int, + body: str = "", + *, + assume_running: bool = False, + ) -> HealthVerdict: if status_code == 200: return HealthVerdict(state="healthy", detail="vLLM /health returned 200 OK", fatal=False) - if status_code in (500, 503) and ("EngineDeadError" in body or "EngineCore encountered an issue" in body): + if status_code in (500, 503) and any(marker in body for marker in self.fatal_health_markers): return HealthVerdict( state="dead", detail=f"vLLM reported fatal EngineDeadError (HTTP {status_code})", fatal=True, ) + if status_code == 503 and assume_running and not body.strip(): + return HealthVerdict( + state="dead", + detail="HTTP 503 from /health: the model engine has stopped", + fatal=True, + ) if status_code == 503: return HealthVerdict( state="starting", @@ -390,6 +671,25 @@ def classify_health_response(self, status_code: int, body: str = "") -> HealthVe ) return HealthVerdict(state="unhealthy", detail=f"vLLM health returned HTTP {status_code}", fatal=False) + def memory_settle_contract( + self, + command: list[str] | tuple[str, ...] | None = None, + *, + environment: dict[str, str] | None = None, + ) -> MemorySettleContract: + return MemorySettleContract( + engine=self.name, + display_name=self.display_name, + drop_caches=True, + enforce_utilization=True, + utilization_flags=("--gpu-memory-utilization",), + kv_cache_bytes_flags=("--kv-cache-memory-bytes",), + supports_sparkcache=True, + requested_utilization=_float_flag(command, "--gpu-memory-utilization"), + requested_kv_cache_bytes=_int_flag(command, "--kv-cache-memory-bytes"), + pinned_bytes=_vllm_pinned_bytes(command), + ) + def validate_parallelism( self, arguments: list[str] | tuple[str, ...], @@ -457,7 +757,19 @@ class SglangAdapter(EngineAdapter): """First-class adapter for SGLang (``python3 -m sglang.launch_server``, shadow mounts, ``parallel_groups``).""" name = "sglang" + display_name = "SGLang" nccl_so_path_var = "SGLANG_NCCL_SO_PATH" + profile_args_key = "sglang_args" + api_kind = "openai" + supports_metrics = True + supports_runtime_status = False + fatal_health_markers = ( + "SchedulerDead", + "EngineDead", + "TokenizerManager is dead", + "ProcessExitedException", + "worker died", + ) def build_rank_command( self, @@ -535,17 +847,58 @@ def health_endpoints( HealthEndpoint(path="/v1/models", url=f"http://{host}:{port}/v1/models", role="api"), ) - def classify_health_response(self, status_code: int, body: str = "") -> HealthVerdict: + def health_probe_spec( + self, + *, + host: str = "127.0.0.1", + port: int | None = stock_image.API_PORT, + rank: int = 0, + api_url: str | None = None, + health_url: str | None = None, + environment: dict[str, str] | None = None, + ) -> HealthProbeSpec: + if rank != 0: + return HealthProbeSpec(engine=self.name, mode="process", endpoints=()) + if api_url: + base = _base_url(api_url) + endpoints = ( + HealthEndpoint(path="/health", url=f"{base}/health", role="liveness"), + HealthEndpoint(path="/health_generate", url=f"{base}/health_generate", role="readiness"), + HealthEndpoint(path="/v1/models", url=f"{base}/v1/models", role="api"), + ) + else: + endpoints = self.health_endpoints(host=host, port=port, rank=rank) + return HealthProbeSpec( + engine=self.name, + mode="http" if endpoints else "process", + endpoints=endpoints, + health_url=endpoints[0].url if endpoints else None, + fatal_status_codes=(503,), + fatal_body_markers=self.fatal_health_markers, + bare_503_is_fatal=True, + ) + + def classify_health_response( + self, + status_code: int, + body: str = "", + *, + assume_running: bool = False, + ) -> HealthVerdict: if status_code == 200: return HealthVerdict(state="healthy", detail="SGLang server returned 200 OK", fatal=False) - if status_code in (500, 503) and any( - marker in body for marker in ("SchedulerDead", "EngineDead", "TokenizerManager is dead") - ): + if status_code in (500, 503) and any(marker in body for marker in self.fatal_health_markers): return HealthVerdict( state="dead", detail=f"SGLang reported fatal runtime crash (HTTP {status_code})", fatal=True, ) + if status_code == 503 and assume_running and not body.strip(): + return HealthVerdict( + state="dead", + detail="HTTP 503 from /health: SGLang server has stopped", + fatal=True, + ) if status_code == 503: return HealthVerdict( state="starting", @@ -554,6 +907,25 @@ def classify_health_response(self, status_code: int, body: str = "") -> HealthVe ) return HealthVerdict(state="unhealthy", detail=f"SGLang health returned HTTP {status_code}", fatal=False) + def memory_settle_contract( + self, + command: list[str] | tuple[str, ...] | None = None, + *, + environment: dict[str, str] | None = None, + ) -> MemorySettleContract: + return MemorySettleContract( + engine=self.name, + display_name=self.display_name, + drop_caches=True, + enforce_utilization=True, + utilization_flags=("--mem-fraction-static",), + kv_cache_bytes_flags=(), + supports_sparkcache=False, + requested_utilization=_float_flag(command, "--mem-fraction-static"), + requested_kv_cache_bytes=None, + pinned_bytes=0, + ) + def validate_parallelism( self, arguments: list[str] | tuple[str, ...], @@ -601,7 +973,12 @@ class GenericContainerAdapter(EngineAdapter): """ name = "generic" + display_name = "Generic" nccl_so_path_var = None + profile_args_key = "container_args" + api_kind = "process" + supports_metrics = False + supports_runtime_status = False def build_rank_command( self, @@ -654,18 +1031,96 @@ def health_endpoints( host: str = "127.0.0.1", port: int | None = None, rank: int = 0, + health_url: str | None = None, ) -> tuple[HealthEndpoint, ...]: - if rank != 0 or port is None: + if rank != 0: + return () + if health_url: + parsed = urllib.parse.urlsplit(health_url) + path = parsed.path or "/health" + return (HealthEndpoint(path=path, url=health_url, role="liveness"),) + if port is None: return () return (HealthEndpoint(path="/health", url=f"http://{host}:{port}/health", role="liveness"),) - def classify_health_response(self, status_code: int, body: str = "") -> HealthVerdict: + def health_probe_spec( + self, + *, + host: str = "127.0.0.1", + port: int | None = None, + rank: int = 0, + api_url: str | None = None, + health_url: str | None = None, + environment: dict[str, str] | None = None, + ) -> HealthProbeSpec: + if rank != 0: + return HealthProbeSpec(engine=self.name, mode="process", endpoints=()) + resolved_url = health_url or (environment or {}).get(HEALTH_URL_ENV) or None + if resolved_url: + endpoints = self.health_endpoints(rank=rank, health_url=resolved_url) + elif port is not None: + endpoints = self.health_endpoints(host=host, port=port, rank=rank) + elif api_url: + base = _base_url(api_url) + endpoints = (HealthEndpoint(path="/health", url=f"{base}/health", role="liveness"),) + else: + endpoints = () + return HealthProbeSpec( + engine=self.name, + mode="http" if endpoints else "process", + endpoints=endpoints, + health_url=endpoints[0].url if endpoints else None, + fatal_status_codes=(), + fatal_body_markers=(), + bare_503_is_fatal=False, + ) + + def classify_health_response( + self, + status_code: int, + body: str = "", + *, + assume_running: bool = False, + ) -> HealthVerdict: if 200 <= status_code < 300: return HealthVerdict(state="healthy", detail=f"endpoint returned HTTP {status_code}", fatal=False) if status_code == 503: return HealthVerdict(state="starting", detail="endpoint returned 503", fatal=False) return HealthVerdict(state="unhealthy", detail=f"endpoint returned HTTP {status_code}", fatal=False) + def memory_settle_contract( + self, + command: list[str] | tuple[str, ...] | None = None, + *, + environment: dict[str, str] | None = None, + ) -> MemorySettleContract: + env = environment or {} + drop = str(env.get(DROP_CACHES_ENV, "")).strip().lower() in ("1", "true", "yes") + return MemorySettleContract( + engine=self.name, + display_name="generic container", + drop_caches=drop, + enforce_utilization=False, + utilization_flags=(), + kv_cache_bytes_flags=(), + supports_sparkcache=False, + requested_utilization=None, + requested_kv_cache_bytes=None, + pinned_bytes=0, + skip_reason=None if drop else "generic container uses process liveness without managed KV-cache utilization", + ) + + def dashboard_summary( + self, + deployment: dict[str, Any] | None = None, + status: dict[str, Any] | None = None, + ) -> dict[str, Any]: + summary = super().dashboard_summary(deployment, status) + dep = deployment or {} + has_http = bool(dep.get("health_url") or (dep.get("api_host") and dep.get("api_port"))) + summary["api_kind"] = "http" if has_http else "process" + return summary + def validate_parallelism( self, arguments: list[str] | tuple[str, ...], @@ -723,3 +1178,120 @@ def adapter_for_facts(facts: dict[str, Any] | None) -> EngineAdapter: if detected == "both": raise stock_image.StockImageError("the image has both vllm and sglang packages; select one serving runtime") return get_engine_adapter(detected or "generic") + + +def _engine_from_command(command: list[str] | tuple[str, ...]) -> str | None: + """Infer an engine name from a container command argv, or None when ambiguous/empty.""" + tokens = [str(item) for item in command if item is not None] + if not tokens: + return None + joined = " ".join(tokens).lower() + if any( + marker in joined + for marker in ("sglang", "--mem-fraction-static", "--dist-init-addr", "--tp-size", "--ep-size") + ): + return "sglang" + first_name = PurePosixPath(tokens[0]).name.lower() + if ( + first_name in ("vllm", "serve") + or any( + PurePosixPath(tok).name.lower() == "vllm" + or tok.startswith(("--gpu-memory-utilization", "--kv-cache-memory-bytes", "--kv-transfer-config", "--headless")) + for tok in tokens + ) + ): + return "vllm" + return "generic" + + +def _engine_from_env(environment: dict[str, Any]) -> str | None: + keys = {str(k) for k in environment} + if "SGLANG_NCCL_SO_PATH" in keys or any(k.startswith("SGLANG_") for k in keys): + return "sglang" + if any(k in keys for k in ("VLLM_NCCL_SO_PATH", "VLLM_HOST_IP", "VLLM_PLUGINS")): + return "vllm" + if HEALTH_URL_ENV in keys or ({"RANK", "WORLD_SIZE"} <= keys): + return "generic" + return None + + +def _normalize_engine_name(value: Any) -> str | None: + if not isinstance(value, str): + return None + low = value.strip().lower() + if low in ADAPTERS: + return low + if low in ("unknown", "gpu-job", "custom", "torch", "pytorch", "exllamav3"): + return "generic" + return None + + +def detect_engine(deployment_or_facts: Any = None) -> EngineAdapter: + """Resolve the ``EngineAdapter`` for a deployment lock, site row, stock plan, probe facts, or command. + + Resolution order: + 1. An existing ``EngineAdapter`` instance. + 2. An explicit engine name string (``vllm``, ``sglang``, ``generic``; ``unknown`` maps to ``generic``). + 3. Explicit metadata fields on a dict: ``engine``, ``framework``, ``labels["io.sparkring.engine"]``, + ``selection["engine"]``, ``stock["engine"]``, or ``launch["engine"]``. + 4. Stock-image probe facts (``vllm`` / ``sglang`` / ``torch`` / ``library`` keys). + 5. Container command tokens (``command`` / ``argv``, or a bare list/tuple of tokens). + 6. Container environment hints (``SGLANG_*``, ``VLLM_*``, ``SPARKRING_HEALTH_URL``). + 7. Default ``VllmAdapter`` for legacy deployments that carry no engine metadata. + """ + if isinstance(deployment_or_facts, EngineAdapter): + return deployment_or_facts + if deployment_or_facts is None: + return ADAPTERS["vllm"] + if isinstance(deployment_or_facts, str): + normalized = _normalize_engine_name(deployment_or_facts) + if normalized is not None: + return ADAPTERS[normalized] + inferred = _engine_from_command(deployment_or_facts.split()) + return ADAPTERS[inferred or "vllm"] + if isinstance(deployment_or_facts, (list, tuple)): + inferred = _engine_from_command(deployment_or_facts) + return ADAPTERS[inferred or "vllm"] + if not isinstance(deployment_or_facts, dict): + return ADAPTERS["vllm"] + + # 1. Explicit engine/framework fields (most authoritative) + candidates = [ + deployment_or_facts.get("engine"), + deployment_or_facts.get("framework"), + ] + for nested_key in ("stock", "selection", "launch"): + nested = deployment_or_facts.get(nested_key) + if isinstance(nested, dict): + candidates.append(nested.get("engine")) + candidates.append(nested.get("framework")) + labels = deployment_or_facts.get("labels") + if isinstance(labels, dict): + candidates.append(labels.get(ENGINE_LABEL)) + for raw in candidates: + normalized = _normalize_engine_name(raw) + if normalized is not None: + return ADAPTERS[normalized] + + # 2. Probe facts record (from stock_image_probe) + if any(key in deployment_or_facts for key in ("vllm", "sglang", "torch", "library")): + return adapter_for_facts(deployment_or_facts) + + # 3. Container command tokens + for cmd_key in ("command", "argv"): + cmd = deployment_or_facts.get(cmd_key) + if isinstance(cmd, (list, tuple)) and cmd: + inferred = _engine_from_command(cmd) + if inferred is not None: + return ADAPTERS[inferred] + + # 4. Container environment hints + for env_key in ("environment", "env"): + env = deployment_or_facts.get(env_key) + if isinstance(env, dict) and env: + inferred = _engine_from_env(env) + if inferred is not None: + return ADAPTERS[inferred] + + # 5. Legacy deployment records without engine metadata default to vLLM + return ADAPTERS["vllm"] diff --git a/runtime/common/installer.py b/runtime/common/installer.py index 0c51e2ec..2eaaf73a 100644 --- a/runtime/common/installer.py +++ b/runtime/common/installer.py @@ -13,8 +13,8 @@ import uuid import zipfile -from runtime.common import (atomic_io, compose, derived_checkpoint, distribution, fabric_layout, installer_image, - process_lock, profiles, serving, setup, tp2) +from runtime.common import (atomic_io, compose, derived_checkpoint, distribution, engine_adapter, fabric_layout, + installer_image, process_lock, profiles, serving, setup, stock_image, tp2) from scripts import deploy_engine ROOT = profiles.ROOT @@ -325,14 +325,25 @@ def backend(card): return "glm-managed" if card["profile"] in (GLM_LEGACY[4], GLM_NO_CACHE[4]) else "compose" +def adapter_of(lock): + """Resolve the ``EngineAdapter`` that owns ``lock`` (defaulting to ``VllmAdapter`` for legacy locks).""" + return engine_adapter.detect_engine(lock) + + +def engine_of(lock): + """Canonical engine name (``vllm``, ``sglang``, ``generic``) of deployment lock ``lock``.""" + return adapter_of(lock).name + + def make_lock(profile, raw_site, revision, bundle_sha256, variant=None, *, image_runtime=None, settings=None, - transport=None): + transport=None, engine=None): """The deployment lock of one request. ``transport`` is the ``transport`` section of a deployment on SIRCL ring sessions (``runtime/common/transport.py``, ``section``); a lock without one runs on the prepared transport of its image, as every lock made - before the section existed does. + before the section existed does. ``engine`` optionally pins the + ``EngineAdapter`` name (``vllm``, ``sglang``, ``generic``). """ if profile not in SUPPORTED: raise ValueError(f"The installer does not deploy {profile}; 'sparkring models' marks the profiles it installs, " @@ -353,6 +364,8 @@ def make_lock(profile, raw_site, revision, bundle_sha256, variant=None, *, image value = {"schema": "sparkring-install-lock/v1", "selection": card, "site": site, "site_input": raw_site, "source_revision": revision, "bundle_sha256": bundle_sha256, "backend": selected_backend} + if engine is not None: + value["engine"] = engine_adapter.get_engine_adapter(engine).name if image_runtime is not None: value["image_runtime"] = image_runtime if settings: @@ -377,10 +390,109 @@ def make_lock(profile, raw_site, revision, bundle_sha256, variant=None, *, image return value +def make_stock_lock( + name, + image, + facts, + arguments, + *, + engine, + reference, + rows, + routes, + host_library, + version, + directory, + model_path=None, + positions=None, + ring_only=False, + health_url=None, + gid_index=None, + extra_env=None, +): + """Build a stock-image deployment lock backed by an explicit ``EngineAdapter``. + + Supports ``vllm``, ``sglang``, and ``generic`` (ExLlamaV3, PyTorch DDP/FSDP, + custom NCCL containers) so ``specifications()``, ``rendered()``, + ``connection()``, ``memory_settle``, ``recovery``, and ``dashboard`` can + handle them uniformly without assuming vLLM. + """ + adapter = engine_adapter.get_engine_adapter(engine) + if not rows or len(rows) != len(routes): + raise ValueError("Stock lock requires one site row and one route map per rank") + ranks = [] + for rank, row in enumerate(rows): + entry = { + "rank": rank, + "host": row["host"], + "management_ip": row.get("management_ip") or row["fabric_ip"], + "host_ip": row["fabric_ip"], + "fabric_ip": row["fabric_ip"], + "interface": row["interface"], + } + if row.get("gid_index") is not None: + entry["gid_index"] = row["gid_index"] + elif row.get("gid") is not None: + entry["gid"] = row["gid"] + if model_path is not None: + entry["model"] = model_path + ranks.append(entry) + stock_payload = { + "engine": adapter.name, + "image": image, + "facts": facts, + "arguments": list(arguments), + "reference": reference, + "routes": list(routes), + "host_library": host_library, + "version": version, + "directory": directory, + "model_path": model_path, + "positions": list(positions) if positions is not None else list(range(len(rows))), + "ring_only": bool(ring_only), + } + if gid_index is not None: + stock_payload["gid_index"] = gid_index + if extra_env: + stock_payload["extra_env"] = dict(extra_env) + if health_url: + stock_payload["health_url"] = health_url + value = { + "schema": "sparkring-stock-lock/v1", + "backend": "compose", + "engine": adapter.name, + "selection": { + "profile": f"stock-{adapter.name}", + "target_variant": None, + "nodes": len(rows), + "image_id": image.get("Id") or reference, + "image_reference": reference, + "release": f"stock-{adapter.name}", + "model_repository": None, + "model_revision": None, + }, + "site": { + "name": name, + "ranks": ranks, + "placement": stock_payload["positions"], + }, + "stock": stock_payload, + } + if health_url: + value["health_url"] = health_url + value["id"] = compose.digest(compose.encoded(value)) + return value + + def validate(lock): + if lock.get("schema") == "sparkring-stock-lock/v1" and "stock" in lock: + candidate = {k: v for k, v in lock.items() if k != "id"} + if compose.digest(compose.encoded(candidate)) != lock.get("id"): + raise ValueError("Stock deployment lock changed; regenerate the deployment plan") + return lock expected = make_lock(lock["selection"]["profile"], lock["site_input"], lock["source_revision"], lock["bundle_sha256"], lock["selection"]["target_variant"], image_runtime=lock.get("image_runtime"), - settings=lock.get("serving"), transport=lock.get("transport")) + settings=lock.get("serving"), transport=lock.get("transport"), engine=lock.get("engine")) if expected != lock: raise ValueError("Deployment lock or its profile/release inputs changed; initialize a new deployment") return lock @@ -389,8 +501,9 @@ def validate(lock): def load(directory): directory = Path(directory).resolve() lock = validate(read(directory / "deployment.lock.json")) - if hashlib.sha256((directory / "source.bundle").read_bytes()).hexdigest() != lock["bundle_sha256"]: - raise ValueError("Source bundle differs from the deployment lock") + if lock.get("schema") != "sparkring-stock-lock/v1": + if hashlib.sha256((directory / "source.bundle").read_bytes()).hexdigest() != lock["bundle_sha256"]: + raise ValueError("Source bundle differs from the deployment lock") return lock @@ -455,6 +568,46 @@ def specifications(lock, *, receipt=None, local=False, only_rank=None): card, site = lock["selection"], lock["site"] if lock["backend"] != "compose": raise ValueError("Managed GLM Compose files are produced by its existing staging lifecycle") + if "stock" in lock: + stock = lock["stock"] + adapter = adapter_of(lock) + rows = site["ranks"] + master = rows[0].get("fabric_ip") or rows[0]["host_ip"] + extra_env = dict(stock.get("extra_env") or {}) + health_url = lock.get("health_url") or stock.get("health_url") + if health_url and engine_adapter.HEALTH_URL_ENV not in extra_env: + extra_env[engine_adapter.HEALTH_URL_ENV] = health_url + target_ranks = [only_rank] if only_rank is not None else list(range(len(rows))) + specs = [] + for rank in target_ranks: + row = rows[rank] + spec = stock_image.rank_spec( + stock["image"], + stock.get("facts"), + stock.get("arguments") or (), + name=site["name"], + reference=stock.get("reference") or card["image_id"], + rank=rank, + row=row, + master=master, + size=len(rows), + routes=stock["routes"][rank], + host_library=stock["host_library"], + version=stock["version"], + model_path=stock.get("model_path"), + directory=stock["directory"], + gid_index=stock.get("gid_index"), + positions=stock.get("positions"), + ring_only=bool(stock.get("ring_only", False)), + engine=adapter.name, + extra_env=extra_env or None, + ) + specs.append(replace( + spec, + name=container_name(lock, rank), + labels={**spec.labels, **container_labels(lock, rank)}, + )) + return specs from runtime.common import installer_image as image_locks rendered_by_compose = (card["profile"] in compose.SUPPORTED or card["profile"] in compose.FABRIC_PROFILES or card["profile"] in image_locks.NOT_SHARED) @@ -503,8 +656,12 @@ def container_name(lock, rank): def container_labels(lock, rank): - """Labels on a Compose deployment's containers: its lock ID and the rank.""" - return {compose.LABEL: lock["id"], "io.sparkring.rank": str(rank)} + """Labels on a Compose deployment's containers: its lock ID, rank, and (when non-default) engine adapter.""" + labels = {compose.LABEL: lock["id"], "io.sparkring.rank": str(rank)} + engine = engine_of(lock) + if "engine" in lock or engine != "vllm": + labels[engine_adapter.ENGINE_LABEL] = engine + return labels def containers(lock): @@ -522,8 +679,41 @@ def rendered(lock): return files +def _command_connection(args, lock, *, environment=None): + """Extract ``(port, model, api_url, health_url)`` from rank-0 command & environment via ``EngineAdapter``.""" + adapter = adapter_of(lock) + raw_port = engine_adapter._flag_value(args, "--port") + port = int(raw_port) if raw_port is not None else None + model = ( + engine_adapter._flag_value(args, "--served-model-name") + or (engine_adapter._flag_value(args, "--model-path") if adapter.name == "sglang" else None) + or (lock.get("selection") or {}).get("profile") + or lock["site"]["name"] + ) + site = lock["site"] + host_ip = ((lock.get("serving") or {}).get("api_bind") or site.get("api_address") + or site["ranks"][0].get("management_ip") or site["ranks"][0].get("host_ip")) + health_url = ( + lock.get("health_url") + or (lock.get("stock") or {}).get("health_url") + or (environment or {}).get(engine_adapter.HEALTH_URL_ENV) + ) + if adapter.name == "generic": + api_url = health_url or (f"http://{host_ip}:{port}" if port is not None and host_ip else None) + else: + if port is None: + port = stock_image.API_PORT + api_url = f"http://{host_ip}:{port}/v1" + result = {"api_url": api_url, "model": model, "port": port} + if "engine" in lock or adapter.name != "vllm": + result["engine"] = adapter.name + if health_url: + result["health_url"] = health_url + return result + + def connection(lock): - """The API of the deployment: ``api_url``, the served ``model`` and the ``port``. + """The API of the deployment: ``api_url``, the served ``model``, ``port``, and ``engine``. The API answers on the API rank at the deployment's port (serving setting ``api_port``, else the profile's). Its address is the listen address @@ -531,18 +721,22 @@ def connection(lock): LAN address, or Spark 2's for a half on Sparks 2 and 3), else the API rank's management address. SparkRing's own checks use this URL; an address named for display (runtime.host.api_endpoint) never replaces it here. + For generic containers without an HTTP port, ``api_url`` is the optional + ``health_url`` (``SPARKRING_HEALTH_URL``) or None. """ if lock["backend"] in ("glm-managed", "glm-existing-mesh"): from runtime.common import glm_tp4 port = int(glm_tp4.DEFAULTS["PORT"]) model = "GLM-5.3-Flash-NVFP4-" + ("QAD" if lock["selection"]["target_variant"] == "nvfp4-qad" else "Spark") + "-TP4" - else: - args = specifications(lock, only_rank=0)[0].command - port = int(args[args.index("--port") + 1]) - model = args[args.index("--served-model-name") + 1] - host_ip = ((lock.get("serving") or {}).get("api_bind") - or lock["site"].get("api_address", lock["site"]["ranks"][0]["management_ip"])) - return {"api_url": f"http://{host_ip}:{port}/v1", "model": model, "port": port} + host_ip = ((lock.get("serving") or {}).get("api_bind") + or lock["site"].get("api_address", lock["site"]["ranks"][0]["management_ip"])) + result = {"api_url": f"http://{host_ip}:{port}/v1", "model": model, "port": port} + engine = engine_of(lock) + if "engine" in lock or engine != "vllm": + result["engine"] = engine + return result + spec = specifications(lock, only_rank=0)[0] + return _command_connection(spec.command, lock, environment=spec.environment) def recorded_connection(directory, lock): @@ -553,15 +747,11 @@ def recorded_connection(directory, lock): package no longer lists (after a package change, or a record of a research entry). The deployment directory keeps the command that ran in ``rank0/container.json`` (``rendered``), whose ``--port`` and - ``--served-model-name`` are what a reader of the record needs. + ``--served-model-name`` (or SGLang/generic metadata) are what a reader of + the record needs. """ - args = read(Path(directory) / "rank0" / "container.json")["command"] - port = int(args[args.index("--port") + 1]) - model = args[args.index("--served-model-name") + 1] - site = lock["site"] - host_ip = ((lock.get("serving") or {}).get("api_bind") or site.get("api_address") - or site["ranks"][0]["management_ip"]) - return {"api_url": f"http://{host_ip}:{port}/v1", "model": model, "port": port} + record = read(Path(directory) / "rank0" / "container.json") + return _command_connection(record.get("command") or (), lock, environment=record.get("environment")) def operation_plan(lock, action): @@ -768,8 +958,8 @@ def status(directory): directory = Path(directory) lock = load(directory) state = read(directory / "state.json") if (directory / "state.json").exists() else {"operation": "not started", "complete": False} - result = {"profile": lock["selection"]["profile"], "state": state, - "deployment_id": lock["id"], "source_revision": lock["source_revision"], + result = {"profile": lock["selection"]["profile"], "engine": engine_of(lock), "state": state, + "deployment_id": lock["id"], "source_revision": lock.get("source_revision"), "image_id": lock["selection"]["image_id"], "image_reference": lock["selection"]["image_reference"], "live_observed": False, "hosts": [r["host"] for r in lock["site"]["ranks"]], **identity(lock), **connection(lock)} diff --git a/runtime/common/stock_image.py b/runtime/common/stock_image.py index c3851210..793e73a2 100644 --- a/runtime/common/stock_image.py +++ b/runtime/common/stock_image.py @@ -141,8 +141,11 @@ def framework(facts): return None -def nccl_so_path_variable(facts=None): - """The environment variable the detected runtime's PyNccl reads for its NCCL library path.""" +def nccl_so_path_variable(facts=None, *, engine=None): + """The environment variable the detected runtime's PyNccl reads for its NCCL library path, or None for generic.""" + if engine is not None: + from runtime.common import engine_adapter + return engine_adapter.get_engine_adapter(engine).nccl_so_path_var return "SGLANG_NCCL_SO_PATH" if framework(facts) == "sglang" else "VLLM_NCCL_SO_PATH" @@ -532,11 +535,35 @@ def _check_sglang(image, facts, arguments, library, manifest, *, size=None, posi return problems -def preflight(image, facts, arguments, *, packs=None, manifest=None, size=None, positions=None, ring_only=False): +def _check_generic(image, facts, arguments, *, size=None, positions=None, ring_only=False): + from runtime.common import engine_adapter + problems = [] + owned = libsircl.owned_settings(image_environment(image)) + if owned: + problems.append(f"the image sets {owned}, which the libsircl transport owns") + if size is not None: + validation = engine_adapter.get_engine_adapter("generic").validate_parallelism( + arguments, size=size, positions=positions, ring_only=ring_only, + ) + problems.extend(validation.problems) + return problems + + +def preflight(image, facts, arguments, *, packs=None, manifest=None, size=None, positions=None, ring_only=False, + engine=None): """What stops ``image`` with ``facts`` (``stock_image_probe.probe``) from running ``arguments`` on libsircl; - empty when nothing does.""" + empty when nothing does. + + When ``engine`` is omitted, ``framework(facts)`` selects ``vllm`` or ``sglang`` and refuses images with neither + or both. Passing ``engine="generic"`` validates arbitrary PyTorch/ExLlamaV3/NCCL containers (no vLLM/SGLang + package required); passing ``engine="vllm"`` or ``engine="sglang"`` selects that runtime explicitly. + """ packs = architectures() if packs is None else packs manifest = api_manifest() if manifest is None else manifest + selected_engine = None + if engine is not None: + from runtime.common import engine_adapter + selected_engine = engine_adapter.get_engine_adapter(engine).name problems = [] if image.get("Architecture") != "arm64" or facts.get("machine") != "aarch64": problems.append(f"the image is {image.get('Architecture')}/{facts.get('machine')}, not arm64/aarch64") @@ -570,50 +597,74 @@ def preflight(image, facts, arguments, *, packs=None, manifest=None, size=None, problems.append(f"a GPU of compute capability {capability} runs none of the kernel packs' " f"architectures ({', '.join(packs)})") torch = facts.get("torch") + if selected_engine == "generic": + # Generic containers may link libnccl.so.2 directly (C++/ExLlamaV3) or via dynamic PyTorch. + if torch and torch.get("nccl") not in ("dynamic", "absent", None): + problems.append(f"the image's torch NCCL is {torch.get('nccl')}: only a torch whose " + "libtorch_cuda.so needs libnccl.so.2 can be pointed at libsircl, and torch's own " + "collectives would otherwise reach another NCCL") + problems += _check_generic(image, facts, arguments, size=size, positions=positions, ring_only=ring_only) + return problems if not torch or torch.get("nccl") != "dynamic": problems.append(f"the image's torch NCCL is {(torch or {}).get('nccl', 'missing')}: only a torch whose " "libtorch_cuda.so needs libnccl.so.2 can be pointed at libsircl, and torch's own collectives " "would otherwise reach another NCCL") - runtime = framework(facts) + runtime = selected_engine if selected_engine is not None else framework(facts) if runtime is None: problems.append("the image has no vllm or sglang package") elif runtime == "both": problems.append("the image has both vllm and sglang packages; stock-image plans require one serving runtime") elif runtime == "sglang": - problems += _check_sglang(image, facts, arguments, library, manifest, size=size, positions=positions, - ring_only=ring_only) + if not (facts or {}).get("sglang"): + problems.append("the image has no sglang package") + else: + problems += _check_sglang(image, facts, arguments, library, manifest, size=size, positions=positions, + ring_only=ring_only) else: - problems += _check_vllm(image, facts, arguments, library, manifest, size=size, positions=positions, - ring_only=ring_only) + if not (facts or {}).get("vllm"): + problems.append("the image has no vllm package") + else: + problems += _check_vllm(image, facts, arguments, library, manifest, size=size, positions=positions, + ring_only=ring_only) return problems -def binding_environment(image, version, facts=None): - return {nccl_so_path_variable(facts): library_target(version), "LD_PRELOAD": preloads(image, version), - "LIBSIRCL_NCCL_API_VERSION": str(libsircl.NCCL_API_VERSION)} +def binding_environment(image, version, facts=None, *, engine=None): + env = {"LD_PRELOAD": preloads(image, version), "LIBSIRCL_NCCL_API_VERSION": str(libsircl.NCCL_API_VERSION)} + variable = nccl_so_path_variable(facts, engine=engine) + if variable: + env[variable] = library_target(version) + return env -def binding_problems(found, version, facts=None): +def binding_problems(found, version, facts=None, *, engine=None): """What the binding probe (``stock_image_probe.binding``) found bound to another library than libsircl.""" target = library_target(version) - variable = (nccl_so_path_variable(facts) if facts is not None - else ("SGLANG_NCCL_SO_PATH" if found.get("sglang_nccl_so_path") else "VLLM_NCCL_SO_PATH")) + if engine is not None: + from runtime.common import engine_adapter + selected = engine_adapter.get_engine_adapter(engine) + variable = selected.nccl_so_path_var + else: + variable = (nccl_so_path_variable(facts) if facts is not None + else ("SGLANG_NCCL_SO_PATH" if found.get("sglang_nccl_so_path") else "VLLM_NCCL_SO_PATH")) problems = [] - if found.get("pynccl_provider") != target: + if variable and found.get("pynccl_provider") != target: problems.append(f"PyNccl's load of {variable} resolves ncclGetVersion in " f"{found.get('pynccl_provider') or found.get('pynccl_error')}, not {target}") if found.get("global_provider") != target: problems.append(f"the process's global scope resolves ncclGetVersion in {found.get('global_provider')}, " f"not {target}") - if found.get("torch_error"): - problems.append(f"importing torch with libsircl failed: {found['torch_error']}") - else: - if found.get("torch_provider") != target: - problems.append(f"torch's libtorch_cuda.so resolves ncclGetVersion in {found.get('torch_provider')}, " - f"not {target}") - if found.get("torch_runtime_nccl_version") != libsircl.NCCL_API_VERSION: - problems.append(f"torch's runtime ncclGetVersion reports {found.get('torch_runtime_nccl_version')}, " - f"not libsircl's {libsircl.NCCL_API_VERSION}") + has_torch = (facts or {}).get("torch") is not None if (facts is not None and engine == "generic") else True + if has_torch: + if found.get("torch_error"): + problems.append(f"importing torch with libsircl failed: {found['torch_error']}") + else: + if found.get("torch_provider") != target: + problems.append(f"torch's libtorch_cuda.so resolves ncclGetVersion in {found.get('torch_provider')}, " + f"not {target}") + if found.get("torch_runtime_nccl_version") != libsircl.NCCL_API_VERSION: + problems.append(f"torch's runtime ncclGetVersion reports {found.get('torch_runtime_nccl_version')}, " + f"not libsircl's {libsircl.NCCL_API_VERSION}") if found.get("mapped") != [target]: problems.append(f"the files mapped with the SONAME libnccl.so.2 are {found.get('mapped')}, not libsircl alone") return problems @@ -651,9 +702,9 @@ def compilation_arguments(arguments, facts): separators=(",", ":"))] -def rank_command(image, facts, arguments, *, rank, size, master, positions=None, ring_only=False): +def rank_command(image, facts, arguments, *, rank, size, master, positions=None, ring_only=False, engine=None): from runtime.common import engine_adapter - runtime = framework(facts) or "vllm" + runtime = engine if engine is not None else (framework(facts) or "vllm") return engine_adapter.get_engine_adapter(runtime).build_rank_command( image, facts, arguments, rank=rank, size=size, master=master, positions=positions, ring_only=ring_only, @@ -668,21 +719,24 @@ def loader_policy_needed(facts, arguments): def rank_spec(image, facts, arguments, *, name, reference, rank, row, master, size, routes, host_library, version, - model_path, directory, gid=None, gid_index=None, positions=None, ring_only=False): + model_path, directory, gid=None, gid_index=None, positions=None, ring_only=False, engine=None, + extra_env=None): """Rank ``rank``'s container: the image's own entrypoint with libsircl as its NCCL. ``row`` is the rank's site row (``host``, ``fabric_ip``, ``interface``, and optional ``gid`` / ``gid_index``); ``directory`` is the plan's directory on every Spark, which holds the receipts and, when the loader - needs it, the seccomp policy. + needs it, the seccomp policy. ``engine`` selects the ``EngineAdapter`` + (``vllm``, ``sglang``, ``generic``); when omitted it is inferred from + ``facts``. """ from runtime.common import engine_adapter - runtime = framework(facts) or "vllm" + runtime = engine if engine is not None else (framework(facts) or "vllm") return engine_adapter.get_engine_adapter(runtime).build_container_spec( image, facts, arguments, name=name, reference=reference, rank=rank, row=row, master=master, size=size, routes=routes, host_library=host_library, version=version, model_path=model_path, directory=directory, gid=gid, gid_index=gid_index, - positions=positions, ring_only=ring_only, + positions=positions, ring_only=ring_only, extra_env=extra_env, ) diff --git a/runtime/common/test_engine_adapter.py b/runtime/common/test_engine_adapter.py index f97cbadc..3590698c 100644 --- a/runtime/common/test_engine_adapter.py +++ b/runtime/common/test_engine_adapter.py @@ -167,3 +167,91 @@ def test_generic_container_adapter_runs_arbitrary_nccl_workloads_without_vllm_or assert adapter.classify_health_response(500).state == "unhealthy" valid = adapter.validate_parallelism(user_cmd, size=2, ring_only=True) assert valid.ok and valid.world_size == 2 and len(valid.groups) == 1 + assert spec.labels[engine_adapter.ENGINE_LABEL] == "generic" + + +def test_health_probe_spec_and_classify_health_response_across_all_engines(): + vllm = engine_adapter.get_engine_adapter("vllm") + vllm_spec = vllm.health_probe_spec(api_url="http://192.0.2.10:8000/v1") + assert vllm_spec.mode == "http" and vllm_spec.bare_503_is_fatal is True + assert [ep.url for ep in vllm_spec.endpoints] == ["http://192.0.2.10:8000/health", "http://192.0.2.10:8000/v1/models"] + assert vllm.classify_health_response(503, "", assume_running=True).fatal is True + assert vllm.classify_health_response(503, "warming up", assume_running=True).fatal is False + assert vllm.classify_health_response(500, "EngineCore encountered an issue").fatal is True + + sglang = engine_adapter.get_engine_adapter("sglang") + sg_spec = sglang.health_probe_spec(api_url="http://192.0.2.10:30000/v1") + assert sg_spec.mode == "http" and sg_spec.bare_503_is_fatal is True + assert [ep.path for ep in sg_spec.endpoints] == ["/health", "/health_generate", "/v1/models"] + assert sglang.classify_health_response(503, "TokenizerManager is dead").fatal is True + assert sglang.classify_health_response(503, "", assume_running=True).fatal is True + assert sglang.classify_health_response(503, "loading weights", assume_running=True).fatal is False + + generic = engine_adapter.get_engine_adapter("generic") + proc_spec = generic.health_probe_spec() + assert proc_spec.mode == "process" and proc_spec.endpoints == () and proc_spec.bare_503_is_fatal is False + env_spec = generic.health_probe_spec(environment={"SPARKRING_HEALTH_URL": "http://192.0.2.10:9090/ready"}) + assert env_spec.mode == "http" and [ep.url for ep in env_spec.endpoints] == ["http://192.0.2.10:9090/ready"] + assert generic.classify_health_response(503, "", assume_running=True).fatal is False + assert generic.classify_health_response(204, "").state == "healthy" + + +def test_memory_settle_contract_across_all_engines(): + vllm = engine_adapter.get_engine_adapter("vllm") + vc = vllm.memory_settle_contract(["vllm", "serve", "/model", "--gpu-memory-utilization", "0.88", + "--kv-cache-memory-bytes=1073741824"]) + assert vc.engine == "vllm" and vc.drop_caches is True and vc.enforce_utilization is True + assert vc.requested_utilization == 0.88 and vc.requested_kv_cache_bytes == 1073741824 and vc.supports_sparkcache + + sglang = engine_adapter.get_engine_adapter("sglang") + sc = sglang.memory_settle_contract(["python3", "-m", "sglang.launch_server", "--mem-fraction-static=0.84"]) + assert sc.engine == "sglang" and sc.display_name == "SGLang" and sc.utilization_flags == ("--mem-fraction-static",) + assert sc.requested_utilization == 0.84 and sc.supports_sparkcache is False and sc.pinned_bytes == 0 + + generic = engine_adapter.get_engine_adapter("generic") + gc = generic.memory_settle_contract(["python3", "-m", "exllamav3.server", "--model", "/model"]) + assert gc.engine == "generic" and gc.drop_caches is False and gc.enforce_utilization is False + assert gc.requested_utilization is None and gc.skip_reason is not None + gc_drop = generic.memory_settle_contract([], environment={"SPARKRING_DROP_CACHES": "1"}) + assert gc_drop.drop_caches is True and gc_drop.enforce_utilization is False and gc_drop.skip_reason is None + + +def test_dashboard_summary_and_detect_engine_resolution(): + vllm_summary = engine_adapter.get_engine_adapter("vllm").dashboard_summary( + {"positions": [0, 1, 2, 3]}, {"tp": 4, "settings": {"decode_context_parallel_size": 2}}, + ) + assert vllm_summary["engine"] == "vllm" and vllm_summary["badge"] == "vLLM" + assert vllm_summary["supports_runtime_status"] is True + assert vllm_summary["parallelism"]["summary"] == "TP4 / DCP2" + + sg_summary = engine_adapter.get_engine_adapter("sglang").dashboard_summary( + {"positions": [0, 1, 2, 3], "command": ["python3", "-m", "sglang.launch_server", "--tp-size", "4", "--ep-size", "4"]}, + ) + assert sg_summary["engine"] == "sglang" and sg_summary["badge"] == "SGLang" + assert sg_summary["supports_runtime_status"] is False and sg_summary["supports_metrics"] is True + assert sg_summary["parallelism"]["summary"] == "TP4 / EP4" + + gen_proc = engine_adapter.get_engine_adapter("generic").dashboard_summary({"positions": [0, 1]}) + assert gen_proc["engine"] == "generic" and gen_proc["api_kind"] == "process" + assert gen_proc["parallelism"]["summary"] == "2 ranks" + gen_http = engine_adapter.get_engine_adapter("generic").dashboard_summary( + {"positions": [0, 1], "health_url": "http://192.0.2.10:9000/health"}, + ) + assert gen_http["api_kind"] == "http" + + # detect_engine resolves from explicit fields, facts, commands, env, and defaults legacy dicts to vLLM. + assert engine_adapter.detect_engine(None).name == "vllm" + assert engine_adapter.detect_engine({}).name == "vllm" + assert engine_adapter.detect_engine("sglang").name == "sglang" + assert engine_adapter.detect_engine("unknown").name == "generic" + assert engine_adapter.detect_engine({"engine": "sglang"}).name == "sglang" + assert engine_adapter.detect_engine({"framework": "sglang"}).name == "sglang" + assert engine_adapter.detect_engine({"labels": {"io.sparkring.engine": "generic"}}).name == "generic" + assert engine_adapter.detect_engine({"launch": {"engine": "unknown"}}).name == "generic" + assert engine_adapter.detect_engine(sglang_facts()).name == "sglang" + assert engine_adapter.detect_engine(facts()).name == "vllm" + assert engine_adapter.detect_engine(["python3", "-m", "sglang.launch_server", "--mem-fraction-static", "0.85"]).name == "sglang" + assert engine_adapter.detect_engine(["python3", "-m", "exllamav3.server", "--model", "/model"]).name == "generic" + assert engine_adapter.detect_engine(["serve", "/model", "--gpu-memory-utilization", "0.9"]).name == "vllm" + assert engine_adapter.detect_engine({"environment": {"SGLANG_NCCL_SO_PATH": TARGET}}).name == "sglang" + assert engine_adapter.detect_engine({"environment": {"SPARKRING_HEALTH_URL": "http://127.0.0.1:9000/h"}}).name == "generic" diff --git a/runtime/common/test_installer.py b/runtime/common/test_installer.py index 4b684747..fc0a20c2 100644 --- a/runtime/common/test_installer.py +++ b/runtime/common/test_installer.py @@ -688,3 +688,78 @@ def tracked_fchmod(fd, mode): assert not failing.exists() assert not list(tmp_path.rglob("*.tmp")) + +def test_make_lock_records_optional_engine_and_preserves_legacy_locks(): + legacy = installer.make_lock(QWEN, site(), "1" * 40, "2" * 64) + assert "engine" not in legacy + assert installer.engine_of(legacy) == "vllm" + assert installer.validate(legacy) == legacy + assert "io.sparkring.engine" not in installer.container_labels(legacy, 0) + + explicit = installer.make_lock(QWEN, site(), "1" * 40, "2" * 64, engine="vllm") + assert explicit["engine"] == "vllm" + assert installer.validate(explicit) == explicit + assert installer.container_labels(explicit, 0)["io.sparkring.engine"] == "vllm" + + +def test_make_stock_lock_renders_sglang_and_generic_specs_connections_and_status(tmp_path): + from runtime.common import libsircl + from runtime.common.test_stock_image import LIBRARY, REFERENCE, SGLANG_REFERENCE, TARGET, image, sglang_facts + from runtime.common.test_transport import document + + _, _, routes, _ = libsircl.group(document("pair", 2), [0, 1]) + rows = [ + {"host": "spark0", "management_ip": "192.0.2.10", "fabric_ip": "198.18.20.1", "interface": "enP7s7"}, + {"host": "spark1", "management_ip": "192.0.2.11", "fabric_ip": "198.18.20.2", "interface": "enP7s7"}, + ] + wheel = "/opt/sglang/nvidia/nccl/lib/libnccl.so.2" + sg_lock = installer.make_stock_lock( + "sglang-pair", image(), sglang_facts(**{"torch.nccl_libraries": [wheel]}), + ["--mem-fraction-static", "0.85", "--served-model-name", "Qwen-SGLang"], + engine="sglang", reference=SGLANG_REFERENCE, rows=rows, routes=routes, + host_library=LIBRARY, version="0.6.0", directory="/var/lib/sparkring/stock/sglang-pair", + model_path="/srv/models/m", positions=[0, 1], + ) + assert sg_lock["engine"] == "sglang" and installer.engine_of(sg_lock) == "sglang" + assert installer.validate(sg_lock) == sg_lock + sg_specs = installer.specifications(sg_lock) + assert len(sg_specs) == 2 + assert sg_specs[0].labels["io.sparkring.engine"] == "sglang" + assert sg_specs[0].environment["SGLANG_NCCL_SO_PATH"] == TARGET + assert "--mem-fraction-static" in sg_specs[0].command + conn = installer.connection(sg_lock) + assert conn == {"api_url": "http://192.0.2.10:8000/v1", "model": "Qwen-SGLang", "port": 8000, "engine": "sglang"} + + # Generic container lock: no vLLM/SGLang flags, no forced --port or --served-model-name crash. + gen_facts = {"torch": {"nccl": "dynamic", "nccl_libraries": [wheel]}} + user_cmd = ["python3", "-m", "exllamav3.server", "--model", "/model", "--tp", "2"] + gen_lock = installer.make_stock_lock( + "exl3-pair", image(entrypoint=()), gen_facts, user_cmd, + engine="generic", reference=REFERENCE, rows=rows, routes=routes, + host_library=LIBRARY, version="0.6.0", directory="/var/lib/sparkring/stock/exl3-pair", + model_path="/srv/models/exl3", positions=[0, 1], + ) + gen_dir = tmp_path / "generic-dep" + installer.write(gen_dir / "deployment.lock.json", gen_lock) + for rel, content in installer.rendered(gen_lock).items(): + installer.write(gen_dir / rel, content) + gen_specs = installer.specifications(gen_lock) + assert list(gen_specs[0].command) == user_cmd + assert gen_specs[0].labels["io.sparkring.engine"] == "generic" + assert gen_specs[0].environment["LD_PRELOAD"] == TARGET + assert not any(k.startswith(("VLLM_", "SGLANG_")) for k in gen_specs[0].environment) + assert installer.connection(gen_lock) == {"api_url": None, "model": "stock-generic", "port": None, "engine": "generic"} + assert installer.recorded_connection(gen_dir, gen_lock) == installer.connection(gen_lock) + assert installer.status(gen_dir)["engine"] == "generic" + + # Generic container with optional health_url propagates SPARKRING_HEALTH_URL and exposes api_url/health_url. + gen_http = installer.make_stock_lock( + "torchrun-http", image(entrypoint=()), gen_facts, ["torchrun", "--nproc-per-node=1", "train.py"], + engine="generic", reference=REFERENCE, rows=rows, routes=routes, + host_library=LIBRARY, version="0.6.0", directory="/var/lib/sparkring/stock/torchrun-http", + health_url="http://192.0.2.10:9090/healthz", + ) + assert installer.specifications(gen_http, only_rank=0)[0].environment["SPARKRING_HEALTH_URL"] == "http://192.0.2.10:9090/healthz" + assert installer.connection(gen_http)["health_url"] == "http://192.0.2.10:9090/healthz" + assert installer.connection(gen_http)["api_url"] == "http://192.0.2.10:9090/healthz" + diff --git a/runtime/common/test_stock_image.py b/runtime/common/test_stock_image.py index 60206a45..18566dda 100644 --- a/runtime/common/test_stock_image.py +++ b/runtime/common/test_stock_image.py @@ -582,3 +582,47 @@ def test_sircl_gid_index_is_configurable_with_documented_fallback(monkeypatch): assert spec_explicit.environment["SIRCL_GID_INDEX"] == "1" +def test_generic_engine_preflight_binding_and_rank_spec_allow_arbitrary_nccl_containers(): + wheel = "/usr/local/lib/python3.12/dist-packages/nvidia/nccl/lib/libnccl.so.2" + generic_found = facts(**{"torch.nccl_libraries": [wheel]}) + generic_found["vllm"] = None + generic_found["sglang"] = None + user_cmd = ["python3", "-m", "exllamav3.server", "--model", "/model", "--tp", "2"] + + # Without explicit engine="generic", preflight still refuses images without vllm/sglang. + assert any("no vllm or sglang" in p for p in stock_image.preflight(image(), generic_found, user_cmd)) + # With explicit engine="generic", preflight and binding pass cleanly without PyNccl requirements. + assert stock_image.preflight(image(), generic_found, user_cmd, size=2, ring_only=True, engine="generic") == [] + env = stock_image.binding_environment(image(), "0.6.0", generic_found, engine="generic") + assert env == {"LD_PRELOAD": TARGET, "LIBSIRCL_NCCL_API_VERSION": str(libsircl.NCCL_API_VERSION)} + generic_bind = {"global_provider": TARGET, "torch_provider": TARGET, "torch_runtime_nccl_version": 22705, + "mapped": [TARGET]} + assert stock_image.binding_problems(generic_bind, "0.6.0", generic_found, engine="generic") == [] + bad_mapped = stock_image.binding_problems({**generic_bind, "mapped": [TARGET, wheel]}, "0.6.0", + generic_found, engine="generic") + assert len(bad_mapped) == 1 and "not libsircl alone" in bad_mapped[0] + + _, _, routes, _ = libsircl.group(document("pair", 2), [0, 1]) + row = {"host": "spark0", "fabric_ip": "192.0.2.20", "interface": "enP7s7"} + spec = stock_image.rank_spec( + image(entrypoint=()), generic_found, user_cmd, name="sr-stock-generic", reference=REFERENCE, + rank=0, row=row, master="192.0.2.20", size=2, routes=routes[0], host_library=LIBRARY, + version="0.6.0", model_path=None, directory="/var/lib/sparkring/stock/sr-stock-generic", + engine="generic", + ) + assert list(spec.command) == user_cmd + assert spec.labels["io.sparkring.engine"] == "generic" + assert spec.environment["LD_PRELOAD"] == TARGET + assert "VLLM_NCCL_SO_PATH" not in spec.environment and "SGLANG_NCCL_SO_PATH" not in spec.environment + assert any(m.target == wheel and m.read_only for m in spec.mounts) + assert not any(m.target == "/model" for m in spec.mounts) + + +def test_explicit_engine_disambiguates_image_with_both_vllm_and_sglang(): + both = facts() + both["sglang"] = sglang_facts()["sglang"] + assert any("both vllm and sglang" in p for p in stock_image.preflight(image(), both, [])) + assert stock_image.preflight(image(), both, ["--context-length", "32768"], size=2, engine="sglang") == [] + assert stock_image.preflight(image(), both, ["--served-model-name", "m"], size=2, engine="vllm") == [] + + diff --git a/runtime/host/dashboard.py b/runtime/host/dashboard.py index 5bcb3490..f7a47faf 100644 --- a/runtime/host/dashboard.py +++ b/runtime/host/dashboard.py @@ -106,7 +106,7 @@ import urllib.request from runtime.common.transport_names import collective_name -from runtime.common import serving, thinking +from runtime.common import engine_adapter, serving, thinking from runtime.host.dashboard_rates import number, plugin_fresh from runtime.host import startup @@ -730,7 +730,9 @@ def deployments_from_site(site: dict, size: int) -> list: """The deployments of a sparkring-dashboard-site/v1 file, checked against the fabric's size. A row that names positions outside the fabric, an unusable API address or port, or a - container name with characters a shell would interpret is left out.""" + container name with characters a shell would interpret is left out. Generic container + deployments (``engine: "generic"``) may omit ``api_host`` and ``api_port`` when they + run without an HTTP server.""" if not isinstance(site, dict) or site.get("schema") != SITE_SCHEMA: raise ValueError(f"not a {SITE_SCHEMA} file") rows = [] @@ -739,22 +741,41 @@ def deployments_from_site(site: dict, size: int) -> list: continue positions = row.get("positions") port = row.get("api_port") + raw_engine = row.get("engine") + engine = ( + raw_engine.strip().lower() + if isinstance(raw_engine, str) and raw_engine.strip().lower() in ("vllm", "sglang", "generic", "flare") + else None + ) if not (isinstance(positions, list) and positions and all(type(p) is int and 0 <= p < size for p in positions) and len(set(positions)) == len(positions)): continue - if not _ip(row.get("api_host")) or type(port) is not int or not 0 < port < 65536: - continue + api_host = row.get("api_host") + process_only_generic = engine == "generic" and api_host is None and port is None + if not process_only_generic: + if not _ip(api_host) or type(port) is not int or not 0 < port < 65536: + continue containers = [c for c in row.get("containers") or [] if isinstance(c, dict) and type(c.get("position")) is int and isinstance(c.get("name"), str) and CONTAINER_RE.fullmatch(c["name"])] - rows.append({"id": str(row.get("id") or run_name(positions)), "deployment_id": row.get("deployment_id"), "profile": row.get("profile"), - "checkpoint": row.get("checkpoint"), "serving": row.get("serving"), - "settings": row.get("settings"), - "model": row.get("model"), "positions": positions, "api_host": row["api_host"], - "api_port": port, "display_url": row.get("display_url"), - "stopped": bool(row.get("stopped")), "containers": containers, - **{key: row[key] for key in ("stopped_at", "serving_at") - if number(row.get(key)) and row[key] > 0}}) + entry = {"id": str(row.get("id") or run_name(positions)), "deployment_id": row.get("deployment_id"), "profile": row.get("profile"), + "checkpoint": row.get("checkpoint"), "serving": row.get("serving"), + "settings": row.get("settings"), + "model": row.get("model"), "positions": positions, "api_host": api_host, + "api_port": port, "display_url": row.get("display_url"), + "stopped": bool(row.get("stopped")), "containers": containers, + **{key: row[key] for key in ("stopped_at", "serving_at") + if number(row.get(key)) and row[key] > 0}} + if engine is not None: + entry["engine"] = engine + if isinstance(row.get("health_url"), str) and row["health_url"].startswith(("http://", "https://")): + entry["health_url"] = row["health_url"][:512] + if isinstance(row.get("parallelism"), dict): + entry["parallelism"] = { + k: v for k, v in row["parallelism"].items() + if k in ("tp", "pp", "dp", "ep", "dcp") and type(v) is int and 1 <= v <= 65535 + } + rows.append(entry) return rows @@ -853,7 +874,7 @@ def rendezvous_head(fabric, container, observed): def parallelism(facts): """Display only parallel sizes present in the public launch facts.""" - return " / ".join(f"{k.upper()}{facts[k]}" for k in ("tp", "dcp", "pp", "dp") if k in facts) + return " / ".join(f"{k.upper()}{facts[k]}" for k in ("tp", "ep", "dcp", "pp", "dp") if k in facts) def unmanaged_groups(fabric, documents, deployments, now): @@ -882,7 +903,7 @@ def unmanaged_groups(fabric, documents, deployments, now): # Revalidate the small public fact schema, including numeric types. c = {k: container[k][:512] for k in ("image", "image_id", "engine", "served_model", "master_addr", "api_bind") if isinstance(container.get(k), str)} - c.update({k: container[k] for k in ("tp", "pp", "dp", "dcp", "nnodes", "node_rank", "master_port", "api_port") + c.update({k: container[k] for k in ("tp", "ep", "pp", "dp", "dcp", "nnodes", "node_rank", "master_port", "api_port") if type(container.get(k)) is int and (0 if k == "node_rank" else 1) <= container[k] <= 65535}) c.update(name=name, position=position["position"], headless=container.get("headless") is True) kwargs = thinking_kwargs(container.get("default_chat_template_kwargs")) @@ -1336,6 +1357,8 @@ def poll(self, model: Model, now: float, viewed: bool) -> bool: whose last recorded operation stopped it is stopped whatever its port does.""" row = model.row host, port = row["api_host"], row["api_port"] + raw_engine = (row.get("launch") or {}).get("engine") or row.get("engine") + adapter = None if raw_engine == "flare" else engine_adapter.detect_engine(row) if row.get("unmanaged") and (host is None or port is None): self.set_state(model, "busy", now) return False @@ -1343,6 +1366,10 @@ def poll(self, model: Model, now: float, viewed: bool) -> bool: self.set_state(model, "stopped", now) model.metrics = model.metrics_at = None return False + if host is None or port is None: + # Managed generic container with no HTTP API: track running state without HTTP probes. + self.set_state(model, "serving", now) + return False if not viewed: return False starting = self.startup_status(model) @@ -1352,13 +1379,12 @@ def poll(self, model: Model, now: float, viewed: bool) -> bool: cadence = METRICS_VIEWED_SECONDS if model.state == "serving" and model.metrics_at is not None: model.next_metrics = min(model.next_metrics, model.metrics_at + cadence) - engine = (row.get("launch") or {}).get("engine") if now >= model.next_metrics: sent = True fetched = self.client.get(host, port, "/metrics") if fetched.ok: text = fetched.body.decode("utf-8", "replace") - metrics = parse_flare_as_metrics(text) if engine == "flare" else parse_metrics(text) + metrics = parse_flare_as_metrics(text) if raw_engine == "flare" else parse_metrics(text) if not row.get("unmanaged") and row.get("model") and metrics.get("model_name") and metrics["model_name"] != row["model"]: state = "idle" with self.lock: @@ -1374,9 +1400,12 @@ def poll(self, model: Model, now: float, viewed: bool) -> bool: fetched.failure, "not_ready") if row["stopped"]: state = "stopped" # the records say its last operation stopped it - if row.get("unmanaged"): - state = ("serving" if fetched.failure == "http" and model.models_ok_at is not None - and 0 <= now - model.models_ok_at < MODELS_SECONDS else "busy") + if row.get("unmanaged") or (adapter is not None and adapter.name == "sglang" and fetched.failure == "http"): + if row.get("unmanaged"): + state = ("serving" if fetched.failure == "http" and model.models_ok_at is not None + and 0 <= now - model.models_ok_at < MODELS_SECONDS else "busy") + elif model.models_ok_at is not None and 0 <= now - model.models_ok_at < MODELS_SECONDS: + state = "serving" # SGLang can serve without --enable-metrics. Retain the same # read paths and cadence even when its counters are absent. if now >= model.next_models: @@ -1406,7 +1435,8 @@ def poll(self, model: Model, now: float, viewed: bool) -> bool: model.models_ok_at = now model.model = listed.get("id") or model.model model.max_model_len = listed.get("max_model_len") or model.max_model_len - if model.state == "serving" and model.runtime_due and engine != "flare": + if (model.state == "serving" and model.runtime_due and raw_engine != "flare" + and (adapter is None or adapter.supports_runtime_status)): sent = True model.runtime_due = False fetched = self.client.get(host, port, "/v1/sparkring/status") @@ -1784,10 +1814,27 @@ def member(self, model: Model, now: float, color: int) -> dict: if capacity and runtime.get("settings"): capacity["max_num_seqs"] = runtime["settings"].get("max_num_seqs") launch = row.get("launch") or {} - flare = launch.get("engine") == "flare" + raw_engine = launch.get("engine") or row.get("engine") + flare = raw_engine == "flare" + if flare: + engine_info = { + "engine": "flare", + "label": "Flare", + "badge": "Flare", + "api_kind": "openai", + "supports_metrics": True, + "supports_runtime_status": False, + "parallelism": {"tp": len(positions), "pp": None, "dp": None, "ep": None, "dcp": None, + "world_size": len(positions), "summary": f"TP{len(positions)}"}, + } + else: + adapter = engine_adapter.detect_engine(row) + engine_info = adapter.dashboard_summary(row, runtime) container = None if flare else next( (c["name"] for c in row["containers"] if c["position"] == head_position), None) gpu_job = bool(row.get("unmanaged") and launch.get("engine") == "unknown") + process_only_generic = (not row.get("unmanaged") and engine_info["engine"] == "generic" + and engine_info["api_kind"] == "process") sparks = [] for position in positions: spark = hostnames.get(position, {}) @@ -1796,11 +1843,18 @@ def member(self, model: Model, now: float, color: int) -> dict: "lan_address": spark.get("lan_address"), "up": up, "position": position, "container": None if flare else next( (c["name"] for c in row["containers"] if c["position"] == position), None)}) - thought = None if gpu_job else thinking_state(row, runtime.get("settings")) + thought = None if (gpu_job or engine_info["engine"] == "generic") else thinking_state(row, runtime.get("settings")) + managed_layout_label = ( + engine_info["parallelism"]["summary"] + if engine_info["engine"] != "vllm" + else layout_label(len(positions)) + ) return { "id": model.id, "name": ("Spark " if len(positions) == 1 else "Sparks ") + ", ".join(map(str, positions)) if row.get("unmanaged") else run_name(positions), "profile": row.get("profile"), + "engine": engine_info["engine"], + "engine_summary": engine_info, "start_command": start_command(row), "unmanaged": bool(row.get("unmanaged")), "gpu_job": gpu_job, "flare": flare, "api_local": bool(row.get("api_local")), "launch": launch, @@ -1809,15 +1863,22 @@ def member(self, model: Model, now: float, color: int) -> dict: "stopped_records": row.get("stopped_records", []), "startup": starting, "spark_startup": spark_starting, - "state": model.state, "state_label": "GPU in use" if gpu_job else LABELS.get(model.state, "Checking"), "state_since": since, + "state": model.state, + "state_label": ("GPU in use" if gpu_job else "Running" if process_only_generic and serving + else LABELS.get(model.state, "Checking")), + "state_since": since, "model": model.model, "model_short": short_model(model.model), "max_model_len": model.max_model_len, "metrics_problem": metrics.get("metrics_problem") if serving else None, "endpoint": endpoint, # The runtime-status view asks the workers for a report every 5 s while it is open. "details_url": f"http://{row['api_host']}:{port}/v1/sparkring/status/view" if model.runtime else None, "layout": {"label": "Flare" if flare else parallelism(launch) - if row.get("unmanaged") else layout_label(len(positions)) if serving else None, "count": len(positions), - "tp": len(positions) if flare else launch.get("tp") if row.get("unmanaged") else runtime.get("tp"), + if row.get("unmanaged") else managed_layout_label if serving else None, "count": len(positions), + "tp": len(positions) if flare else launch.get("tp") if row.get("unmanaged") else ( + runtime.get("tp") if runtime.get("tp") is not None else engine_info["parallelism"]["tp"] + ), + "pp": launch.get("pp") if row.get("unmanaged") else engine_info["parallelism"]["pp"], + "ep": launch.get("ep") if row.get("unmanaged") else engine_info["parallelism"]["ep"], "dcp": launch.get("dcp") if row.get("unmanaged") else (runtime.get("settings") or {}).get("decode_context_parallel_size")}, "live": {key: metrics.get(key) for key in ("running", "waiting", "kv")} if model.metrics else None, diff --git a/runtime/host/install_workflow.py b/runtime/host/install_workflow.py index d7470edb..57dcb985 100644 --- a/runtime/host/install_workflow.py +++ b/runtime/host/install_workflow.py @@ -60,10 +60,12 @@ import re import sys import time +import urllib.parse from pathlib import Path, PurePosixPath from runtime.common import ( distribution, + engine_adapter, fabric_layout, image_lock, installer, @@ -476,12 +478,13 @@ def _select_mesh(site, cluster, profile, hint, **options): def profile_arguments(card): - """The vLLM arguments of the card's profile with the card's checkpoint settings.""" + """The serving arguments of the card's profile with the card's checkpoint settings.""" from runtime.common import toolchain_profiles configuration = profiles.read_json(installer.ROOT / card["configuration"]) if "checkpoints" in configuration: configuration = toolchain_profiles.checkpoint_settings(configuration, card["target_variant"]) - return configuration.get("vllm_args", []) + adapter = engine_adapter.detect_engine(configuration) + return configuration.get(adapter.profile_args_key, configuration.get("vllm_args", [])) ENDPOINT_SETTINGS = ("api_port", "api_bind") @@ -997,20 +1000,21 @@ def _permits(check, facts, permitted, rank, managed): def settle_memory(directory, *, run=None, say=print): """Drop the page cache on every Spark of the deployment in ``directory`` and wait for settled memory before - its vLLM starts (runtime.host.memory_settle); a Spark with less available memory than vLLM asks for - refuses the start. vLLM's ask is rank 0's --gpu-memory-utilization of the total, read from the rendered - container of a Compose-rendered deployment, and its SparkCache connector's pinned host memory counts - beside it (memory_settle.pinned_bytes); another backend's start drops caches without those checks. + its engine starts (``runtime.host.memory_settle``), dispatched through ``EngineAdapter.memory_settle_contract``. + vLLM enforces ``--gpu-memory-utilization`` plus SparkCache pinned bytes; SGLang enforces + ``--mem-fraction-static``; generic containers settle or skip cleanly without requiring vLLM flags. A Spark where this deployment's own rank container already runs is left out: its model holds that memory, and the start keeps the running container (an installation repeated while it serves). When the model runs on every Spark of the deployment, nothing is settled and nothing is refused.""" lock = installer.load(directory) - utilization, pinned = None, 0 + contract, utilization, pinned = None, None, 0 if lock.get("backend") == "compose": - command = installer.specifications(lock, only_rank=0)[0].command - utilization, _ = memory_settle.requested(command) - pinned = memory_settle.pinned_bytes(command) + spec = installer.specifications(lock, only_rank=0)[0] + adapter = engine_adapter.detect_engine(lock if ("engine" in lock or "stock" in lock) else list(spec.command)) + contract = adapter.memory_settle_contract(spec.command, environment=getattr(spec, "environment", None)) + utilization = contract.requested_utilization + pinned = contract.pinned_bytes if run is None: from scripts.installer_runner import ssh @@ -1022,7 +1026,7 @@ def run(host, argv): if not hosts: say("Memory settle skipped: this deployment's model already runs on every Spark.") return [] - return memory_settle.settle(hosts, utilization, run=run, pinned_bytes=pinned, say=say) + return memory_settle.settle(hosts, utilization, run=run, pinned_bytes=pinned, say=say, contract=contract) def check_managed_namespace(lock): @@ -1798,6 +1802,298 @@ def prepare(path): return completed +_STOCK_LIBRARY_RE = re.compile(r"/[^\0]*/libsircl\.so\.([0-9]+\.[0-9]+\.[0-9]+)") +STOCK_SPARK_DIRECTORY = "/var/lib/sparkring/stock" + + +def _stock_needs(message, field, details=None): + raise NeedsInput(f"{message}. Nothing has been changed.", field=field, details=details) + + +def _validate_health_url(value): + if value is None: + return None + parsed = urllib.parse.urlsplit(str(value)) + if parsed.scheme not in ("http", "https") or not parsed.hostname: + _stock_needs(f"--health-url must be an http:// or https:// URL with a host, got {value!r}", "health_url") + return str(value) + + +def execute_stock_engine(args, arguments, *, state, invoke): + """Plan or execute a stock-image deployment through ``EngineAdapter`` (``--engine vllm|sglang|generic``). + + Keeps fail-closed validation via ``stock_image.preflight``, ``parallel_groups``, and + ``stock_image.binding_problems``. With ``--plan`` it writes each rank's Compose file, + ``deployment.lock.json`` (carrying explicit ``"engine": adapter.name``), and ``plan.json`` + without mutating any Spark. With ``--yes`` (and without ``--plan``) it settles unified memory + through ``adapter.memory_settle_contract``, distributes the Compose files, and starts workers + before rank 0. + """ + from runtime.common import libsircl, loader_policy, stock_image + from runtime.host import relays + + adapter = engine_adapter.get_engine_adapter(args.engine or "generic") + if args.transport != libsircl.BACKEND: + _stock_needs(f"--image {args.image} names a stock image, which runs only with --transport libsircl", "transport") + if args.nccl is not None: + _stock_needs("--nccl applies to deployments on SIRCL; a stock image runs every collective on libsircl", "transport") + if args.profile: + _stock_needs("--image REF runs the selected engine adapter with the arguments after --; it takes no --profile", + "profile") + if not args.plan and not args.yes: + _stock_needs("Specify --plan to review or --yes to execute this stock-image deployment", "plan") + library = getattr(args, "libsircl_library", None) + found = _STOCK_LIBRARY_RE.fullmatch(library or "") + if not found: + _stock_needs("--libsircl-library names the host build of libsircl every Spark holds, an absolute path ending in " + "libsircl.so. (runtime/images/libsircl_layer.py host-library)", "libsircl_library") + version = found.group(1) + paths = args.model_path or [] + if adapter.name == "generic": + if len(paths) > 1 or (paths and ("=" in paths[0] or not PurePosixPath(paths[0]).is_absolute())): + _stock_needs("--model-path, when given for generic containers, names one absolute directory", "model_path") + model_path = paths[0] if paths else None + else: + if len(paths) != 1 or "=" in paths[0] or not PurePosixPath(paths[0]).is_absolute(): + _stock_needs("--model-path names one absolute directory that holds the model on every Spark", "model_path") + model_path = paths[0] + health_url = _validate_health_url(getattr(args, "health_url", None)) + + require_head() + try: + cluster = installer.read(Path(state) / "cluster.json") + except OSError: + _stock_needs("Run sudo sparkring setup first: a stock image runs on the recorded fabric", "setup") + document = recorded_fabric(state, cluster) + ring_only = bool(getattr(args, "ring_only", False)) + reason = libsircl.fabric_unavailable(document, ring_only=ring_only) + if reason: + _stock_needs(f"--transport libsircl cannot run here: {reason}", "transport") + layout = placements.layout_of(cluster) + try: + placement = placements.parse(args.on, layout) if args.on else None + except ValueError as error: + _stock_needs(str(error), "placement") + positions = list(placement) if placement is not None else list(range(len(cluster["plan"]["spec"]["hosts"]))) + try: + group, devices, routes, planner = libsircl.group(document, positions, ring_only=ring_only) + except transports.TransportError as error: + _stock_needs(f"--transport libsircl cannot run on positions {positions}: {error}", "placement") + + reference_document = (relays.group_reference(state, cluster) + if (not ring_only and placements.relayed(layout, placement)) else None) + site = controller.model_site(cluster, f"stock-{adapter.name}", "main", placement, fabric=reference_document) + rows = site["hosts"] + + def _ssh(host, command, data=None): + try: + return invoke(host, command, data=data) if data is not None else invoke(host, command) + except (RuntimeError, OSError) as error: + raise NeedsInput(f"Spark {host} could not run {' '.join(command[:4])}: {error}. Nothing has been changed.", + field="image") from None + + reports, problems = [], {} + for rank, row in enumerate(rows): + host = row["host"] + image_record = json.loads(_ssh(host, ["sudo", "-n", "docker", "image", "inspect", args.image]))[0] + digest = _ssh(host, ["sha256sum", library]).split()[0] + facts = stock_image.parse(_ssh(host, stock_image.probe_command(args.image, library, version), + data=stock_image.PROBE_SOURCE)) + found_problems = stock_image.preflight( + image_record, facts, list(arguments), size=len(rows), positions=positions, ring_only=ring_only, + engine=adapter.name, + ) + parallel_check = adapter.validate_parallelism( + list(arguments), size=len(rows), positions=positions, ring_only=ring_only, + ) + for issue in parallel_check.problems: + if issue not in found_problems: + found_problems.append(issue) + bound = None + if not found_problems: + bound = stock_image.parse(_ssh( + host, + stock_image.probe_command( + args.image, library, version, + environment=stock_image.binding_environment(image_record, version, facts, engine=adapter.name), + binding=True, + shadow_paths=stock_image.nccl_shadow_paths(facts, version), + ), + data=stock_image.PROBE_SOURCE, + )) + found_problems = stock_image.binding_problems(bound, version, facts, engine=adapter.name) + if found_problems: + problems[f"rank {rank} ({host})"] = found_problems + reports.append({"host": host, "image": image_record, "library_sha256": digest, "facts": facts, "binding": bound}) + if len({report["image"]["Id"] for report in reports}) > 1: + problems["image"] = ["the Sparks hold different images under " + args.image] + if len({report["library_sha256"] for report in reports}) > 1: + problems["library"] = [f"the Sparks hold different bytes at {library}"] + if problems: + lines = [f"{where}: {problem}" for where, found_list in problems.items() for problem in found_list] + _stock_needs("The stock image cannot run with libsircl here: " + "; ".join(lines), "image", + details={"problems": problems}) + + image_record = reports[0]["image"] + digest = reports[0]["library_sha256"] + identity = { + "engine": adapter.name, + "image": image_record["Id"], + "library": digest, + "positions": positions, + "model": model_path, + "arguments": list(arguments), + "fabric": document["id"], + } + if ring_only: + identity["ring_only"] = True + if health_url: + identity["health_url"] = health_url + name = "sr-stock-" + hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()[:12] + spark_directory = f"{STOCK_SPARK_DIRECTORY}/{name}" + output = Path(state) / "stock" / name + output.mkdir(parents=True, exist_ok=True) + + lock = installer.make_stock_lock( + name, + image_record, + reports[0]["facts"], + list(arguments), + engine=adapter.name, + reference=image_record["Id"], + rows=rows, + routes=routes, + host_library=library, + version=version, + directory=spark_directory, + model_path=model_path, + positions=positions, + ring_only=ring_only, + health_url=health_url, + ) + specs = installer.specifications(lock) + files, commands = {}, {"prepare": [], "start": [], "stop": []} + seccomp_text = None + for rank, (row, spec) in enumerate(zip(rows, specs, strict=True)): + compose_name = f"compose.rank{rank}.yaml" + files[compose_name] = stock_image.compose_text(spec, image_record["Id"]) + rank_dir = output / f"rank{rank}" + rank_dir.mkdir(parents=True, exist_ok=True) + (rank_dir / "container.json").write_text(installer.compose.encoded(spec.document()), encoding="utf-8", + newline="\n") + host_quoted = shlex.quote(row["host"]) + remote = f"{spark_directory}/{compose_name}" + commands["prepare"].append( + f"ssh {host_quoted} 'sudo install -d -m 0755 {spark_directory}/{stock_image.RECEIPTS}' && " + f"ssh {host_quoted} 'sudo tee {remote} >/dev/null' < {output / compose_name}" + ) + if spec.security_opt: + seccomp_text = loader_policy.PROFILE.read_text(encoding="utf-8") + files["loader-seccomp.json"] = seccomp_text + commands["prepare"].append( + f"ssh {host_quoted} 'sudo tee {spark_directory}/loader-seccomp.json >/dev/null' " + f"< {output / 'loader-seccomp.json'}" + ) + commands["start"].append(f"ssh {host_quoted} 'sudo docker compose -f {remote} up -d'") + commands["stop"].append(f"ssh {host_quoted} 'sudo docker compose -f {remote} down'") + for file_name, text in files.items(): + (output / file_name).write_text(text, encoding="utf-8", newline="\n") + (output / "deployment.lock.json").write_text(installer.compose.encoded(lock), encoding="utf-8", newline="\n") + + conn = installer.connection(lock) + probe_spec = adapter.health_probe_spec( + api_url=conn["api_url"], health_url=health_url, environment=specs[0].environment, + ) + dash_summary = adapter.dashboard_summary( + {"engine": adapter.name, "positions": positions, "command": list(specs[0].command), + "api_host": rows[0]["fabric_ip"] if conn["port"] else None, "api_port": conn["port"], + "health_url": health_url}, + ) + result = { + "schema": stock_image.SCHEMA, + "state": "planned" if args.plan else "complete", + "status": libsircl.STATUS, + "name": name, + "engine": adapter.name, + "framework": adapter.name, + "image": {"reference": args.image, "id": image_record["Id"]}, + "library": {"path": library, "sha256": digest}, + "group": group, + "positions": positions, + "routes": routes, + "planner": planner, + "directory": {"node_a": str(output), "sparks": spark_directory}, + "files": sorted(files), + "commands": commands, + "api_url": conn["api_url"], + "health_probe": {"mode": probe_spec.mode, "endpoints": [ep.url for ep in probe_spec.endpoints]}, + "dashboard_summary": dash_summary, + "preflight": [{ + "host": report["host"], + "engine": adapter.name, + "framework": stock_image.framework(report["facts"]) or adapter.name, + "glibc": report["facts"].get("glibc"), + "cuda_driver_api": (report["facts"].get("cuda") or {}).get("driver_api"), + "vllm": (report["facts"].get("vllm") or {}).get("version"), + "sglang": (report["facts"].get("sglang") or {}).get("version"), + "torch": (report["facts"].get("torch") or {}).get("version"), + "torch_nccl": (report["binding"] or {}).get("torch_nccl_version"), + "torch_runtime_nccl": (report["binding"] or {}).get("torch_runtime_nccl_version"), + } for report in reports], + } + if health_url: + result["health_url"] = health_url + (output / "plan.json").write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8", + newline="\n") + if args.plan: + return result + + # Execution path (--engine ... --yes): settle memory via EngineAdapter, distribute files, start workers then rank 0. + settle_memory(output, run=lambda host, argv: _ssh(host, argv)) + for rank, (row, spec) in enumerate(zip(rows, specs, strict=True)): + host = row["host"] + compose_name = f"compose.rank{rank}.yaml" + remote = f"{spark_directory}/{compose_name}" + _ssh(host, ["sudo", "-n", "install", "-d", "-m", "0755", f"{spark_directory}/{stock_image.RECEIPTS}"]) + _ssh(host, ["sudo", "-n", "tee", remote], data=files[compose_name]) + if spec.security_opt and seccomp_text is not None: + _ssh(host, ["sudo", "-n", "tee", f"{spark_directory}/loader-seccomp.json"], data=seccomp_text) + for rank in [*range(1, len(rows)), 0]: + remote = f"{spark_directory}/compose.rank{rank}.yaml" + _ssh(rows[rank]["host"], ["sudo", "-n", "docker", "compose", "-f", remote, "up", "-d"]) + (output / "state.json").write_text( + json.dumps({"generation": 1, "operation": "up", "complete": True}, indent=2) + "\n", + encoding="utf-8", newline="\n", + ) + return result + + +def stock_engine_lines(result): + """Human-readable summary for a stock-image ``EngineAdapter`` plan or execution.""" + from runtime.common import libsircl + group = result["group"] + engine = result.get("engine") or result.get("framework") or "vllm" + adapter = engine_adapter.get_engine_adapter(engine) + label = f"{adapter.display_name} ({adapter.name})" + header = ( + f"Stock image {result['image']['reference']} ({result['image']['id'][7:19]}) on libsircl " + f"[{label}] ({result['state']}): {result['library']['path']}" + ) + printed = [ + header, + f" libsircl group: {group['name']} at positions {', '.join(map(str, group['positions']))}; " + f"{group['lanes']} lanes per peer, {libsircl.relays_text(group)}", + f" Files: {result['directory']['node_a']}", + ] + if result.get("api_url"): + printed.append(f" Endpoint: {result['api_url']}") + if result["state"] == "planned": + printed += [" Copy them to every Spark:"] + [" " + cmd for cmd in result["commands"]["prepare"]] + printed += [" Start every rank:"] + [" " + cmd for cmd in result["commands"]["start"]] + printed += [" Stop:"] + [" " + cmd for cmd in result["commands"]["stop"]] + return printed + + def main(argv=None): parser = argparse.ArgumentParser(prog="sparkring install", parents=[colour.parser()], description="Set up this Spark ring and deploy one exact model profile.") @@ -1876,6 +2172,12 @@ def main(argv=None): parser.add_argument("--ring-only", action="store_true", help="with --transport libsircl: connect only ring neighbors with LIBSIRCL_RING_ONLY=1 " "(direct-cable pairs and whole cycles, no ConnectX relay table required)") + parser.add_argument("--engine", choices=tuple(sorted(engine_adapter.ADAPTERS)), + help="with --image REF --transport libsircl: explicit engine adapter (vllm, sglang, generic) " + "supporting both --plan and --yes execution through EngineAdapter") + parser.add_argument("--health-url", metavar="URL", + help="with --engine generic: optional HTTP health probe URL (sets SPARKRING_HEALTH_URL); " + "when omitted, recovery uses container running-state liveness") serving_settings.add_arguments(parser, install=True) # A stock image's runtime arguments follow --. argv = list(sys.argv[1:] if argv is None else argv) @@ -1917,6 +2219,8 @@ def main(argv=None): parser.error("--expert-parallel requires a SparkRing installer image name") if vllm_arguments and not stock: parser.error("arguments after -- are a stock image's vLLM arguments: use them with --image REF") + if (args.engine is not None or args.health_url is not None) and not stock: + parser.error("--engine and --health-url apply only with --image REF") if args.ring_only and args.transport != transports.LIBSIRCL: parser.error("--ring-only applies only with --transport libsircl") if args.nccl is not None: @@ -1944,7 +2248,9 @@ def journals(): except OSError: before[journal] = None try: - if stock: + if stock and (args.engine is not None or args.health_url is not None): + result = execute_stock_engine(args, vllm_arguments, state=controller.STATE, invoke=discovery.ssh) + elif stock: from runtime.host import stock_install result = stock_install.plan(args, vllm_arguments, state=controller.STATE, invoke=discovery.ssh) else: @@ -1974,14 +2280,17 @@ def journals(): # refresh prints one line and never changes the result. from runtime.host import dashboard_admin dashboard_admin.refresh_site() - if result["state"] == "complete": + if result["state"] == "complete" and stock: + for line in stock_engine_lines(result): + print(line) + elif result["state"] == "complete": if (result.get("hairpin") or {}).get("required"): print(hairpin_ring.complete_text(len(result["hairpin"].get("ranks") or []) or 4)) ready_line = model_ready_line(result) if ready_line: print("Model ready: " + ready_line) else: - print("Model ready: " + result["api_url"]) + print("Model ready: " + str(result.get("api_url") or result.get("name") or "ready")) for line in summary_lines(result): print(line) elif result["state"] == "cancelled": @@ -1993,6 +2302,9 @@ def journals(): if result.get("field") != "checkpoint": for line in controller.detail_lines(result.get("details")): print(" " + line) + elif result["state"] == "planned" and stock and (args.engine is not None or args.health_url is not None): + for line in stock_engine_lines(result): + print(line) elif result["state"] == "planned" and stock: from runtime.host import stock_install for line in stock_install.lines(result): diff --git a/runtime/host/memory_settle.py b/runtime/host/memory_settle.py index 8ef03089..86f11e8b 100644 --- a/runtime/host/memory_settle.py +++ b/runtime/host/memory_settle.py @@ -1,26 +1,32 @@ -"""Free the page cache and wait for settled memory on a deployment's Sparks before vLLM starts. +"""Free the page cache and wait for settled memory on a deployment's Sparks before an engine starts. On GB10 the CPU and GPU share one memory, so the page cache that checkpoint reads and the previous model's -teardown leave behind counts against the free memory vLLM checks at startup: vLLM refuses to start when the -free memory is below ``--gpu-memory-utilization`` of the total. Before every start of a deployment, -``settle`` therefore +teardown leave behind counts against the free memory serving engines check at startup: vLLM refuses to start +when free memory is below ``--gpu-memory-utilization`` of the total, and SGLang checks ``--mem-fraction-static``. +Generic containers (ExLlamaV3, PyTorch DDP/FSDP, custom NCCL jobs) dispatch through +``EngineAdapter.memory_settle_contract`` and settle or skip cleanly without requiring vLLM flags. + +Before every start of a deployment, ``settle`` therefore: 1. writes back dirty pages and drops the page, dentry and inode caches on each of its Sparks - (``sync; echo 3 > /proc/sys/vm/drop_caches``, which frees caches only and changes no setting); + (``sync; echo 3 > /proc/sys/vm/drop_caches``, which frees caches only and changes no setting), unless + the engine's contract skips cache-dropping; 2. reads ``MemTotal`` and ``MemAvailable`` from ``/proc/meminfo`` every 5 s until two readings differ by less than 256 MiB on every Spark, for at most 180 s; -3. refuses the start, naming each Spark's settled available memory and the share vLLM asks for, when any - Spark has less available than that share. +3. refuses the start, naming each Spark's settled available memory and the share the engine asks for, when + utilization enforcement is active and any Spark has less available than that share. -Before it waits, it also refuses a start whose vLLM share (``--gpu-memory-utilization`` of the total) plus -the pinned host memory of a SparkCache connector (``pinned_bytes``: its page-capture slots and CUDA restore -arenas, which it allocates beside vLLM's share) exceeds a Spark's total less HEADROOM_GIB for the system. +Before it waits, it also refuses a start whose engine share (``--gpu-memory-utilization`` / +``--mem-fraction-static`` of the total) plus the pinned host memory of a SparkCache connector +(``pinned_bytes``: its page-capture slots and CUDA restore arenas, which it allocates beside vLLM's share) +exceeds a Spark's total less HEADROOM_GIB for the system. The serving A/B runner (performance/harnesses/serving_ab) applies the same steps before each of its starts. """ -import json import time +from runtime.common import engine_adapter + DROP_CACHES = ["sudo", "-n", "sh", "-c", "sync; echo 3 > /proc/sys/vm/drop_caches"] MEMINFO = ["awk", "/^MemTotal:|^MemAvailable:/ {print $2}", "/proc/meminfo"] SETTLE_SECONDS, SETTLE_STEP, STABLE_KIB = 180, 5, 256 * 1024 @@ -31,83 +37,112 @@ class MemoryShort(RuntimeError): - """A Spark has less settled available memory than vLLM asks for at startup.""" - - -def requested(command): - """``(utilization, kv_cache_bytes)`` of a vLLM command's ``--gpu-memory-utilization`` and - ``--kv-cache-memory-bytes``, each None when the command does not set it.""" - tokens = [str(token) for token in command] - values = {} - for index, token in enumerate(tokens): - flag, equals, value = token.partition("=") - if flag in ("--gpu-memory-utilization", "--kv-cache-memory-bytes"): - values[flag] = value if equals else (tokens[index + 1] if index + 1 < len(tokens) else None) - utilization = values.get("--gpu-memory-utilization") - kv_bytes = values.get("--kv-cache-memory-bytes") - return (float(utilization) if utilization else None), (int(kv_bytes) if kv_bytes else None) - - -def pinned_bytes(command): - """Pinned host memory, in bytes, that the SparkCache connector of a vLLM command allocates beside vLLM's - share: with ``spark_cache_async_page_capture`` on, its capture slots - (``spark_cache_async_page_capture_slot_bytes`` times ``spark_cache_async_page_capture_slot_count``, 2 by - default); with ``spark_cache_cuda_restore`` on, its restore arenas - (``spark_cache_cuda_restore_arena_budget_bytes``, else one lane's two placement arenas). 0 for a command - without ``--kv-transfer-config`` or with another connector.""" - tokens = [str(token) for token in command] - raw = None - for index, token in enumerate(tokens): - flag, equals, value = token.partition("=") - if flag == "--kv-transfer-config": - raw = value if equals else (tokens[index + 1] if index + 1 < len(tokens) else None) - if not raw: - return 0 - try: - extra = json.loads(raw).get("kv_connector_extra_config") or {} - except (ValueError, AttributeError): - return 0 - total = 0 - if extra.get("spark_cache_async_page_capture"): - total += int(extra.get("spark_cache_async_page_capture_slot_bytes") or 0) * int( - extra.get("spark_cache_async_page_capture_slot_count") or 2) - if extra.get("spark_cache_cuda_restore"): - budget = extra.get("spark_cache_cuda_restore_arena_budget_bytes") - total += int(budget) if budget else 2 * int(extra.get("spark_cache_cuda_placement_arena_bytes") or 0) - return total + """A Spark has less settled available memory than the serving engine asks for at startup.""" + + +def contract_for(command=None, *, engine=None, environment=None): + """Resolve the ``MemorySettleContract`` for ``command`` via ``EngineAdapter``.""" + adapter = ( + engine_adapter.get_engine_adapter(engine) + if isinstance(engine, str) + else (engine if isinstance(engine, engine_adapter.EngineAdapter) else engine_adapter.detect_engine(command)) + ) + return adapter.memory_settle_contract(command, environment=environment) + + +def requested(command, *, engine=None): + """``(utilization, kv_cache_bytes)`` extracted via ``EngineAdapter.memory_settle_contract``. + + Reads ``--gpu-memory-utilization`` / ``--kv-cache-memory-bytes`` for vLLM, + ``--mem-fraction-static`` for SGLang, and ``(None, None)`` for generic containers. + """ + contract = contract_for(command, engine=engine) + return contract.requested_utilization, contract.requested_kv_cache_bytes + + +def pinned_bytes(command, *, engine=None): + """Pinned host memory, in bytes, allocated beside the engine's share (vLLM SparkCache connector; 0 for others).""" + return contract_for(command, engine=engine).pinned_bytes def _gib(kib): return round(kib / 2 ** 20, 2) -def budget_problem(rows, utilization, pinned): - """The refusal text when vLLM's share plus ``pinned`` bytes exceed a Spark's total less HEADROOM_GIB, or +def _contract_labels(contract=None, engine=None): + if contract is None and engine is not None: + contract = contract_for(engine=engine) + if contract is None: + return "vLLM", "--gpu-memory-utilization", True + flag = contract.utilization_flags[0] if contract.utilization_flags else "--gpu-memory-utilization" + return contract.display_name, flag, contract.supports_sparkcache + + +def budget_problem(rows, utilization, pinned, *, contract=None, engine=None): + """The refusal text when the engine's share plus ``pinned`` bytes exceed a Spark's total less HEADROOM_GIB, or None. ``rows`` are ``(host, total KiB)``.""" + if contract is not None and not contract.enforce_utilization: + return None if not utilization: return None + display_name, flag_name, supports_sparkcache = _contract_labels(contract, engine) over = [] for host, total in rows: total_gib = total / 2 ** 20 share, pinned_gib = utilization * total_gib, pinned / 2 ** 30 if share + pinned_gib > total_gib - HEADROOM_GIB: - over.append(f"{host} (vLLM's share {utilization:g} of {total_gib:.2f} GiB is {share:.2f} GiB, " - f"SparkCache pins {pinned_gib:.2f} GiB, together {share + pinned_gib:.2f} GiB, above " - f"{total_gib - HEADROOM_GIB:.2f} GiB: the total less {HEADROOM_GIB:g} GiB for the system)") + if supports_sparkcache: + over.append( + f"{host} ({display_name}'s share {utilization:g} of {total_gib:.2f} GiB is {share:.2f} GiB, " + f"SparkCache pins {pinned_gib:.2f} GiB, together {share + pinned_gib:.2f} GiB, above " + f"{total_gib - HEADROOM_GIB:.2f} GiB: the total less {HEADROOM_GIB:g} GiB for the system)" + ) + else: + over.append( + f"{host} ({display_name}'s share {utilization:g} of {total_gib:.2f} GiB is {share:.2f} GiB, " + f"above {total_gib - HEADROOM_GIB:.2f} GiB: the total less {HEADROOM_GIB:g} GiB for the system)" + ) if not over: return None - return ("Not starting: the model's memory does not fit on " + ", ".join(over) + ". Lower the profile's " - "--gpu-memory-utilization or its SparkCache capture slots (spark_cache_async_page_capture_slot_bytes).") - - -def settle(hosts, utilization, *, run, pinned_bytes=0, sleep=time.sleep, now=time.monotonic, say=print): + if supports_sparkcache: + return ( + "Not starting: the model's memory does not fit on " + ", ".join(over) + f". Lower the profile's " + f"{flag_name} or its SparkCache capture slots (spark_cache_async_page_capture_slot_bytes)." + ) + return ( + "Not starting: the model's memory does not fit on " + ", ".join(over) + + f". Lower {flag_name} so the allocation leaves at least {HEADROOM_GIB:g} GiB for the system." + ) + + +def settle( + hosts, + utilization, + *, + run, + pinned_bytes=0, + sleep=time.sleep, + now=time.monotonic, + say=print, + engine=None, + contract=None, +): """Drop caches on each of ``hosts`` (in rank order, each once), wait for settled memory and return one row per host: ``host``, ``total_gib``, ``available_gib``, ``asks_gib`` (None without ``utilization``) and - whether the readings ``settled``. ``run(host, argv)`` runs a command on that Spark and returns its standard - output; ``pinned_bytes`` is the SparkCache connector's pinned host memory (``pinned_bytes()``). Raises - MemoryShort, before waiting, when ``utilization`` of a Spark's total plus ``pinned_bytes`` exceeds that - total less HEADROOM_GIB (``budget_problem``), and after settling when a Spark has less available memory - than ``utilization`` of its total.""" + whether the readings ``settled``. + + Dispatches engine-specific memory rules through ``contract`` (or ``engine`` via + ``EngineAdapter.memory_settle_contract``): vLLM enforces ``--gpu-memory-utilization`` and SparkCache + pinned bytes; SGLang enforces ``--mem-fraction-static``; generic containers skip cache-drop and + utilization refusal by default so arbitrary Torch/NCCL/ExLlamaV3 containers start cleanly. + """ + if contract is None and engine is not None: + contract = contract_for(engine=engine) + if contract is not None and not contract.drop_caches and not contract.enforce_utilization: + say(f"Memory settle skipped: {contract.skip_reason or contract.display_name}.") + return [] + display_name, flag_name, _ = _contract_labels(contract, engine) + effective_utilization = None if (contract is not None and not contract.enforce_utilization) else utilization hosts = list(dict.fromkeys(hosts)) for host in hosts: run(host, DROP_CACHES) @@ -120,7 +155,13 @@ def reading(): return values previous, deadline = reading(), now() + SETTLE_SECONDS - problem = budget_problem([(host, total) for host, (total, _) in zip(hosts, previous)], utilization, pinned_bytes) + problem = budget_problem( + [(host, total) for host, (total, _) in zip(hosts, previous)], + effective_utilization, + pinned_bytes, + contract=contract, + engine=engine, + ) if problem: raise MemoryShort(problem) while True: @@ -131,17 +172,17 @@ def reading(): if settled or now() > deadline: break rows = [{"host": host, "total_gib": _gib(total), "available_gib": _gib(available), - "asks_gib": _gib(utilization * total) if utilization else None, "settled": settled} + "asks_gib": _gib(effective_utilization * total) if effective_utilization else None, "settled": settled} for host, (total, available) in zip(hosts, current)] say("Memory before the start (" + ("settled" if settled else f"not settled after {SETTLE_SECONDS} s") - + (f"; vLLM asks for {utilization:g} of the total" if utilization else "") + "): " - + ", ".join(f"{row['host']} {row['available_gib']:.2f} GiB available" for row in rows) + ".") + + (f"; {display_name} asks for {effective_utilization:g} of the total" if effective_utilization else "") + + "): " + ", ".join(f"{row['host']} {row['available_gib']:.2f} GiB available" for row in rows) + ".") short = [row for row in rows if row["asks_gib"] is not None and row["available_gib"] < row["asks_gib"]] if short: raise MemoryShort( - "Not starting: available memory after dropping caches is below what vLLM asks for at startup " - "(--gpu-memory-utilization of the total) on " + ", ".join( - f"{row['host']} ({row['available_gib']:.2f} of {row['total_gib']:.2f} GiB available, vLLM asks " - f"{row['asks_gib']:.2f} GiB)" for row in short) + f"Not starting: available memory after dropping caches is below what {display_name} asks for at startup " + f"({flag_name} of the total) on " + ", ".join( + f"{row['host']} ({row['available_gib']:.2f} of {row['total_gib']:.2f} GiB available, {display_name} " + f"asks {row['asks_gib']:.2f} GiB)" for row in short) + ". A process outside this deployment holds the memory; stop it and install again.") return rows diff --git a/runtime/host/recovery.py b/runtime/host/recovery.py index bce10567..f00ceea2 100644 --- a/runtime/host/recovery.py +++ b/runtime/host/recovery.py @@ -64,7 +64,7 @@ import urllib.request from pathlib import Path -from runtime.common import compose, fabric_layout, installer, process_lock +from runtime.common import compose, engine_adapter, fabric_layout, installer, process_lock from runtime.host import ( colour, controller, @@ -411,42 +411,88 @@ def _opener(): return urllib.request.build_opener(urllib.request.ProxyHandler({})).open +def _read_body(stream, limit=4096): + if stream is None or not hasattr(stream, "read"): + return "" + try: + raw = stream.read(limit) + except OSError: + return "" + if isinstance(raw, bytes): + return raw.decode("utf-8", "replace") + return str(raw or "") + + def _ask(url, timeout, opener): """``(status, error)`` of one GET: the HTTP status, or None and why there was no answer.""" + status, _, error = _probe_http(url, timeout, opener) + return status, error + + +def _probe_http(url, timeout, opener): + """``(status, body, error)`` of one GET: HTTP status and bounded body, or None and error.""" try: with opener(url, timeout=timeout) as response: - return response.status, None + return response.status, _read_body(response), None except urllib.error.HTTPError as error: - return error.code, error.reason + return error.code, _read_body(error), error.reason except (OSError, ValueError) as error: - return None, str(getattr(error, "reason", None) or error) + return None, "", str(getattr(error, "reason", None) or error) -def api_health(api_url, *, timeout=API_TIMEOUT, opener=None): - """Rank 0's API answer: ``{"ok", "status", "dead", "error"}``. +def api_health(api_url, *, timeout=API_TIMEOUT, opener=None, engine="vllm", health_url=None): + """Rank 0's API answer: ``{"ok", "status", "dead", "error"}``, dispatched via ``EngineAdapter``. - vLLM's ``/health`` answers 200 while its engine runs and 503 once the - engine client has failed (``EngineDeadError``), the condition in which - chat requests fail with HTTP 500 "EngineCore encountered an issue"; that - 503 sets ``dead``. Any other failure (a timeout, a refused connection, - another status) asks ``/v1/models`` as a second probe: an answer there - counts as serving, and without one the API is failing but not ``dead``, - which recovery treats as a fault only once it lasts API_SILENCE seconds. + Uses ``adapter.health_probe_spec(...)`` and ``adapter.classify_health_response(...)``: + - vLLM: ``/health`` (200 healthy, 503 or ``EngineDeadError`` sets ``dead``), fallback ``/v1/models``; + - SGLang: ``/health``, ``/health_generate``, and ``/v1/models``, recognizing SGLang dead-worker + signatures (``SchedulerDead``, ``EngineDead``, ``TokenizerManager is dead``) and 503 crashes; + - generic containers: optional configured ``health_url`` (never fatally tripping vLLM 503), or + process-liveness mode (returns ``ok=True`` without sending HTTP requests when no endpoint is set). """ - base = api_url.removesuffix("/").removesuffix("/v1") + adapter = engine_adapter.detect_engine(engine) + probe = adapter.health_probe_spec(api_url=api_url, health_url=health_url, rank=0) + if probe.mode == "process" or not probe.endpoints: + return {"ok": True, "status": None, "dead": False, "error": None} opener = opener or _opener() - status, reason = _ask(base + "/health", timeout, opener) - if status == 200: - return {"ok": True, "status": 200, "dead": False, "error": None} - if status == 503: - return {"ok": False, "status": 503, "dead": True, - "error": "HTTP 503 from /health: the model engine has stopped"} - first = f"HTTP {status} from /health" if status else f"no answer from {base}/health: {reason}" - second, other = _ask(base + "/v1/models", timeout, opener) - if second == 200: - return {"ok": True, "status": 200, "dead": False, "error": None, "note": first + "; /v1/models answered"} - more = f"HTTP {second}" if second else f"no answer: {other}" - return {"ok": False, "status": status, "dead": False, "error": f"{first}; /v1/models: {more}"} + primary = probe.endpoints[0] + status, body, reason = _probe_http(primary.url, timeout, opener) + if status is not None: + verdict = adapter.classify_health_response(status, body, assume_running=True) + if verdict.state == "healthy": + return {"ok": True, "status": status, "dead": False, "error": None} + if verdict.fatal: + return {"ok": False, "status": status, "dead": True, "error": verdict.detail} + first = f"HTTP {status} from {primary.path}" if status else f"no answer from {primary.url}: {reason}" + secondaries = probe.endpoints[1:] + if not secondaries: + return {"ok": False, "status": status, "dead": False, "error": first} + failures = [first] + for endpoint in secondaries: + sec_status, sec_body, sec_reason = _probe_http(endpoint.url, timeout, opener) + if sec_status is not None: + sec_verdict = adapter.classify_health_response(sec_status, sec_body, assume_running=True) + if sec_verdict.state == "healthy": + return { + "ok": True, + "status": sec_status, + "dead": False, + "error": None, + "note": f"{first}; {endpoint.path} answered", + } + if sec_verdict.fatal: + return {"ok": False, "status": sec_status, "dead": True, "error": sec_verdict.detail} + more = f"HTTP {sec_status}" if sec_status else f"no answer: {sec_reason}" + failures.append(f"{endpoint.path}: {more}") + return {"ok": False, "status": status, "dead": False, "error": "; ".join(failures)} + + +def _probe_api(api, url, *, adapter, health_url=None): + if api is not None: + return api(url) + if adapter.name == "vllm" and health_url is None: + return api_health(url) + return api_health(url, engine=adapter, health_url=health_url) def _docker_time(value): @@ -625,9 +671,14 @@ def status_assessment(deployment, nodes, record, *, tunnel=None, api=None): return None ranks = ranks_from_observations(deployment["observations"]) documents = {row.get("host"): row for row in nodes or []} + adapter = engine_adapter.detect_engine(deployment) + health_url = deployment.get("health_url") or (record or {}).get("health_url") + probe = adapter.health_probe_spec(api_url=deployment.get("api_url"), health_url=health_url, rank=0) health = None - if ranks and ranks[0].get("running") and deployment.get("api_url"): - health = (api or api_health)(deployment["api_url"]) + if ranks and ranks[0].get("running") and probe.mode == "http": + target_url = health_url or deployment.get("api_url") + if target_url: + health = _probe_api(api, target_url, adapter=adapter, health_url=health_url) record = record or {} boots = (record.get("boots") or {}) if record.get("generation") == state.get("generation") else {} current = boot_ids(documents) @@ -846,18 +897,23 @@ def observe(directory, lock, record, state, *, invoke, api=None, tunnel=None): ranks = [{"rank": row["rank"], "host": row["host"], "running": None} for row in lock["site"]["ranks"]] else: ranks = probe_containers(lock, invoke=invoke) + adapter = engine_adapter.detect_engine(lock) + health_url = lock.get("health_url") or (lock.get("stock") or {}).get("health_url") or record.get("health_url") health = None if unreachable or ranks[0].get("running"): - url = record.get("api_url") - if not url: + url = record.get("api_url") or health_url + if not url and adapter.name != "generic": url = retained_source.apply(directory, "saved-status", cache=controller.STATE / "retained-sources")["api_url"] update(directory, api_url=url) - health = (api or api_health)(url) + probe = adapter.health_probe_spec(api_url=url, health_url=health_url, rank=0) + if probe.mode == "http" and (url or health_url): + health = _probe_api(api, url or health_url, adapter=adapter, health_url=health_url) boots = boot_ids(documents) baseline = (record.get("boots") or {}) if record.get("generation") == state.get("generation") else {} rebooted = [host for host in hosts if baseline.get(host) and boots.get(host) and baseline[host] != boots[host]] finding = assess(ranks, api=health, rebooted=rebooted, nodes=documents, tunnel=tunnel, require_mesh=len(hosts) == 4 and ring_of_four()) + finding["engine"] = adapter.name finding["boots"] = boots finding["telemetry"] = documents.get(hosts[0], {}).get("telemetry", {}).get(lock["id"]) return finding diff --git a/runtime/host/test_dashboard.py b/runtime/host/test_dashboard.py index 5bd8d19e..ae21f874 100644 --- a/runtime/host/test_dashboard.py +++ b/runtime/host/test_dashboard.py @@ -959,3 +959,76 @@ def test_the_quiet_command_holds_and_releases(tmp_path, capsys): assert dashboard.main(["quiet", "release", holder, "--quiet-file", str(quiet)]) == 0 assert json.loads(capsys.readouterr().out) == {"released": holder, "still_quiet": False} assert dashboard.main(["quiet", "hold", "--quiet-file", str(quiet)]) == 2 + + +def test_dashboard_renders_managed_sglang_and_generic_deployments_with_engine_metadata(tmp_path): + clock = Clock() + api = FakeAPI(clock) + api.models[(NODE_A_LAN, 30000)] = "DeepSeek-V4.1-SGLang" + original_open = api.open + + def sglang_no_metrics(request, timeout=None): + parts = urllib.request.urlparse(request.full_url) + if (parts.hostname, parts.port, parts.path) == (NODE_A_LAN, 30000, "/metrics"): + raise urllib.error.HTTPError(request.full_url, 404, "metrics disabled", {}, None) + return original_open(request, timeout=timeout) + + api.open = sglang_no_metrics + site_path = tmp_path / "site.json" + site_path.write_text(json.dumps({ + "schema": dashboard.SITE_SCHEMA, + "deployments": [ + { + "id": "sglang-on-0-3", "profile": "stock-sglang", "engine": "sglang", + "model": "DeepSeek-V4.1-SGLang", "positions": [0, 1, 2, 3], + "api_host": NODE_A_LAN, "api_port": 30000, "stopped": False, + "parallelism": {"tp": 4, "ep": 4}, + "containers": [{"position": p, "name": f"sr-sg-r{p}"} for p in range(4)], + }, + { + "id": "exl3-on-4-5", "profile": "stock-generic", "engine": "generic", + "model": "ExLlamaV3-Job", "positions": [4, 5], + "api_host": None, "api_port": None, "stopped": False, + "containers": [{"position": 4, "name": "sr-gen-r0"}, {"position": 5, "name": "sr-gen-r1"}], + }, + { + "id": "legacy-vllm-on-6-7", "profile": "qwen38-flash-next-tp2", + "model": "Qwen3.8-Flash-Next", "positions": [6, 7], + "api_host": "192.0.2.16", "api_port": 8000, "stopped": False, + "containers": [{"position": 6, "name": "sr-vllm-r0"}, {"position": 7, "name": "sr-vllm-r1"}], + }, + ], + }), encoding="utf-8") + api.models[("192.0.2.16", 8000)] = "Qwen3.8-Flash-Next" + + client = dashboard.ReadOnlyClient(opener=api) + found = dashboard.Collector( + [dashboard.Source(fabric_file(tmp_path), site_path)], client, + quiet_path=tmp_path / "quiet", node_status_path=None, recovery_path=None, clock=clock, + ) + found.mark_viewed() + found.cycle() + members = {m["id"].split(":", 1)[1]: m for m in found.snapshot()["groups"][0]["members"]} + assert set(members) == {"sglang-on-0-3", "exl3-on-4-5", "legacy-vllm-on-6-7"} + + # SGLang: serves cleanly via /v1/models fallback without polling /v1/sparkring/status. + sg = members["sglang-on-0-3"] + assert sg["engine"] == "sglang" and sg["engine_summary"]["badge"] == "SGLang" + assert sg["engine_summary"]["parallelism"]["summary"] == "TP4 / EP4" + assert sg["layout"]["label"] == "TP4 / EP4" and sg["layout"]["ep"] == 4 + assert sg["state"] == "serving" + sg_paths = [urllib.request.urlparse(r.full_url).path for r in api.requests if urllib.request.urlparse(r.full_url).port == 30000] + assert "/v1/sparkring/status" not in sg_paths and "/v1/models" in sg_paths + + # Generic process-only container: accepted without HTTP host/port, zero HTTP requests, Running label. + gen = members["exl3-on-4-5"] + assert gen["engine"] == "generic" and gen["engine_summary"]["badge"] == "Generic" + assert gen["engine_summary"]["api_kind"] == "process" + assert gen["engine_summary"]["parallelism"]["summary"] == "2 ranks" + assert gen["state"] == "serving" and gen["state_label"] == "Running" + assert gen["endpoint"] is None + + # Legacy vLLM site row without explicit "engine" defaults cleanly to vLLM. + vllm = members["legacy-vllm-on-6-7"] + assert vllm["engine"] == "vllm" and vllm["engine_summary"]["badge"] == "vLLM" + assert vllm["state"] == "serving" diff --git a/runtime/host/test_memory_settle.py b/runtime/host/test_memory_settle.py index b5609a2b..dd46d63c 100644 --- a/runtime/host/test_memory_settle.py +++ b/runtime/host/test_memory_settle.py @@ -192,3 +192,63 @@ def run(host, argv): said = [] assert REAL_SETTLE_MEMORY(tmp_path, run=run, say=said.append) == [] assert seen == {} and said == ["Memory settle skipped: this deployment's model already runs on every Spark."] + + +def test_sglang_memory_settle_reads_mem_fraction_static_and_refuses_short_sparks(): + cmd = ["python3", "-m", "sglang.launch_server", "--model-path", "/model", "--mem-fraction-static", "0.85"] + assert memory_settle.requested(cmd) == (0.85, None) + assert memory_settle.pinned_bytes(cmd) == 0 + + sparks = Sparks({"operator@192.0.2.10": [116 * GIB], "operator@192.0.2.11": [80 * GIB]}) + sleep, now = clock() + said = [] + with pytest.raises(memory_settle.MemoryShort) as refused: + memory_settle.settle(["operator@192.0.2.10", "operator@192.0.2.11"], 0.85, run=sparks.run, sleep=sleep, + now=now, say=said.append, engine="sglang") + assert "SGLang asks for 0.85 of the total" in said[0] + assert "SGLang" in str(refused.value) and "--mem-fraction-static" in str(refused.value) + assert "vLLM" not in str(refused.value) + + over = memory_settle.budget_problem([("gb10", round(121.69 * GIB))], 0.98, 0, engine="sglang") + assert over is not None and "SGLang's share" in over and "--mem-fraction-static" in over + + +def test_generic_container_settles_without_crashing_on_missing_vllm_flags(monkeypatch, tmp_path): + from runtime.common import installer + cmd = ["python3", "-m", "exllamav3.server", "--model", "/model", "--tp", "2"] + assert memory_settle.requested(cmd, engine="generic") == (None, None) + assert memory_settle.pinned_bytes(cmd, engine="generic") == 0 + + calls = [] + said = [] + rows = memory_settle.settle( + ["operator@192.0.2.10", "operator@192.0.2.11"], None, + run=lambda host, argv: calls.append((host, argv)) or "", + say=said.append, engine="generic", + ) + assert rows == [] and calls == [] + assert any("Memory settle skipped" in line for line in said) + + # End-to-end through install_workflow.settle_memory for SGLang and generic locks. + sglang_lock = {"backend": "compose", "engine": "sglang", + "site": {"name": "sg-pair", "ranks": [{"rank": 0, "host": "operator@192.0.2.10"}]}} + monkeypatch.setattr(installer, "load", lambda directory: sglang_lock) + monkeypatch.setattr(installer, "specifications", lambda value, only_rank=None: [ + SimpleNamespace(command=("python3", "-m", "sglang.launch_server", "--mem-fraction-static=0.82"), + environment={"SGLANG_NCCL_SO_PATH": "/opt/sparkring/libsircl/lib/libsircl.so.0.6.0"})]) + seen = {} + + def fake_settle(hosts, utilization, **kwargs): + seen.update(hosts=hosts, utilization=utilization, contract=kwargs.get("contract")) + return [] + monkeypatch.setattr(memory_settle, "settle", fake_settle) + REAL_SETTLE_MEMORY(tmp_path, run=lambda host, argv: "") + assert seen["utilization"] == 0.82 and seen["contract"].engine == "sglang" + + generic_lock = {"backend": "compose", "engine": "generic", + "site": {"name": "gen-pair", "ranks": [{"rank": 0, "host": "operator@192.0.2.10"}]}} + monkeypatch.setattr(installer, "load", lambda directory: generic_lock) + monkeypatch.setattr(installer, "specifications", lambda value, only_rank=None: [ + SimpleNamespace(command=tuple(cmd), environment={})]) + REAL_SETTLE_MEMORY(tmp_path, run=lambda host, argv: "") + assert seen["utilization"] is None and seen["contract"].engine == "generic" and not seen["contract"].drop_caches diff --git a/runtime/host/test_recovery.py b/runtime/host/test_recovery.py index d4b94768..64f539bf 100644 --- a/runtime/host/test_recovery.py +++ b/runtime/host/test_recovery.py @@ -991,3 +991,110 @@ def hairpin_problem(slot=None): assert result["state"] == "report" assert result["finding"]["state"] == "hairpin" assert result["finding"]["next_action"] == "on Node A: sudo sparkring hairpin" + + +def test_api_health_supports_sglang_dead_signatures_and_health_generate_fallback(): + import io + + class Answer: + def __init__(self, status=200, body=b""): + self.status = status + self._body = body + + def read(self, limit=-1): + return self._body[:limit] if limit >= 0 else self._body + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + # SGLang /health 503 with SchedulerDead triggers immediate dead classification. + def sg_dead(url, timeout): + raise urllib.error.HTTPError(url, 503, "Service Unavailable", {}, io.BytesIO(b"SchedulerDead: worker exited")) + dead = recovery.api_health("http://192.0.2.10:30000/v1", opener=sg_dead, engine="sglang") + assert dead["ok"] is False and dead["dead"] is True and "SGLang" in dead["error"] + + # SGLang /health 503 loading -> falls through to /health_generate -> TokenizerManager is dead triggers fatal crash. + probed = [] + + def sg_fallback_dead(url, timeout): + probed.append(url) + if url.endswith("/health"): + raise urllib.error.HTTPError(url, 503, "Service Unavailable", {}, io.BytesIO(b"loading weights")) + raise urllib.error.HTTPError(url, 500, "Internal Error", {}, io.BytesIO(b"TokenizerManager is dead")) + dead2 = recovery.api_health("http://192.0.2.10:30000/v1", opener=sg_fallback_dead, engine="sglang") + assert dead2["ok"] is False and dead2["dead"] is True + assert probed == ["http://192.0.2.10:30000/health", "http://192.0.2.10:30000/health_generate"] + + # SGLang /health 404 -> /health_generate 200 counts as healthy. + probed.clear() + + def sg_health_generate_ok(url, timeout): + probed.append(url) + if url.endswith("/health"): + raise urllib.error.HTTPError(url, 404, "Not Found", {}, io.BytesIO(b"")) + return Answer(200, b"ok") + ok = recovery.api_health("http://192.0.2.10:30000/v1", opener=sg_health_generate_ok, engine="sglang") + assert ok["ok"] is True and ok["dead"] is False + assert probed == ["http://192.0.2.10:30000/health", "http://192.0.2.10:30000/health_generate"] + + +def test_generic_container_recovery_uses_process_liveness_or_optional_health_url(tmp_path, monkeypatch): + import io + from runtime.host import discovery, placement + + # Process-only generic container: api_health never opens HTTP connections. + def fail_opener(url, timeout): + raise AssertionError(f"generic process-only container must not send HTTP probes: {url}") + proc = recovery.api_health(None, opener=fail_opener, engine="generic") + assert proc == {"ok": True, "status": None, "dead": False, "error": None} + + # Generic container with custom health_url: 503 is NOT fatal (no false vLLM EngineDeadError restart). + seen_urls = [] + + def generic_503(url, timeout): + seen_urls.append(url) + raise urllib.error.HTTPError(url, 503, "Service Unavailable", {}, io.BytesIO(b"")) + res = recovery.api_health(None, opener=generic_503, engine="generic", health_url="http://192.0.2.10:9090/ready") + assert res["ok"] is False and res["dead"] is False and seen_urls == ["http://192.0.2.10:9090/ready"] + + # Full recovery.check() on a process-only generic deployment: running containers -> serving with zero HTTP probes; + # stopped worker -> partial -> restarts cleanly. + monkeypatch.setattr(controller, "STATE", tmp_path / "state") + value = cluster(2) + node.save(controller.STATE, "cluster.json", value) + hosts = [host["host"] for host in value["plan"]["spec"]["hosts"]] + directory = tmp_path / "state" / "deployments" / "exl3" + lock = { + "id": "g" * 64, "backend": "compose", "engine": "generic", + "selection": {"profile": "stock-generic", "target_variant": None, "model_repository": None, + "model_revision": None, "release": "stock-generic"}, + "site": {"name": "exl3", "ranks": [{"rank": r, "host": h} for r, h in enumerate(hosts)]}, + } + installer.write(directory / "deployment.lock.json", lock) + installer.write(directory / "state.json", {"generation": 1, "operation": "up", "complete": True}) + placement.record(controller.STATE, None, directory) + sparks = Sparks(hosts) + sparks.running.update({0: True, 1: True}) + monkeypatch.setattr(discovery, "ssh", sparks.ssh) + monkeypatch.setattr(recovery, "api_health", lambda *a, **kw: pytest.fail("process-only generic must not call api_health")) + clock = Clock() + res_serving = recovery.check(now=clock, tunnel={}) + assert res_serving["state"] == "serving" + + # status_assessment also skips HTTP probing for process-only generic deployments. + dep = {"engine": "generic", "state": {"generation": 1, "operation": "up", "complete": True}, + "api_url": None, "observations": [{"host": h, "result": sparks.observation(r)} for r, h in enumerate(hosts)]} + assessed = recovery.status_assessment(dep, [], {}, tunnel={}) + assert assessed["state"] == "serving" + + # When a worker container stops, recovery detects partial and restarts cleanly. + sparks.running[1] = False + applied = [] + assert recovery.check(now=clock, apply=applied.append, tunnel={})["state"] == "confirming" + clock.advance(60) + monkeypatch.setenv("SPARKRING_LOG_DIR", str(tmp_path / "logs")) + recovery.check(now=clock, apply=applied.append, tunnel={}) + assert applied == ["down", "up"] diff --git a/runtime/host/test_stock_install.py b/runtime/host/test_stock_install.py index 4a606afb..960c216e 100644 --- a/runtime/host/test_stock_install.py +++ b/runtime/host/test_stock_install.py @@ -197,3 +197,113 @@ def test_an_sglang_stock_image_plan_writes_launch_server_compose_files(stock, ca assert "Off: SGLang's custom all-reduce, so PyNccl carries the device collectives;" in out.err assert "vLLM" not in out.err + +def test_engine_generic_plan_and_execute_through_engine_adapter(stock, capsys, monkeypatch): + value, _ = stock + wheel_nccl = "/usr/local/lib/python3.12/dist-packages/nvidia/nccl/lib/libnccl.so.2" + hosts = [host["host"] for host in installer.read(controller.STATE / "cluster.json")["plan"]["spec"]["hosts"]] + generic_found = facts(**{"torch.nccl_libraries": [wheel_nccl]}) + generic_found["vllm"] = None + generic_found["sglang"] = None + generic_bind = {"global_provider": TARGET, "torch_provider": TARGET, "torch_runtime_nccl_version": 22705, + "torch_nccl_version": [2, 27, 5], "mapped": [TARGET]} + + ssh_calls = [] + + def generic_ssh(host, argv, *, data=None, **options): + ssh_calls.append((host, list(argv), data)) + if argv[:5] == ["sudo", "-n", "docker", "image", "inspect"]: + return json.dumps([image(entrypoint=())]) + if argv[0] == "sha256sum": + return f"{'b' * 64} {argv[1]}\n" + if argv[:4] == ["sudo", "-n", "docker", "run"]: + if "--binding" in argv: + assert not any(a.startswith(("VLLM_NCCL_SO_PATH=", "SGLANG_NCCL_SO_PATH=")) for a in argv) + return "STOCK-IMAGE-PROBE " + json.dumps(generic_bind) + "\n" + return "STOCK-IMAGE-PROBE " + json.dumps(generic_found) + "\n" + if argv[:2] == ["sh", "-c"] and "inspect" in argv[2]: + return "" + return "ok\n" + + monkeypatch.setattr(flow.discovery, "ssh", generic_ssh) + user_cmd = ["python3", "-m", "exllamav3.server", "--model", "/model", "--tp", "2"] + + # 1. --plan with --engine generic (no --model-path required) writes lock + compose with zero vLLM/SGLang flags. + assert sparkring.main([ + "install", "--image", REFERENCE, "--transport", "libsircl", "--engine", "generic", + "--libsircl-library", LIBRARY, "--plan", "--json", "--", *user_cmd, + ]) == 0 + out = capsys.readouterr() + planned = json.loads(out.out) + assert planned["state"] == "planned" and planned["engine"] == "generic" + assert planned["api_url"] is None and planned["health_probe"] == {"mode": "process", "endpoints": []} + assert planned["dashboard_summary"]["engine"] == "generic" + directory = Path(planned["directory"]["node_a"]) + lock = installer.read(directory / "deployment.lock.json") + assert lock["engine"] == "generic" + service0 = yaml.safe_load((directory / "compose.rank0.yaml").read_text())["services"]["model"] + assert service0["command"] == user_cmd + assert service0["environment"]["LD_PRELOAD"] == TARGET + assert not any(k.startswith(("VLLM_", "SGLANG_")) for k in service0["environment"]) + + # 2. --yes execution with --engine generic and --health-url distributes compose & starts workers before rank 0. + ssh_calls.clear() + assert sparkring.main([ + "install", "--image", REFERENCE, "--transport", "libsircl", "--engine", "generic", + "--health-url", "http://192.0.2.20:9090/healthz", + "--libsircl-library", LIBRARY, "--yes", "--json", "--", *user_cmd, + ]) == 0 + executed = json.loads(capsys.readouterr().out) + assert executed["state"] == "complete" and executed["engine"] == "generic" + assert executed["health_url"] == "http://192.0.2.20:9090/healthz" + assert executed["health_probe"] == {"mode": "http", "endpoints": ["http://192.0.2.20:9090/healthz"]} + up_calls = [(h, argv) for h, argv, _ in ssh_calls if argv[:4] == ["sudo", "-n", "docker", "compose"] and "up" in argv] + assert [h for h, _ in up_calls] == [hosts[1], hosts[0]] + assert json.loads((Path(executed["directory"]["node_a"]) / "state.json").read_text())["complete"] is True + + +def test_engine_sglang_execute_runs_memory_settle_and_refuses_bad_parallelism(stock, capsys, monkeypatch): + hosts = [host["host"] for host in installer.read(controller.STATE / "cluster.json")["plan"]["spec"]["hosts"]] + wheel_nccl = "/opt/sglang/lib/python3.12/site-packages/nvidia/nccl/lib/libnccl.so.2" + sg_facts = sglang_facts(**{"torch.nccl_libraries": [wheel_nccl]}) + ssh_calls = [] + + def sg_ssh(host, argv, *, data=None, **options): + ssh_calls.append((host, list(argv), data)) + if argv[:5] == ["sudo", "-n", "docker", "image", "inspect"]: + return json.dumps([image()]) + if argv[0] == "sha256sum": + return f"{'b' * 64} {argv[1]}\n" + if argv[:4] == ["sudo", "-n", "docker", "run"]: + if "--binding" in argv: + return "STOCK-IMAGE-PROBE " + json.dumps(sglang_binding()) + "\n" + return "STOCK-IMAGE-PROBE " + json.dumps(sg_facts) + "\n" + return "ok\n" + + monkeypatch.setattr(flow.discovery, "ssh", sg_ssh) + + # Fail-closed parallelism refusal before any mutation when --ep-size exceeds group width. + assert sparkring.main([ + "install", "--image", SGLANG_REFERENCE, "--transport", "libsircl", "--engine", "sglang", + "--libsircl-library", LIBRARY, "--model-path", "/srv/models/m", "--yes", "--json", + "--", "--ep-size", "4", + ]) == 3 + refused = json.loads(capsys.readouterr().out) + assert refused["field"] == "image" and "expert parallelism 4" in refused["message"] + assert not any(argv[:4] == ["sudo", "-n", "docker", "compose"] for _, argv, _ in ssh_calls) + + # Valid SGLang --engine sglang --yes executes settle_memory + compose up workers then rank 0. + settled = [] + monkeypatch.setattr(flow, "settle_memory", lambda directory, **kw: settled.append(Path(directory)) or []) + ssh_calls.clear() + assert sparkring.main([ + "install", "--image", SGLANG_REFERENCE, "--transport", "libsircl", "--engine", "sglang", + "--libsircl-library", LIBRARY, "--model-path", "/srv/models/m", "--yes", "--json", + "--", "--mem-fraction-static", "0.85", + ]) == 0 + done = json.loads(capsys.readouterr().out) + assert done["state"] == "complete" and done["engine"] == "sglang" + assert len(settled) == 1 + up_calls = [(h, argv) for h, argv, _ in ssh_calls if argv[:4] == ["sudo", "-n", "docker", "compose"] and "up" in argv] + assert [h for h, _ in up_calls] == [hosts[1], hosts[0]] +