From 6d66e2121d665cc85aebfee8c11e1f03774a8f24 Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:15:48 -0600 Subject: [PATCH 1/2] Modularize dashboard.py into focused runtime/host modules and decouple CPU helpers --- runtime/host/dashboard.py | 2468 +-------------------------- runtime/host/dashboard_client.py | 131 ++ runtime/host/dashboard_collector.py | 1029 +++++++++++ runtime/host/dashboard_parsers.py | 353 ++++ runtime/host/dashboard_quiet.py | 156 ++ runtime/host/dashboard_server.py | 302 ++++ runtime/host/dashboard_sources.py | 501 ++++++ runtime/host/host_load.py | 32 +- 8 files changed, 2592 insertions(+), 2380 deletions(-) create mode 100644 runtime/host/dashboard_client.py create mode 100644 runtime/host/dashboard_collector.py create mode 100644 runtime/host/dashboard_parsers.py create mode 100644 runtime/host/dashboard_quiet.py create mode 100644 runtime/host/dashboard_server.py create mode 100644 runtime/host/dashboard_sources.py diff --git a/runtime/host/dashboard.py b/runtime/host/dashboard.py index f7a47faf..6a534187 100644 --- a/runtime/host/dashboard.py +++ b/runtime/host/dashboard.py @@ -1,2408 +1,120 @@ """``sparkring dashboard``: a read-only web page of one or more SparkRing fabrics and the models they serve. -Status: Experimental. Covered by offline tests only; no ring has run it. - -The page shows each fabric's ring of Sparks with the arc every model serves -from, and per model its state, output tokens per second, requests, KV cache -use and budget, draft acceptance, first-token time, prefix-cache hits, -serving settings, collective transport, image and per-Spark memory and disk. -``sparkring dashboard tui`` (``runtime.host.dashboard_tui``) shows the same -status document in a terminal, read from this service. - -Where its data comes from -------------------------- - -- Host files. The fabric document and the site file are compared every - one-second cycle by device, inode, modification time and size, and re-read - when any of them changed, so a site file that ``export`` replaces is shown - within a second. SIGHUP (``systemctl reload sparkring-dashboard``) re-reads - them at the next cycle whatever their stamps say. The host-agent status and - the recovery record are re-read every FILES_SECONDS: - - - the fabric document (``sparkring-fabric/v1``, ``runtime.common.fabric_document``) - for the Sparks, their positions, hostnames and management addresses; - - the site file (``sparkring-dashboard-site/v1``, SITE_PATH) that - ``sudo sparkring dashboard export`` writes on Node A from the controller's - deployment records: each deployment's profile, served model name, positions, - API address and port and container names. The controller's records are - readable by root only; the site file holds only these fields, so the - dashboard needs no privilege; - - this Spark's host-agent status (``sparkring-node-status/v1``, - ``/run/sparkring/status.json``) and the recovery timer's public cache of - every Spark's agent facts (``sparkring-dashboard-nodes/v1``, NODE_REPORTS_PATH); - - on Node A, the recovery timer's latest finding per deployment - (``sparkring-recovery/v1``, RECOVERY_PATH), which it writes about once a - minute while a model is active. - -- HTTP GET requests to each deployment's API, through ``ReadOnlyClient``: - - - ``/metrics`` every METRICS_VIEWED_SECONDS while a browser or the terminal - view shows the status (it fetched ``/api/status`` within VIEWER_SECONDS; - ``/api/status?viewer=passive`` does not count); no API reads otherwise. The vllm:cache_config_info gauge gives the - KV cache budget; - - ``/v1/models`` every MODELS_SECONDS while the model serves, for its served - name and context length. A failed metrics read tells the states apart: a - refused connection is a stopped model, a timeout an unreachable Spark and an - HTTP error a model still starting; a silent API is asked every FAILED_SECONDS; - - ``/v1/sparkring/status`` (the runtime-status plugin) once per model run. - Each uncached request makes the plugin ask every worker for a report - through the engine's control path, which runs between decode steps, so it - is never polled. ``/api/refresh?model=ID`` asks for one more, at most once - per RUNTIME_REFRESH_SECONDS per model. - -Invariants ----------- - -- ``ReadOnlyClient.get`` is the only network request this module makes. It - sends GET without a body, only to READ_PATHS, only to addresses the host - files name. Inference paths such as ``/v1/chat/completions`` and - ``/v1/completions`` are refused before a connection is opened. -- The module starts no process: no SSH, no ``docker``, no ``ping``. Log - viewing is on demand by the operator: the page shows the command that - prints a model's log, and the operator runs it. Startup progress comes from - bounded log reads in the viewer-leased host-agent channel, never this service. -- While quiet mode is held, no request is sent at all, from the next - one-second cycle on, for measurements that must see no outside traffic. An - operator holds it with the quiet file (QUIET_PATH, ``sparkring dashboard quiet - on``); a measurement holds it with a holder file of its own - (``quiet hold``/``quiet release``), so measurements that overlap, or an - operator's hold, never end each other's. A holder lapses when its process has - exited or after its time to live. -- The service lowers its own priority (``lower_priority``): idle CPU - scheduling, nice 19 and, on a Spark, the CPUs outside the fastest class as - SIRCL's classifier finds them (the Cortex-A725 cores of a GB10), so serving - processes and SIRCL's threads on the performance cores are never displaced. - It writes no file; ``export`` and ``quiet``, run by an operator, each write one. -- It listens on Node A's LAN address and on 127.0.0.1 (``listen_addresses``), - never on a fabric or administration address. Loopback serves programs on - Node A itself, such as ``curl http://127.0.0.1:8090/api/status`` and the - terminal view, without the LAN address that setup recorded; every program - there can reach the LAN address too, so it widens nothing. +Public facade and CLI entry point. The implementation is split across focused +sibling modules so each concern stays small and testable while external callers +and tests continue to import from ``runtime.host.dashboard``: + +- ``dashboard_client``: single GET-only HTTP egress client (``ReadOnlyClient``) +- ``dashboard_parsers``: pure Prometheus / Flare / runtime-status parsers +- ``dashboard_sources``: read-only host file, external endpoint, and unmanaged-container discovery +- ``dashboard_collector``: periodic snapshot collector and bounded ``HistoryStore`` +- ``dashboard_quiet``: quiet-mode holds and low-priority efficiency-core placement +- ``dashboard_server``: HTTP server, Basic Auth, loopback/LAN bind guard, and SHA-256 CSP page assembly """ from __future__ import annotations import argparse -import base64 -import collections -from concurrent.futures import ThreadPoolExecutor -from functools import lru_cache -import gzip -import hashlib import hmac -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -import ipaddress -import json +from http.server import ThreadingHTTPServer import os from pathlib import Path -import re -import signal -import shlex -import socket import sys -import threading import time -import urllib.error -import urllib.parse -import urllib.request - -from runtime.common.transport_names import collective_name -from runtime.common import engine_adapter, serving, thinking -from runtime.host.dashboard_rates import number, plugin_fresh -from runtime.host import startup - -SCHEMA = "sparkring-dashboard/v1" -SITE_SCHEMA = "sparkring-dashboard-site/v1" -SITE_PATH = Path("/var/lib/sparkring/dashboard/site.json") -# Endpoints served outside the installer (sparkring dashboard external): read-only cards. -EXTERNAL_PATH = Path("/var/lib/sparkring/dashboard/external.json") -EXTERNAL_SCHEMA = "sparkring-dashboard-external/v1" -EXTERNAL_KINDS = ("flare", "openai") -EXTERNAL_ID_RE = re.compile(r"[a-z0-9][a-z0-9-]{0,39}") -FABRIC_PATH = Path("/etc/sparkring/fabric/topology.json") -NODE_STATUS_PATH = Path("/run/sparkring/status.json") -NODE_REPORTS_PATH = Path("/var/lib/sparkring/dashboard/nodes.json") -RECOVERY_PATH = Path("/var/lib/sparkring/recovery.json") -QUIET_PATH = Path("/run/sparkring/dashboard.quiet") -# One file per measurement that holds quiet mode, beside QUIET_PATH (quiet_holders_directory). -QUIET_HOLDERS = "dashboard-quiet" -QUIET_SCHEMA = "sparkring-dashboard-quiet/v1" -QUIET_TTL_SECONDS = 12 * 3600 -QUIET_LABEL_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,39}") -PAGE = Path(__file__).with_name("dashboard.html") - -# The only paths the collector requests: the model list, vLLM's Prometheus metrics and the -# runtime-status plugin's JSON report. Each is a GET that runs no model. -READ_PATHS = frozenset({"/metrics", "/v1/models", "/v1/sparkring/status"}) -READ_ACCEPT = {"/metrics": "text/plain", "/v1/models": "application/json", - "/v1/sparkring/status": "application/json"} -METRICS_VIEWED_SECONDS = 2.0 -HISTORY_SECONDS = 3 * 3600 -HISTORY_SAMPLES = 2161 -HISTORY_SPACING = 5.0 -HISTORY_DEPLOYMENTS = 8 -HISTORY_DELTA_SAMPLES = 120 -HISTORY_VALUES = ("gen", "prompt", "accepted", "drafts", "draft_tokens", "steps", "ttft_sum", "ttft_count", - "pc_hits", "pc_queries", "step_seconds", "step_accepted", "running", "waiting", "kv") -MODELS_SECONDS = 60.0 -VIEWER_SECONDS = 6.0 -FILES_SECONDS = 30.0 -RUNTIME_REFRESH_SECONDS = 300.0 -HTTP_TIMEOUT = 2.0 -FAILED_SECONDS = 15.0 # a model API that does not answer is asked again after this long -MAX_RESPONSE_BYTES = 8 * 1024 * 1024 -MAX_FILE_BYTES = 1024 * 1024 -MAX_EVENTS = 200 -CLOCK_STEP_SECONDS = 2.0 # a cycle whose clock reads this much earlier than the last one's saw a step back -DEFAULT_PORT = 8090 -LOG_LINES = 40 -COUNTERS = { - "vllm:generation_tokens_total": "gen", - "vllm:prompt_tokens_total": "prompt", - "vllm:spec_decode_num_accepted_tokens_total": "accepted", - "vllm:spec_decode_num_drafts_total": "drafts", - "vllm:spec_decode_num_draft_tokens_total": "draft_tokens", - "vllm:num_preemptions_total": "preemptions", - "vllm:time_to_first_token_seconds_sum": "ttft_sum", - "vllm:time_to_first_token_seconds_count": "ttft_count", - "vllm:prefix_cache_queries_total": "pc_queries", - "vllm:prefix_cache_hits_total": "pc_hits", - "sglang:generation_tokens_total": "gen", - "sglang:prompt_tokens_total": "prompt", - "sglang:time_to_first_token_seconds_sum": "ttft_sum", - "sglang:time_to_first_token_seconds_count": "ttft_count", -} -SETTING_KEYS = ( - "tensor_parallel_size", "decode_context_parallel_size", "max_model_len", "max_num_seqs", "max_num_batched_tokens", - "cache_dtype", "quantization", "speculative_method", "num_speculative_tokens", - "reasoning_parser", "tool_call_parser", "default_chat_template_kwargs", - "kv_cache_memory_bytes", "prefix_caching_enabled", +from runtime.common import thinking +from runtime.host import dashboard_server as _server +from runtime.host.dashboard_client import ( + HTTP_TIMEOUT, MAX_RESPONSE_BYTES, READ_ACCEPT, READ_PATHS, + Fetched, NoRedirect, ReadOnlyClient, RequestRefused, _failure_kind, request_url, +) +from runtime.host.dashboard_collector import ( + CLOCK_STEP_SECONDS, FAILED_SECONDS, FILES_SECONDS, HISTORY_DELTA_SAMPLES, HISTORY_DEPLOYMENTS, + HISTORY_SAMPLES, HISTORY_SECONDS, HISTORY_SPACING, HISTORY_VALUES, MAX_EVENTS, + METRICS_VIEWED_SECONDS, MODELS_SECONDS, NODE_REPORTS_PATH, NODE_STATUS_PATH, RECOVERY_PATH, + RUNTIME_REFRESH_SECONDS, SCHEMA, VIEWER_SECONDS, Collector, External, HistoryStore, Model, +) +from runtime.host.dashboard_parsers import ( + COUNTERS, FLARE_COUNTERS, FLARE_GAUGES, FLARE_JSON_KEYS, FLARE_METRICS_PROBLEM, FLARE_SERIES, + LABEL_ESCAPE_RE, LABEL_RE, LABELS, MODEL_TAIL_WORDS, SETTING_KEYS, + capacity_from_cache_info, known, layout_label, parse_flare_as_metrics, parse_flare_metrics, + parse_labels, parse_metrics, read_runtime_status, read_transport, run_name, short_model, +) +from runtime.host.dashboard_quiet import ( + QUIET_HOLDERS, QUIET_LABEL_RE, QUIET_PATH, QUIET_SCHEMA, QUIET_TTL_SECONDS, + _process_alive, efficiency_cpus, lower_priority, quiet, quiet_hold, quiet_holders_directory, + quiet_release, quiet_state, +) +from runtime.host.dashboard_server import ( + DEFAULT_PORT, PAGE, default_bind, host_allowed, is_loopback_bind, + listen_addresses, make_handler, open_servers, page_bytes, reload_on_hangup, url_of, +) +from runtime.host.dashboard_sources import ( + CONTAINER_RE, EXTERNAL_ID_RE, EXTERNAL_KINDS, EXTERNAL_PATH, EXTERNAL_SCHEMA, FABRIC_PATH, + HOSTNAME_RE, LOG_LINES, MAX_FILE_BYTES, SITE_PATH, SITE_SCHEMA, Source, _ip, + chat_defaults, deployments_from_site, external_rows, fabric_from_document, log_commands, + parallelism, read_external, read_json, recovery_findings, rendezvous_head, + spark_cached_details, start_command, thinking_line, thinking_record, thinking_state, + unmanaged_groups, ) -LABELS = {"busy": "Busy: API unavailable", "serving": "Serving", "not_ready": "Not ready", "stopped": "No model running", - "offline": "Offline", "idle": "Idle", None: "Checking", - "installing": "Installing", "starting": "Starting", "loading": "Loading weights", - "compiling": "Compiling", "tuning": "Tuning B12X", "graphs": "Capturing CUDA graphs", "failed": "Failed"} -MODEL_TAIL_WORDS = {"csf", "nvfp4", "fp8", "fp4", "mxfp8", "mxfp4", "int4", "int8", "awq", "gptq", "bf16", - "fp16", "qad", "spark", "attention", "gguf", "nf3", "exl3"} -LABEL_RE = re.compile(r'([A-Za-z_][A-Za-z0-9_]*)="((?:[^"\\]|\\.)*)"') -LABEL_ESCAPE_RE = re.compile(r"\\(.)") -CONTAINER_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}") -HOSTNAME_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9-]{1,63})*") - - -# -- the one network client --------------------------------------------------------------- -class RequestRefused(ValueError): - """A request the dashboard must never send: not a GET, not a read path, or not a known address.""" - - -def request_url(host, port, path, allowed_hosts) -> str: - """The URL of one permitted read; RequestRefused for anything else. - - `path` must be exactly one of READ_PATHS (no query, no other path), `host` one of - `allowed_hosts` (the addresses the host files name) and `port` a TCP port.""" - if path not in READ_PATHS: - raise RequestRefused(f"the dashboard reads only {', '.join(sorted(READ_PATHS))}, not {path!r}") - if host not in allowed_hosts: - raise RequestRefused(f"{host!r} is not an address the fabric document or site file names") - if type(port) is not int or not 0 < port < 65536: - raise RequestRefused(f"{port!r} is not a TCP port") - literal = f"[{host}]" if ":" in host else host - return f"http://{literal}:{port}{path}" - - -class Fetched: - """The outcome of one read: `body` on success, else `failure` (refused, timeout, unreachable, - http) with `code` for an HTTP error status.""" - - def __init__(self, body=None, failure=None, code=None): - self.body, self.failure, self.code = body, failure, code - - @property - def ok(self) -> bool: - return self.failure is None - - -class NoRedirect(urllib.request.HTTPRedirectHandler): - """A read endpoint cannot widen the permitted address, port or path by redirecting.""" - - def redirect_request(self, request, fp, code, message, headers, newurl): - return None - - -class ReadOnlyClient: - """Sends the collector's GET requests and counts them; the module's only network egress. - - `opener` is a urllib opener; the default ignores proxy settings from the environment, so - requests to Spark addresses never leave through a proxy.""" - - def __init__(self, opener=None, timeout=HTTP_TIMEOUT): - self.opener = opener or urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) - self.timeout = timeout - self.allowed: frozenset = frozenset() - self.lock = threading.Lock() - self.requests = collections.Counter() # path -> requests sent - self.received = 0 # response bytes - - def allow(self, hosts) -> None: - self.allowed = frozenset(hosts) - - def get(self, host, port, path) -> Fetched: - url = request_url(host, port, path, self.allowed) - request = urllib.request.Request(url, method="GET", headers={ - "User-Agent": "sparkring-dashboard", "Accept": READ_ACCEPT[path]}) - if request.get_method() != "GET" or request.data is not None: - raise RequestRefused("the dashboard sends GET requests without a body only") - with self.lock: - self.requests[path] += 1 - try: - with self.opener.open(request, timeout=self.timeout) as response: - deadline = time.monotonic() + self.timeout - chunks, size = [], 0 - # read1 performs at most one underlying socket read. A peer that - # drips bytes cannot keep an unbounded read() alive indefinitely. - while size <= MAX_RESPONSE_BYTES: - if time.monotonic() >= deadline: - raise TimeoutError("metrics response deadline exceeded") - chunk = response.read1(min(65536, MAX_RESPONSE_BYTES + 1 - size)) - if not chunk: - break - chunks.append(chunk) - size += len(chunk) - body = b"".join(chunks) - except urllib.error.HTTPError as error: - return Fetched(failure="http", code=error.code) - except urllib.error.URLError as error: - return Fetched(failure=_failure_kind(error.reason)) - except (TimeoutError, socket.timeout): - return Fetched(failure="timeout") - except OSError as error: - return Fetched(failure=_failure_kind(error)) - with self.lock: - self.received += len(body) - if len(body) > MAX_RESPONSE_BYTES: - return Fetched(failure="too_large") - return Fetched(body=body) - - def counters(self) -> dict: - with self.lock: - return {"requests": dict(self.requests), "received_bytes": self.received} - - -def _failure_kind(reason) -> str: - if isinstance(reason, ConnectionRefusedError): - return "refused" - if isinstance(reason, (TimeoutError, socket.timeout)): - return "timeout" - return "unreachable" - - -# -- parsers -------------------------------------------------------------------------------- -def parse_labels(text: str) -> dict: - """'a="x",b="y"' -> {"a": "x", "b": "y"}, with the exposition format's escapes undone.""" - return {key: LABEL_ESCAPE_RE.sub(lambda m: "\n" if m.group(1) == "n" else m.group(1), value) - for key, value in LABEL_RE.findall(text)} - - -def parse_metrics(text: str) -> dict: - """Serving-engine series the page uses, summed across engines; KV use takes the maximum. - - `cache_info` holds the first engine's vllm:cache_config_info labels; `model_name` the - model_name label of the first vLLM series; `started` the API process's - process_start_time_seconds, which identifies one model run.""" - out: dict = {"finished": {}, "cache_info": None, "model_name": None, "started": None} - kv = None - for line in text.splitlines(): - if not line or line[0] == "#": - continue - brace = line.find("{") - if brace != -1: - end = line.rfind("}") - if end < brace: - continue - name, labels, rest = line[:brace], line[brace + 1:end], line[end + 1:] - else: - name, _, rest = line.partition(" ") - labels = "" - if name == "vllm:cache_config_info": - if out["cache_info"] is None: - out["cache_info"] = parse_labels(labels) - continue - parts = rest.split() - if not parts: - continue - try: - value = float(parts[0]) - except ValueError: - continue - if out["model_name"] is None and name.startswith(("vllm:", "sglang:")) and 'model_name="' in labels: - out["model_name"] = parse_labels(labels).get("model_name") - if name in COUNTERS: - key = COUNTERS[name] - out[key] = out.get(key, 0.0) + value - elif name in ("vllm:num_requests_running", "sglang:num_running_reqs"): - out["running"] = out.get("running", 0.0) + value - elif name in ("vllm:num_requests_waiting", "sglang:num_queue_reqs"): - out["waiting"] = out.get("waiting", 0.0) + value - elif name in ("vllm:kv_cache_usage_perc", "vllm:gpu_cache_usage_perc", "sglang:token_usage"): - kv = value if kv is None else max(kv, value) - elif name == "vllm:request_success_total": - reason = parse_labels(labels).get("finished_reason") or "other" - out["finished"][reason] = out["finished"].get(reason, 0.0) + value - elif name == "process_start_time_seconds": - out["started"] = value - out["kv"] = kv - return out - - -# Flare's /metrics series the external cards show (ghcr.io/local-inference-lab/flare). Gauges are read as -# they are; counters are read as they are and the generation counter also gives a rate between two reads. -FLARE_GAUGES = {"flare_active_requests": "active_requests", "flare_pending_requests": "pending_requests", - "flare_http_request_capacity": "request_capacity", "flare_uptime_seconds": "uptime_seconds", - "flare_generated_tokens_last_minute": "tokens_last_minute", "flare_total_kv_tokens": "kv_tokens_total", - "flare_free_kv_tokens": "kv_tokens_free", "flare_cached_kv_tokens": "kv_tokens_cached"} -FLARE_COUNTERS = {"flare_generated_tokens_total": "generated_tokens", "flare_prefill_tokens_total": "prefill_tokens", - "flare_requests_completed_total": "requests_completed", "flare_requests_failed_total": "requests_failed", - "flare_requests_cancelled_total": "requests_cancelled", - "flare_preemptions_total": "preemptions", - "flare_speculative_offered_drafts_total": "drafts_offered", - "flare_speculative_accepted_drafts_total": "drafts_accepted", - "flare_verification_draft_tokens_total": "draft_tokens", - "flare_engram_row_cache_hits_total": "row_cache_hits", "flare_engram_row_cache_misses_total": "row_cache_misses", - "flare_cache_lookups_total": "prefix_lookups", "flare_cache_hits_total": "prefix_hits", - "flare_http_requests_total": "http_requests"} -FLARE_SERIES = {**FLARE_GAUGES, **FLARE_COUNTERS} -# Helios JSON snapshots use field names rather than Prometheus series names. -FLARE_JSON_KEYS = {"flare_generated_tokens_total": "generated_tokens", - "flare_prefill_tokens_total": "prefill_tokens", - "flare_active_requests": "active", "flare_pending_requests": "pending", - "flare_requests_completed_total": "completed", "flare_requests_failed_total": "failed", - "flare_speculative_accepted_drafts_total": "accepted_drafts", - "flare_verification_draft_tokens_total": "verification_drafts"} -FLARE_METRICS_PROBLEM = "No recognized numeric Flare metrics in /metrics response." - - -def parse_flare_metrics(text: str) -> dict: - """Flare's Prometheus series or JSON snapshot mapped to the same short names. - - Labelled text series are summed over labels. Only recognized numeric JSON fields - are used; absent series stay absent, including fields that only the text API emits.""" - out: dict = {} - try: - document = json.loads(text) - except (ValueError, RecursionError): - pass - else: - if not isinstance(document, dict): - return out - for name, key in FLARE_SERIES.items(): - value = document.get(name, document.get(FLARE_JSON_KEYS.get(name))) - if number(value): - out[key] = value - page_tokens = document.get("page_tokens") - if number(page_tokens): - for field, series in (("total_pages", "flare_total_kv_tokens"), - ("free_pages", "flare_free_kv_tokens"), - ("cached_pages", "flare_cached_kv_tokens")): - pages = document.get(field) - if number(pages): - out.setdefault(FLARE_SERIES[series], pages * page_tokens) - return out - for line in text.splitlines(): - if not line or line[0] == "#": - continue - brace = line.find("{") - if brace != -1: - end = line.rfind("}") - if end < brace: - continue - name, rest = line[:brace], line[end + 1:] - else: - name, _, rest = line.partition(" ") - key = FLARE_SERIES.get(name) - if key is None: - continue - parts = rest.split() - if not parts: - continue - try: - value = float(parts[0]) - except ValueError: - continue - out[key] = out.get(key, 0.0) + value - return out - - -def parse_flare_as_metrics(text: str) -> dict: - """Flare's series in the shape the model cards and history already read. - - ``parse_metrics`` serves vLLM and SGLang; this adapter keeps Flare's own - names as separate series where they are useful and maps the shared - counters. ``started`` stays None: Flare publishes uptime but no start - time, and deriving one would split history on every restart. - """ - flare = parse_flare_metrics(text) - out: dict = {"finished": {}, "cache_info": None, "model_name": None, "started": None} - out["metrics_problem"] = None if flare else FLARE_METRICS_PROBLEM - for source, key in (("generated_tokens", "gen"), ("prefill_tokens", "prompt"), - ("drafts_accepted", "accepted"), ("drafts_offered", "drafts"), - ("draft_tokens", "draft_tokens"), ("prefix_hits", "pc_hits"), - ("prefix_lookups", "pc_queries"), ("preemptions", "preemptions")): - if source in flare: - out[key] = flare[source] - for source, key in (("active_requests", "running"), ("pending_requests", "waiting"), - ("request_capacity", "request_capacity"), ("uptime_seconds", "uptime_seconds"), - ("tokens_last_minute", "tokens_last_minute"), ("kv_tokens_total", "kv_tokens_total"), - ("kv_tokens_free", "kv_tokens_free"), ("kv_tokens_cached", "kv_tokens_cached")): - if source in flare: - out[key] = flare[source] - total, free = flare.get("kv_tokens_total"), flare.get("kv_tokens_free") - if total and free is not None: - out["kv"] = (total - free) / total - for source, key in (("requests_completed", "stop"), ("requests_failed", "error"), - ("requests_cancelled", "abort")): - if source in flare: - out["finished"][key] = flare[source] - return out - - -def read_external(path) -> list: - """The endpoints the file at ``path`` lists, validated; [] when the file is absent. - - The document is ``sparkring-dashboard-external/v1``: ``endpoints``, each with an ``id`` - (lowercase letters, digits and hyphens, at most 40 characters, distinct), a ``label`` (at most 80 - characters), a ``kind`` (``flare`` or ``openai``), a ``host`` (an IP address), a ``port`` and an - optional ``position``: the ring position of the Spark that serves it, which places the endpoint on - the ring figure among the ring's own models. Raises ValueError for a document that is not of that - form.""" - try: - document = read_json(Path(path)) - except FileNotFoundError: - return [] - return external_rows(document, path) - - -def external_rows(document, path="external list") -> list: - """The validated endpoints of an external-list ``document`` (read_external's rules); ``path`` names it in errors.""" - if not isinstance(document, dict) or document.get("schema") != EXTERNAL_SCHEMA: - raise ValueError(f"{path}: expected {EXTERNAL_SCHEMA}") - rows = document.get("endpoints") - if not isinstance(rows, list): - raise ValueError(f"{path}: endpoints must be a list") - out, seen = [], set() - for row in rows: - if not isinstance(row, dict): - raise ValueError(f"{path}: each endpoint is an object") - identifier = row.get("id") - if not isinstance(identifier, str) or not EXTERNAL_ID_RE.fullmatch(identifier) or identifier in seen: - raise ValueError(f"{path}: endpoint id {identifier!r} is not a distinct short lowercase name") - label = row.get("label") - if not isinstance(label, str) or not label.strip() or len(label) > 80: - raise ValueError(f"{path}: endpoint {identifier} needs a label of at most 80 characters") - kind = row.get("kind", "openai") - if kind not in EXTERNAL_KINDS: - raise ValueError(f"{path}: endpoint {identifier} kind must be one of {', '.join(EXTERNAL_KINDS)}") - host, port = row.get("host"), row.get("port") - if not isinstance(host, str) or not _ip(host): - raise ValueError(f"{path}: endpoint {identifier} host must be an IP address") - if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535: - raise ValueError(f"{path}: endpoint {identifier} port must be 1 to 65535") - entry = {"id": identifier, "label": label.strip(), "kind": kind, "host": host, "port": port} - position = row.get("position") - if position is not None: - if not isinstance(position, int) or isinstance(position, bool) or position < 0: - raise ValueError(f"{path}: endpoint {identifier} position must be a ring position, 0 or more") - entry["position"] = position - seen.add(identifier) - out.append(entry) - return out - - -def capacity_from_cache_info(info: dict | None) -> dict | None: - """The KV cache budget from vllm:cache_config_info, or None when the gauge lacks it. - - The gauge carries kv_cache_size_tokens, kv_cache_max_concurrency and kv_cache_memory_bytes, - the figures of the engine's "GPU KV cache size" startup line; no log needs to be read.""" - if not info: - return None - - def number(key, cast): - try: - return cast(info[key]) - except (KeyError, TypeError, ValueError): - return None # absent, or vLLM's "None" for an unset value - - tokens = number("kv_cache_size_tokens", int) - if tokens is None: - return None - return {"kv_tokens": tokens, "concurrency": number("kv_cache_max_concurrency", float), - "kv_bytes": number("kv_cache_memory_bytes", int), - "gpu_memory_utilization": number("gpu_memory_utilization", float), - "block_size": number("block_size", int), "max_num_seqs": None, "max_model_len": None, - "mm": None, "source": "metrics"} - - -def known(field): - return field.get("value") if isinstance(field, dict) and field.get("state") == "known" else None - - -def read_transport(doc: dict) -> dict | None: - """The transport of the TP group's collectives and the b12x bundle the image carries. - - runtime-status 0.3.6 and later report `tp_collective_transport` per worker; for older - images the label comes from the TP group's resident backend facts. `label` is the - transport's display name (``runtime.common.transport_names``). - - `bundle` (and its older alias `profile`) names the b12x RoCEnante bundle in the image, - whichever transport runs; `bundle_in_use` is True when RoCEnante carries the - collectives, False when another transport does and None when that is not known. The - page and the terminal view show the transport, never the bundle name.""" - backend = rocenante = nccl_available = nccl_disabled = collective = sircl_version = None - for rank in (doc.get("workers") or {}).get("ranks") or []: - transport = rank.get("transport") or {} - tp_group = (transport.get("groups") or {}).get("TP") or {} - backend = backend or known(tp_group.get("b12x_backend")) - if rocenante is None: - rocenante = known((tp_group.get("rocenante") or {}).get("enabled")) - nccl = tp_group.get("nccl") or {} - if nccl_available is None: - nccl_available = known(nccl.get("available")) - if nccl_disabled is None: - nccl_disabled = known(nccl.get("disabled")) - for effective in (rank.get("effective") or {}, transport.get("effective") or {}): - collective = collective or known(effective.get("tp_collective_transport")) - sircl_version = sircl_version or known(effective.get("tp_sircl_version")) - provenance = doc.get("provenance") or {} - bundle = known((provenance.get("b12x_comm_bundle") or {}).get("name")) or known(provenance.get("transport_profile")) - running = collective - if collective is None: - if isinstance(backend, str) and "sircl" in backend.lower(): - running = "sircl" - elif rocenante is True: - running = "rocenante" - elif not backend and nccl_available and not nccl_disabled: - running = "nccl" - label = collective_name(running) if running is not None else (str(backend) if backend else None) - if label is None and bundle is None: - return None - nccl_on = None if nccl_available is None and nccl_disabled is None else bool(nccl_available) and not nccl_disabled - in_use = None if running is None else running == "rocenante" - return {"label": label, "collective": collective, "sircl_version": sircl_version if collective == "sircl" else None, - "nccl": nccl_on, "bundle": bundle, "profile": bundle, "bundle_in_use": in_use, "source": "runtime"} - - -def read_runtime_status(doc: dict) -> dict: - """The fields of a sparkring-runtime-status/v1 document the page shows.""" - effective = doc.get("effective") or {} - arguments = (doc.get("configured") or {}).get("arguments") or {} - - def value(key): - found = known(effective.get(key)) - return known(arguments.get(key)) if found is None else found - - workers = doc.get("workers") or {} - nodes, image = [], None - for rank in workers.get("ranks") or []: - identity = rank.get("identity") or {} - image = image or known(identity.get("image_id")) - resources = rank.get("resources") or {} - memory = resources.get("memory") or {} - root = next((fs for fs in resources.get("filesystems") or [] if "/" in (fs.get("paths") or [])), {}) - nodes.append({"rank": known(identity.get("rank")), "node": resources.get("node"), - "memory_total": memory.get("total_bytes"), "memory_available": memory.get("available_bytes"), - "disk_total": root.get("total_bytes"), - "disk_available": root.get("available_bytes", root.get("free_bytes"))}) - started = doc.get("startup_snapshot_at_unix_ns") - return {"settings": {key: value(key) for key in SETTING_KEYS}, "nodes": nodes, - "workers": {"expected": workers.get("expected_count"), "received": workers.get("received_count")}, - "image": image.split(":")[-1][:12] if isinstance(image, str) else None, - "started_at": started / 1e9 if isinstance(started, (int, float)) else None, - "tp": value("tensor_parallel_size"), "dp": value("data_parallel_size"), - "pp": value("pipeline_parallel_size"), "transport": read_transport(doc)} - - -def short_model(model) -> str | None: - """Model family without its packaging tail: 'GLM-5.3-Flash-NVFP4-Spark-TP2' -> 'GLM-5.3-Flash'.""" - if not model: - return None - kept = [] - for part in str(model).split("/")[-1].split("-"): - low = part.lower() - if kept and (low in MODEL_TAIL_WORDS or re.fullmatch(r"(tp|dcp)\d+", low) or re.fullmatch(r"[\d.]+bpw", low)): - break - kept.append(part) - return "-".join(kept) or str(model) - - -def layout_label(size) -> str | None: - if not isinstance(size, int) or size < 1: - return None - return f"TP{size} {'ring' if size >= 4 else 'pair'}" - - -def run_name(positions) -> str: - """'tp4-7-2' for the arc 7, 0, 1, 2; the run naming the lab tooling and SIRCL use.""" - return f"tp{len(positions)}-{positions[0]}-{positions[-1]}" - - -# -- host files ------------------------------------------------------------------------------ -def read_json(path: Path): - """A small JSON host file, or raises OSError/ValueError.""" - with open(path, "rb") as stream: - data = stream.read(MAX_FILE_BYTES + 1) - if len(data) > MAX_FILE_BYTES: - raise ValueError(f"{path} is larger than {MAX_FILE_BYTES} bytes") - return json.loads(data.decode("utf-8")) - - -def fabric_from_document(document: dict) -> dict: - """The parts of a sparkring-fabric/v1 document the dashboard uses; ValueError when unusable. - - The full validator (runtime.common.fabric_document.validate) also checks every port and - cable. The dashboard retains cable address ownership to resolve repeated rendezvous - addresses without assuming that neighbouring containers belong to one model.""" - if not isinstance(document, dict) or document.get("schema") != "sparkring-fabric/v1": - raise ValueError("not a sparkring-fabric/v1 document") - size, positions, shape = document.get("size"), document.get("positions"), document.get("shape") - if shape not in ("cycle", "path", "pair") or not isinstance(size, int) or size < 2 \ - or not isinstance(positions, list) or len(positions) != size: - raise ValueError("the fabric document's shape, size and positions do not agree") - rows = [] - for index, row in enumerate(positions): - if not isinstance(row, dict) or row.get("position") != index: - raise ValueError(f"position {index} is missing or out of order") - hostname = row.get("hostname") - if not isinstance(hostname, str) or not HOSTNAME_RE.fullmatch(hostname): - raise ValueError(f"position {index} has no usable hostname") - address = (row.get("management") or {}).get("address") - addresses = [address, row.get("lan_address")] - for port in (row.get("ports") or {}).values(): - for function in (port.get("functions") or {}).values(): - addresses.append(str(function.get("address") or "").split("/")[0]) - neighbors = [] - for port in (row.get("ports") or {}).values(): - peer = port.get("peer") or {} - remote_position = peer.get("position") - if type(remote_position) is not int or not 0 <= remote_position < size: - continue - remote_port = (positions[remote_position].get("ports") or {}).get(str(peer.get("port")), {}) - for function in (remote_port.get("functions") or {}).values(): - remote_address = str(function.get("address") or "").split("/")[0] - if _ip(remote_address): - neighbors.append({"position": remote_position, "address": remote_address}) - rows.append({"position": index, "hostname": hostname, "node_id": row.get("node_id"), - "neighbors": neighbors, "ports": row.get("ports") or {}, - "addresses": [a for a in addresses if _ip(a)], - "address": address if _ip(address) else None, - "lan_address": row.get("lan_address") if _ip(row.get("lan_address")) else None}) - verified = document.get("verified") - return {"id": document.get("id") if isinstance(document.get("id"), str) else None, - "cluster": document.get("cluster") if isinstance(document.get("cluster"), str) else None, - "shape": shape, "closed": shape == "cycle", "size": size, "positions": rows, - "verified": verified.get("result") if isinstance(verified, dict) else None} - - -def spark_cached_details(document): - """Allow-listed optional node facts; never collect hardware data for the viewer.""" - gpu = document.get("gpu") or {} - gpu = {k: gpu[k] for k in ("memory_used_bytes", "memory_total_bytes", "temperature_c") - if isinstance(gpu, dict) and number(gpu.get(k)) and gpu[k] >= 0} - control = document.get("control") - links = document.get("links", control.get("peers", []) if isinstance(control, dict) else []) - links = links if isinstance(links, list) else [] - links = [{k: row[k][:128] if isinstance(row[k], str) else row[k] for k in ("netdev", "carrier", "operstate") - if isinstance(row.get(k), (str, bool))} for row in links[:16] if isinstance(row, dict)] - containers = document.get("containers") or [] - containers = containers if isinstance(containers, list) else [] - containers = [{k: row[k][:128] for k in ("name", "state", "health") if isinstance(row.get(k), str)} - for row in containers[:32] if isinstance(row, dict)] - return {"gpu": gpu, "links": links, "containers": containers} - - -def _ip(value) -> bool: - try: - ipaddress.ip_address(str(value)) - except ValueError: - return False - return True - - -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. 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 = [] - for row in site.get("deployments") or []: - if not isinstance(row, dict): - 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 - 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"])] - 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 - - -@lru_cache(maxsize=128) -def thinking_record(profile, checkpoint): - """Resolve shipped thinking records once per profile/checkpoint, without host access.""" - try: - return thinking.of(profile, checkpoint) - except (OSError, ValueError, KeyError): - return None - - -def chat_defaults(row, settings): - """Observed runtime kwargs take precedence over launch facts and saved settings, even when empty.""" - for source in (settings or {}, row.get("launch") or {}, row.get("settings") or {}): - value = source.get("default_chat_template_kwargs") - if isinstance(value, str): - try: - value = json.loads(value) - except ValueError: - continue - if isinstance(value, dict): - return value - return None - - -def thinking_state(row, settings): - """Effective thinking and provenance from observations, then saved/profile defaults.""" - unmanaged = row.get("unmanaged") - profile, checkpoint = row.get("profile"), row.get("checkpoint") - record = None if unmanaged or not isinstance(profile, str) or ( - checkpoint is not None and not isinstance(checkpoint, str)) else thinking_record(profile, checkpoint) - if not unmanaged and record is None: - return None - kwargs = chat_defaults(row, settings) - chosen = {} - enabled = False - if kwargs is None: - chosen = serving.effective(profile, row.get("serving"), checkpoint) if not unmanaged else {} - else: - off = record and record["off"] - enabled = bool(off) and all(kwargs.get(k) is True for k in off) - if (off and all(kwargs.get(k) == v for k, v in off.items()) - or (unmanaged or record["name"] == "deepseek-v41-encoder") and ( - kwargs.get("enable_thinking") is False or kwargs.get("thinking") is False - or kwargs.get("reasoning_effort") == "none")): - chosen = {"thinking": "off"} - elif kwargs.get("reasoning_effort") is not None and ( - unmanaged or thinking.accepts(record, kwargs["reasoning_effort"])): - chosen = {"reasoning_effort": kwargs["reasoning_effort"]} - elif unmanaged and (kwargs.get("enable_thinking") is True or kwargs.get("thinking") is True): - chosen = {"thinking": "on"} - if unmanaged: - return {"thinking": chosen.get("thinking", "on" if "reasoning_effort" in chosen else "unknown"), - "level": chosen.get("reasoning_effort"), "chosen": bool(chosen), "levels": [], - "model": {"thinking": "unknown", "level": None}} - state = thinking.deployment_default(record, chosen) - if enabled and state["thinking"] != "off": - state.update(thinking="on", chosen=True) - return state - - -def thinking_line(row, settings): - """Shared display text; unknown installed checkpoints have no line.""" - state = thinking_state(row, settings) - return thinking.deployment_text(state) if state else None - - -def rendezvous_head(fabric, container, observed): - """Resolve a master to a Spark, preferring ownership on the worker's cable. - - Unique fabric/host addresses also identify masters reached through relays. - Legacy reports without address ownership may use a single observed rank zero; - multiple possible owners are never combined into an invented distributed run. - """ - master = container.get("master_addr") - positions = {p["position"]: p for p in fabric["positions"]} - local = positions[container["position"]] - owners = {p["position"] for p in positions.values() - if master in p.get("addresses", [p.get("address")]) - or master == p.get("hostname")} - if container.get("node_rank") == 0: - return container["position"] if not owners or container["position"] in owners else None - neighbors = {n["position"] for n in local.get("neighbors", []) if n["address"] == master} - if len(neighbors) == 1: - return next(iter(neighbors)) - if len(owners) == 1: - return next(iter(owners)) - if owners or neighbors: - return None - heads = {c["position"] for c in observed if c.get("node_rank") == 0 - and (c.get("engine"), c.get("master_addr"), c.get("master_port")) == - (container.get("engine"), master, container.get("master_port"))} - return next(iter(heads)) if len(heads) == 1 else None - - -def parallelism(facts): - """Display only parallel sizes present in the public launch 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): - """Join fresh launch facts by head Spark, or GPU jobs by image and rendezvous.""" - from runtime.host.node_containers import MAX_CONTAINERS, thinking_kwargs - groups, observed = {}, [] - known = {(c["position"], c["name"]) for row in deployments if not row["stopped"] for c in row["containers"]} - for position in fabric["positions"]: - candidates = [d for d in documents if isinstance(d, dict) and d.get("node_id") == position.get("node_id") - and position.get("node_id")] - candidates = [d for d in candidates if number(d.get("observed_at"))] - if not candidates: - continue - doc = max(candidates, key=lambda d: d["observed_at"]) - interval = doc.get("interval_seconds") - interval = min(3600, max(30, interval)) if number(interval) else 30 - if not -5 <= now - doc["observed_at"] <= max(90, interval * 2 + 30): - continue - rows = doc.get("model_containers") - for container in rows[:MAX_CONTAINERS] if isinstance(rows, list) else []: - if not isinstance(container, dict) or container.get("managed") is not False: - continue - name = container.get("name") - if not isinstance(name, str) or not CONTAINER_RE.fullmatch(name) or (position["position"], name) in known: - continue - # 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", "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")) - if kwargs is not None: - c["default_chat_template_kwargs"] = kwargs - master = c.get("master_addr") - if master: - try: - parsed = ipaddress.ip_address(master) - master = None if parsed.is_loopback or parsed.is_unspecified else str(parsed) - except ValueError: - master = master.lower().rstrip(".") - if master == "localhost": - master = None - c["master_addr"] = master - observed.append(c) - for c in observed: - head = rendezvous_head(fabric, c, observed) if c.get("master_addr") and c.get("master_port") else None - key = (("gpu-job", c.get("image_id") or c.get("image"), c["master_addr"], c["master_port"]) - if c.get("engine") == "unknown" and c.get("master_addr") and c.get("master_port") else - (c.get("engine"), "head", head, c["master_port"]) if head is not None else - ("single", c["position"], c["name"])) - groups.setdefault(key, []).append(c) - result = [] - for key, containers in groups.items(): - containers.sort(key=lambda c: (c.get("node_rank", 65536), c["position"], c["name"])) - positions = sorted({c["position"] for c in containers}) - ranks = {c["node_rank"] for c in containers if "node_rank" in c} - expected = max([c.get("nnodes", 1) for c in containers] + [max(ranks, default=0) + 1]) - heads = [c for c in containers if c.get("engine") in ("vllm", "sglang", "flare") - and c.get("node_rank", 0 if expected == 1 else -1) == 0 and not c["headless"]] - head = heads[0] if len(heads) == 1 else None - info = head or containers[0] - head_position = head["position"] if head else None - head_spark = next((p for p in fabric["positions"] if p["position"] == head_position), {}) - bind = (head or {}).get("api_bind") - loopback = bind in ("127.0.0.1", "::1", "localhost") - host = (head_spark.get("address") if not bind or bind in ("0.0.0.0", "::") else - bind if bind in head_spark.get("addresses", [head_spark.get("address")]) else None) - complete = len(ranks) == expected and len(positions) >= expected - if expected == 1: - complete = True - summary = (None if complete else - "head Spark not reporting" if info.get("engine") == "flare" and 0 not in ranks - else f"incomplete: {len(positions)} of {expected} Sparks reporting") - digest = hashlib.sha256(json.dumps(key).encode()).hexdigest()[:20] - result.append({"id": "unmanaged-" + digest, "unmanaged": True, "model": head.get("served_model") if head else None, - "positions": positions, "head_position": head_position, "api_host": host, - "api_port": head.get("api_port") if head and host else None, - "head_port": head.get("api_port") if head else None, "api_local": loopback, - "stopped": False, "containers": containers, "launch": info, - "expected_sparks": expected, "group_note": summary, - "stopped_records": [r for r in deployments if r["stopped"] and set(r["positions"]) & set(positions)]}) - return result - - -class Source: - """One fabric's host files: its fabric document and its site file, re-read when they change.""" - - def __init__(self, fabric_path: Path, site_path: Path): - self.fabric_path, self.site_path = Path(fabric_path), Path(site_path) - self.stamps = None - self.fabric = None - self.deployments: list = [] - self.problem = None - self.display_name = None - - def _stamp(self, path): - """(device, inode, modification time, size): a file replaced by rename gets another inode - even when its time and size repeat.""" - try: - stat = path.stat() - return (stat.st_dev, stat.st_ino, stat.st_mtime_ns, stat.st_size) - except OSError: - return None - - def refresh(self, force: bool = False) -> bool: - """Re-read both files when either one's stamp changed, or when `force`; True when they were - re-read.""" - stamps = (self._stamp(self.fabric_path), self._stamp(self.site_path)) - if stamps == self.stamps and not force: - return False - self.stamps = stamps - self.display_name = None - try: - self.fabric = fabric_from_document(read_json(self.fabric_path)) - except (OSError, ValueError) as error: - self.fabric, self.deployments = None, [] - self.problem = f"fabric document {self.fabric_path}: {error}" - return True - try: - site = read_json(self.site_path) - self.deployments = deployments_from_site(site, self.fabric["size"]) - from runtime.host import ring_name - if site.get("display_name") is not None: - self.display_name = ring_name.validate(site["display_name"]) - self.problem = None - except FileNotFoundError: - self.deployments = [] - self.problem = (f"no site file at {self.site_path}; on Node A, sudo sparkring dashboard export " - "writes it from the deployment records") - except (OSError, ValueError) as error: - self.deployments = [] - self.problem = f"site file {self.site_path}: {error}" - return True - - def ring_id(self) -> str: - cluster = (self.fabric or {}).get("cluster") or "fabric" - return "ring-" + re.sub(r"[^A-Za-z0-9_.-]", "-", cluster)[:40] - - -# -- one model -------------------------------------------------------------------------------- -class Model: - """One deployment's API endpoint: raw observations and state.""" - - def __init__(self, source: Source, row: dict): - self.source = source - self.row = row - self.key = (source.ring_id(), row["id"]) - self.id = f"{source.ring_id()}:{row['id']}" - self.state = None - self.state_since = None - self.model = row.get("model") - self.max_model_len = None - self.metrics = None - self.capacity = None - self.runtime = None - self.run_key = None # identifies the model run whose runtime status was read - self.runtime_due = True - self.runtime_requested_at = None - self.next_metrics = 0.0 - self.next_models = 0.0 - self.last_ok = None - self.models_ok_at = None - self.metrics_at = None - self.history_sample = None - - def observe_metrics(self, metrics: dict, now: float) -> None: - self.metrics = metrics - self.metrics_at = now - self.capacity = capacity_from_cache_info(metrics.get("cache_info")) or self.capacity - if metrics.get("model_name"): - self.model = metrics["model_name"] - run_key = (self.model, metrics.get("started")) - if run_key != self.run_key: - self.run_key, self.runtime_due = run_key, True - self.last_ok = now - - -# -- one endpoint outside the installer -------------------------------------------------------- -class External: - """One endpoint of the external list: what its /metrics and /v1/models said, and its state.""" - - def __init__(self, row: dict): - self.row = row - self.id = "external:" + row["id"] - self.state = None - self.state_since = None - self.model = None - self.root = None - self.max_model_len = None - self.metrics = None - self.metrics_at = None - self.sample = None # (generated_tokens, at) of the previous /metrics read - self.output_tps = None - self.next_metrics = 0.0 - self.next_models = 0.0 - - def observe_metrics(self, metrics: dict, now: float) -> None: - generated = metrics.get("generated_tokens") - if generated is not None and self.sample is not None and now > self.sample[1] and generated >= self.sample[0]: - self.output_tps = (generated - self.sample[0]) / (now - self.sample[1]) - if generated is not None: - self.sample = (generated, now) - else: - self.sample, self.output_tps = None, None - self.metrics, self.metrics_at = metrics, now - - -# -- the collector ---------------------------------------------------------------------------- -class Collector: - """Decides which reads are due, sends them through the client and keeps the results.""" - - def __init__(self, sources, client: ReadOnlyClient, *, quiet_path: Path = QUIET_PATH, - node_status_path: Path | None = NODE_STATUS_PATH, recovery_path: Path | None = RECOVERY_PATH, - node_reports_path: Path | None = NODE_REPORTS_PATH, - live_path=Path("/run/sparkring/dashboard-live.json"), - viewer_path=Path("/run/sparkring-dashboard/viewer"), - external_path: Path | None = EXTERNAL_PATH, - clock=time.time, cpu_clock=time.process_time): - self.sources = list(sources) - self.client = client - self.external_path = Path(external_path) if external_path else None - self.externals: dict = {} # endpoint id -> External, from the external list file - self.external_stamp = None - self.external_problem = None - self.quiet_path = Path(quiet_path) if quiet_path else None - self.node_status_path = Path(node_status_path) if node_status_path else None - self.recovery_path = Path(recovery_path) if recovery_path else None - self.node_reports_path = Path(node_reports_path) if node_reports_path else None - self.node_reports = [] - self.live_path, self.viewer_path = live_path, viewer_path - self.live_telemetry = {} - self.live_startup, self.operations = {}, [] - self.next_lease = 0 - self.recovery: dict = {} # deployment directory name -> the recovery timer's latest finding - self.clock, self.cpu_clock = clock, cpu_clock - self.lock = threading.Lock() - self.models: dict = {} - self.events: collections.deque = collections.deque(maxlen=MAX_EVENTS) - self.started = clock() - self.last_view = None - self.next_files = 0.0 - self.reload_requested = threading.Event() # SIGHUP: re-read the host files at the next cycle - self.last_cycle = None - self.quiet = False - self.node_status = None - self.cycles = 0 - self.cycle_cpu = collections.deque(maxlen=120) # CPU seconds of recent cycles that sent requests - self.history = {} - self.history_seq = 0 - self.history_gaps = set() - - # -- inputs ---------------------------------------------------------------------------- - def viewed(self, now) -> bool: - return self.last_view is not None and now - self.last_view <= VIEWER_SECONDS - - def mark_viewed(self, now=None) -> None: - """A browser fetched the status: poll at the viewed cadence from now on.""" - now = self.clock() if now is None else now - with self.lock: - was = self.viewed(now) - self.last_view = now - if self.viewer_path and now >= self.next_lease: - try: - self.viewer_path.touch() - except OSError: - pass - self.next_lease = now + METRICS_VIEWED_SECONDS - if not was: - for model in self.models.values(): - model.next_metrics = min(model.next_metrics, now) - - def request_runtime(self, model_id: str, now=None) -> bool: - """Read one model's runtime status again at the next cycle; at most once per RUNTIME_REFRESH_SECONDS.""" - now = self.clock() if now is None else now - with self.lock: - model = self.models.get(model_id) - if model is None or (model.runtime_requested_at is not None - and now - model.runtime_requested_at < RUNTIME_REFRESH_SECONDS): - return False - model.runtime_requested_at, model.runtime_due = now, True - return True - - def request_reload(self) -> None: - """Re-read every host file at the next cycle (the SIGHUP handler; systemctl reload).""" - self.reload_requested.set() - - def read_status_files(self) -> None: - self.node_reports = [] - if self.node_reports_path is not None: - try: - doc = read_json(self.node_reports_path) - if doc.get("schema") == "sparkring-dashboard-nodes/v1" and isinstance(doc.get("nodes"), list): - self.node_reports = doc["nodes"][:256] - except (OSError, ValueError, AttributeError): - pass - if self.node_status_path is not None: - try: - self.node_status = read_json(self.node_status_path) - except (OSError, ValueError): - self.node_status = None - if self.recovery_path is not None: - self.recovery = recovery_findings(self.recovery_path) - self.reload_externals() - - def reload_externals(self) -> None: - """Re-read the external list when its stamp changed; keep each listed endpoint's state across re-reads.""" - if self.external_path is None: - return - try: - stat = self.external_path.stat() - stamp = (stat.st_dev, stat.st_ino, stat.st_mtime_ns, stat.st_size) - except OSError: - stamp = None - if stamp == self.external_stamp and self.external_stamp is not None: - return - self.external_stamp = stamp - try: - rows = read_external(self.external_path) - self.external_problem = None - except (OSError, ValueError) as error: - rows, self.external_problem = [], str(error) - with self.lock: - wanted = {row["id"]: row for row in rows} - for identifier in [i for i in self.externals if i not in wanted]: - del self.externals[identifier] - for identifier, row in wanted.items(): - current = self.externals.get(identifier) - if current is None or (current.row["host"], current.row["port"]) != (row["host"], row["port"]): - self.externals[identifier] = External(row) - else: - current.row = row - - def reload_sources(self, force: bool = False) -> None: - """Re-read each fabric's document and site file whose stamp changed (all of them when - `force`), and follow the deployments they list: a model per row, kept across re-reads.""" - for source in self.sources: - source.refresh(force) - hosts, wanted = set(), {} - for source in self.sources: - unmanaged = unmanaged_groups(source.fabric, [*self.node_reports, self.node_status], source.deployments, - self.last_cycle if self.last_cycle is not None else self.clock()) if source.fabric else [] - hidden = {r["id"] for group in unmanaged for r in group["stopped_records"]} - pending = deployments_from_site({"schema": SITE_SCHEMA, "deployments": [op["deployment"] for op in self.operations]}, - len(source.fabric["positions"])) if source is self.sources[0] and source.fabric else [] - occupied = {p for row in pending for p in row["positions"]} - rows = [r for r in source.deployments if r["id"] not in hidden and not occupied.intersection(r["positions"])] - for row in rows + pending + [r for r in unmanaged if not occupied.intersection(r["positions"])]: - if row["api_host"]: - hosts.add(row["api_host"]) - wanted[(source.ring_id(), row["id"])] = (source, row) - with self.lock: - hosts.update(external.row["host"] for external in self.externals.values()) - self.client.allow(hosts) - with self.lock: - for model_id in [m for m, model in self.models.items() if model.key not in wanted]: - del self.models[model_id] - known = {model.key: model for model in self.models.values()} - for key, (source, row) in wanted.items(): - if key in known: - if (known[key].row.get("api_host"), known[key].row.get("api_port"), known[key].row.get("containers")) != ( - row.get("api_host"), row.get("api_port"), row.get("containers")) and row.get("unmanaged"): - fresh = Model(source, row) - self.models[fresh.id] = fresh - self.history_gaps.add(fresh.id) - known[key].row = row - else: - model = Model(source, row) - self.models[model.id] = model - - # -- one cycle ------------------------------------------------------------------------- - def clock_went_back(self, now: float) -> None: - """The wall clock stepped back, as an NTP correction after boot or a manual date does. - - Every schedule here is kept in that clock, so each read would otherwise wait out the whole - step: the reads fall due now. Raw observations from the clock's future are invalidated, - and a viewer or a state that the old clock dated later than now is dated now.""" - print(f"sparkring dashboard: the clock went back by {self.last_cycle - now:.0f} s; reads rescheduled", - file=sys.stderr, flush=True) - self.next_files = now - self.next_lease = now - with self.lock: - self.history_gaps.update(self.models) - if self.last_view is not None and self.last_view > now: - self.last_view = now - for model in self.models.values(): - model.next_metrics = min(model.next_metrics, now) - model.next_models = min(model.next_models, now) - if model.runtime_requested_at is not None and model.runtime_requested_at > now: - model.runtime_requested_at = None - if model.state_since is not None and model.state_since > now: - model.state_since = now - model.metrics_at = None - - def cycle(self, now=None) -> None: - now = self.clock() if now is None else now - if self.last_cycle is not None and now < self.last_cycle - CLOCK_STEP_SECONDS: - self.clock_went_back(now) - self.last_cycle = now - # Host files first, in quiet mode too: two stats a second, and no request to any Spark. - forced = self.reload_requested.is_set() - if forced: - self.reload_requested.clear() - if forced or now >= self.next_files: - self.read_status_files() - self.next_files = now + FILES_SECONDS - self.read_live(now) - self.reload_sources(forced) - # Quiet mode is checked on every cycle (a stat and a small directory listing a second), so a - # hold takes effect before a measurement that starts right after it. - self.quiet = bool(self.quiet_path and quiet_state(self.quiet_path, now)["quiet"]) - with self.lock: - self.prune_history(now) - if self.quiet: - with self.lock: - self.history_gaps.update(self.models) - return - before = self.cpu_clock() - sent = False - with self.lock: - models = list(self.models.values()) - viewed = self.viewed(now) - # One outstanding request per group, at most eight workers. Independent - # heads cannot serialize healthy samples behind a slow head's timeout. - if len(models) > 1 and viewed: - with ThreadPoolExecutor(max_workers=8, thread_name_prefix="dashboard-metrics") as pool: - sent = any(list(pool.map(lambda model: self.poll(model, now, viewed), models))) - else: - for model in models: - sent = self.poll(model, now, viewed) or sent - with self.lock: - externals = list(self.externals.values()) - for external in externals: - sent = self.poll_external(external, now, viewed) or sent - with self.lock: - for model in models: - if viewed: - self.remember(model, now) - else: - self.history_gaps.add(model.id) - if sent: - self.cycle_cpu.append(self.cpu_clock() - before) - self.cycles += 1 - - def read_live(self, now): - self.live_telemetry, self.live_startup, self.operations = {}, {}, [] - if not self.viewed(now) or not self.live_path or (self.quiet_path and quiet_state(self.quiet_path, now)["quiet"]): - return - try: - live = read_json(self.live_path) - if number(live.get("at")) and -5 <= now - live["at"] <= 6: - self.live_telemetry = live.get("telemetry", {}) - raw = live.get("startup", {}) - self.live_startup = startup.project(raw, list(raw)[:8], now) - self.operations = [op for op in live.get("operations", [])[:8] - if isinstance(op, dict) and isinstance(op.get("deployment"), dict) - and op.get("phase") in startup.PHASES and number(op.get("started_at")) - and number(op.get("at")) and -5 <= now - op["at"] <= 6] - except (OSError, ValueError, AttributeError, TypeError): - pass - - def startup_status(self, model): - deployment = model.row.get("deployment_id") - ranks = startup.group(self.live_startup.get(deployment, []), model.row["positions"]) - operation = next((op for op in self.operations if op["deployment"].get("deployment_id") == deployment), None) - if operation: - # A previous run's containers must not hide checkpoint preparation. - if not ranks or ranks["started_at"] < operation["started_at"] or ranks["phase"] == "starting": - return {k: v for k, v in operation.items() if k != "deployment"} - ranks["started_at"] = min(operation["started_at"], ranks["started_at"]) - return ranks - - def poll(self, model: Model, now: float, viewed: bool) -> bool: - """Send the reads that are due for one model; True when any request was sent. - - A model whose /metrics answer is serving: vLLM's API server listens only once its engine - is ready. A refused connection is a stopped model, a timeout an unreachable Spark and an - HTTP error a model still starting. A /metrics answer that names a different model means - another deployment of an overlapping slot holds the port, and this one is idle. A deployment - 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 - if row["stopped"]: - 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) - if starting and (starting["phase"] == "failed" or starting["started_at"] > (model.metrics_at or 0)) and model.state == "serving": - model.next_metrics = min(model.next_metrics, now) - sent = False - 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) - 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 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: - model.metrics = None - model.metrics_at = None - else: - state = "serving" - with self.lock: - model.observe_metrics(metrics, now) - model.next_metrics = now + cadence - else: - state = {"refused": "stopped", "timeout": "offline", "unreachable": "offline"}.get( - fetched.failure, "not_ready") - if row["stopped"]: - state = "stopped" # the records say its last operation stopped it - 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: - model.next_models = now + MODELS_SECONDS - listed = self.models_listed(self.client.get(host, port, "/v1/models")) - if listed: - state = "serving" - with self.lock: - 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 - with self.lock: - model.metrics = None - model.metrics_at = None - model.next_metrics = now + max(cadence, FAILED_SECONDS) - model.api_state = state - state = getattr(model, "api_state", model.state) - if starting and (state != "serving" or starting["phase"] in ("installing", "failed")): - state = "starting" if starting["phase"] == "ready" else starting["phase"] - self.set_state(model, state, now) - if model.state == "serving" and now >= model.next_models: - sent = True - model.next_models = now + MODELS_SECONDS - listed = self.models_listed(self.client.get(host, port, "/v1/models")) - if listed: - with self.lock: - 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 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") - runtime = None - if fetched.ok: - try: - runtime = read_runtime_status(json.loads(fetched.body)) - except (ValueError, AttributeError, TypeError): - runtime = None - with self.lock: - model.runtime = runtime - return sent - - def poll_external(self, external: External, now: float, viewed: bool) -> bool: - """Send the reads due for one external endpoint; True when any request was sent. - - An endpoint whose /metrics answers is serving; a refused connection means nothing listens, - a timeout an unreachable host and an HTTP error a server that is not ready. /v1/models is - read once a minute while it serves, for the model's name, root and context length.""" - if not viewed: - return False - row = external.row - host, port = row["host"], row["port"] - sent = False - if external.state == "serving" and external.metrics_at is not None: - external.next_metrics = min(external.next_metrics, external.metrics_at + METRICS_VIEWED_SECONDS) - if now >= external.next_metrics: - sent = True - fetched = self.client.get(host, port, "/metrics") - if fetched.ok: - metrics = parse_flare_metrics(fetched.body.decode("utf-8", "replace")) if row["kind"] == "flare" else {} - with self.lock: - external.observe_metrics(metrics, now) - state = "serving" - external.next_metrics = now + METRICS_VIEWED_SECONDS - else: - state = {"refused": "stopped", "timeout": "offline", "unreachable": "offline"}.get(fetched.failure, "not_ready") - with self.lock: - external.metrics, external.metrics_at, external.output_tps, external.sample = None, None, None, None - external.next_metrics = now + max(METRICS_VIEWED_SECONDS, FAILED_SECONDS) - self.set_external_state(external, state, now) - if external.state == "serving" and now >= external.next_models: - sent = True - external.next_models = now + MODELS_SECONDS - listed = self.models_listed(self.client.get(host, port, "/v1/models")) - if listed: - with self.lock: - external.model = listed.get("id") or external.model - external.root = listed.get("root") or external.root - external.max_model_len = listed.get("max_model_len") or external.max_model_len - return sent - - def set_external_state(self, external: External, state: str, now: float) -> None: - with self.lock: - if state == external.state: - return - previous, external.state, external.state_since = external.state, state, now - if previous is not None or state == "serving": - self.events.append({"at": now, "stack": external.row["label"], "text": LABELS[state], - "kind": state}) - - def external_member(self, external: External, now: float) -> dict: - """One external endpoint as the page shows it: identity, state and the figures of its last read.""" - row, metrics = external.row, external.metrics or {} - serving = external.state == "serving" - - def ratio(numerator, denominator): - top, bottom = metrics.get(numerator), metrics.get(denominator) - return (top / bottom) if top is not None and bottom else None - - stats = None - if serving and metrics: - kv_total, kv_free = metrics.get("kv_tokens_total"), metrics.get("kv_tokens_free") - stats = {"output_tps": external.output_tps, - "tokens_last_minute": metrics.get("tokens_last_minute"), - "active_requests": metrics.get("active_requests"), "pending_requests": metrics.get("pending_requests"), - "request_capacity": metrics.get("request_capacity"), - "kv_in_use": ((kv_total - kv_free) / kv_total) if kv_total and kv_free is not None else None, - "kv_tokens_total": kv_total, "kv_tokens_cached": metrics.get("kv_tokens_cached"), - "uptime_seconds": metrics.get("uptime_seconds"), - "generated_tokens": metrics.get("generated_tokens"), "prefill_tokens": metrics.get("prefill_tokens"), - "requests_completed": metrics.get("requests_completed"), "requests_failed": metrics.get("requests_failed"), - "http_requests": metrics.get("http_requests"), - "draft_acceptance": ratio("drafts_accepted", "drafts_offered"), - "row_cache_hit_rate": (metrics["row_cache_hits"] / (metrics["row_cache_hits"] + metrics["row_cache_misses"]) - if metrics.get("row_cache_hits") is not None and metrics.get("row_cache_misses") is not None - and metrics["row_cache_hits"] + metrics["row_cache_misses"] else None), - "prefix_hit_rate": ratio("prefix_hits", "prefix_lookups")} - return {"id": external.id, "label": row["label"], "kind": row["kind"], "host": row["host"], "port": row["port"], - "position": row.get("position"), - "endpoint": f"http://{row['host']}:{row['port']}/v1", "metrics_url": f"http://{row['host']}:{row['port']}/metrics", - "state": external.state, "state_label": LABELS[external.state], "state_since": external.state_since, - "model": external.model, "root": external.root, "max_model_len": external.max_model_len, - "metrics_problem": FLARE_METRICS_PROBLEM if serving and row["kind"] == "flare" and not metrics else None, - "metrics_at": external.metrics_at, "stats": stats} - - def external_ring_member(self, external: External, source: Source, now: float, color: int) -> dict: - """An external endpoint placed on a ring, in the shape of member(): a one-Spark group at its listed - position, with the endpoint's figures as ``live`` and its card document under the same keys as - external_member().""" - card = self.external_member(external, now) - row, stats = external.row, card["stats"] - position = row["position"] - spark = next((p for p in source.fabric["positions"] if p["position"] == position), {}) - serving = external.state == "serving" - runtime_name = "Flare" if row["kind"] == "flare" else "OpenAI API" - return { - **card, - "name": run_name([position]), "profile": None, "start_command": None, - "unmanaged": False, "gpu_job": False, "launch": {}, - "ownership_label": "Not installed by SparkRing: no automatic recovery, no install record", - "group_note": None, "containers": [], "stopped_records": [], - "startup": None, "spark_startup": None, - "model_short": short_model(external.model), "details_url": None, - "layout": {"label": runtime_name, "count": 1, "tp": 1, "dcp": None}, - "live": {"output_tps": stats["output_tps"], "running": stats["active_requests"], - "waiting": stats["pending_requests"], "kv": stats["kv_in_use"], "read_at": external.metrics_at} - if stats else None, - "counters": None, "plugin_counters": None, "counter_samples": [], - "totals": {"finished": stats["requests_completed"], "preemptions": None, - "output_tokens": stats["generated_tokens"], "prompt_tokens": stats["prefill_tokens"]} - if stats else None, - "thinking": None, "thinking_default": None, "thinking_provenance": None, - "settings": None, "nodes": [], "capacity": None, "workers": None, "image": None, "transport": None, - "sparks": [{"name": spark.get("hostname", str(position)), "address": spark.get("address"), - "lan_address": spark.get("lan_address"), "up": True if serving else None, - "position": position, "container": None}], - "history": [], - "arc": {"positions": [position], "first": position, "last": position, "size": 1, - "run": run_name([position]), "source": "external", "source_label": "external endpoint list", - "inferred": False, "detail": None, "color": color}, - "ring": source.ring_id(), - "head": {"position": position, "name": spark.get("hostname"), "address": row["host"], "port": row["port"], - "container": None}, - "logs": log_commands(spark.get("hostname"), None), - "runtime_read": False, "recovery": None, "external": True, - } - - @staticmethod - def models_listed(fetched: Fetched) -> dict | None: - if not fetched.ok: - return None - try: - data = json.loads(fetched.body).get("data") or [] - except (ValueError, AttributeError): - return None - return data[0] if data and isinstance(data[0], dict) else None - - def set_state(self, model: Model, state: str, now: float) -> None: - with self.lock: - if state == model.state: - return - previous, model.state, model.state_since = model.state, state, now - if state != "serving": - model.runtime = None if state != "not_ready" else model.runtime - text = LABELS[state] + (f": {model.model}" if state == "serving" and model.model else "") - if previous is not None or state == "serving": - self.events.append({"at": now, "stack": run_name(model.row["positions"]), "text": text, - "kind": state}) - - def run(self, stop: threading.Event) -> None: - while not stop.is_set(): - cycle_started = time.monotonic() - try: - self.cycle() - except Exception as error: # one bad response must not stop the page - print(f"sparkring dashboard: collection failed: {error!r}", file=sys.stderr, flush=True) - stop.wait(max(0.05, 1.0 - (time.monotonic() - cycle_started))) - - # -- the status document ----------------------------------------------------------------- - def plugin_snapshot(self, model, now): - fallback = {"run_id": (model.metrics or {}).get("started")} - deployment = model.row.get("deployment_id") - # The root agent forwards head snapshots through the existing SSH path. - # This service reads only its local projection and the inventory cache. - reports = [self.node_status, *self.node_reports] - candidates = [self.live_telemetry.get(deployment)] + [report["telemetry"].get(deployment) for report in reports - if isinstance(report, dict) and isinstance(report.get("telemetry"), dict)] - candidates.append((self.recovery.get(model.row["id"]) or {}).get("telemetry")) - fresh = [p for p in candidates if plugin_fresh(p, fallback, now) - and (not self.viewed(now) or now - p["at"] <= 12)] - chosen = max(fresh, key=lambda p: p["at"], default=None) - metrics = model.metrics or {} - if (chosen and number(model.metrics_at) and model.metrics_at > chosen["at"] - and metrics.get("running") == 0 and metrics.get("waiting") == 0 - and (chosen["running"] != 0 or chosen["waiting"] != 0)): - return None # a newer idle observation must not inherit a busy plugin interval - return chosen - - def prune_history(self, now): - for model_id in list(self.history): - if model_id not in self.models: - del self.history[model_id] - continue - rows = self.history[model_id] - while rows and rows[0]["counters"]["at"] < now - HISTORY_SECONDS: - rows.popleft() - while rows and rows[-1]["observed_at"] > now: - rows.pop() - self.history_gaps.intersection_update(self.models) - - def remember(self, model, now): - """Retain only bounded raw numeric fields, never rates or mutable source documents. - - Each sample carries exactly one source. A fresh stat-logger snapshot is - stored as the plugin payload alone; only a cycle without one stores the - /metrics read, so the label and the values can never diverge and no - sample mixes plugin and /metrics counters. - """ - if model.id not in self.history: - if len(self.history) >= HISTORY_DEPLOYMENTS: - return - self.history[model.id] = collections.deque(maxlen=HISTORY_SAMPLES) - rows = self.history[model.id] - plugin = self.plugin_snapshot(model, now) - if model.state != "serving" or (not plugin and not number(model.metrics_at)): - self.history_gaps.add(model.id) - return - metrics = model.metrics or {} - if plugin: - sample = {k: plugin[k] for k in (*HISTORY_VALUES, "at", "monotonic") if number(plugin.get(k))} | { - "source": "plugin", "schema": "sparkring-stats/v1", "run_id": plugin["run_id"], - "step_timing": bool(plugin.get("step_timing"))} - else: - sample = {"source": "metrics", "at": model.metrics_at, "run_id": metrics.get("started"), - "values": {k: metrics[k] for k in HISTORY_VALUES if number(metrics.get(k))}} - at = sample["at"] - if not number(at) or now - at > (180 if plugin else 125): - self.history_gaps.add(model.id) - return - # Inspect every live observation before thinning the archive. A reset - # between retained rows still creates a boundary, even if its counters - # have already exceeded the last archived value by the next archive tick. - last = model.history_sample - if last: - before = last.get("values", last) - values = sample.get("values", sample) - if ((last["source"], last["run_id"]) != (sample["source"], sample["run_id"]) - or sample.get("monotonic", at) < last.get("monotonic", last["at"]) - or any(number(values.get(k)) and number(before.get(k)) and values[k] < before[k] - for k in HISTORY_VALUES if k not in ("running", "waiting", "kv"))): - self.history_gaps.add(model.id) - model.history_sample = sample - # Snapshot identity is independent of the collector's read time and fallback reads. - previous = rows[-1]["counters"] if rows else None - if previous and (rows[-1]["source"], previous["run_id"], - previous.get("monotonic", previous["at"])) == ( - sample["source"], sample["run_id"], sample.get("monotonic", at)): - return - if previous and model.id not in self.history_gaps and 0 <= at - previous["at"] < HISTORY_SPACING: - return - self.history_seq += 1 - rows.append({"seq": self.history_seq, "observed_at": now, "source": sample["source"], - "counters": sample, "boundary": model.id in self.history_gaps}) - self.history_gaps.discard(model.id) - - def history_snapshot(self, now=None): - now = self.clock() if now is None else now - with self.lock: - self.prune_history(now) - return {"generated_at": now, "service_started": self.started, "history_cursor": self.history_seq, - "counter_history": {key: list(rows) for key, rows in self.history.items()}} - - def snapshot(self, now=None, since=None) -> dict: - """The sparkring-dashboard/v1 document: the fields the page reads, in the shape it reads them.""" - now = self.clock() if now is None else now - with self.lock: - models = list(self.models.values()) - groups, rings = [], [] - color = 0 - externals = sorted(self.externals.values(), key=lambda e: e.row["id"]) - placed: set = set() - for source in self.sources: - fabric = source.fabric - members = [] - for model in sorted(models, key=lambda m: (min(m.row["positions"]), m.id)): - if model.source is source: - member = self.member(model, now, color) - rows = self.history.get(model.id, ()) - delta = list(rows)[-1:] if since is None else [r for r in rows if r["seq"] > since] - if len(delta) > HISTORY_DELTA_SAMPLES: - delta = delta[-HISTORY_DELTA_SAMPLES:] - delta[0] = {**delta[0], "boundary": True} - member["counter_samples"] = delta - members.append(member) - color += 1 - # An endpoint listed with a position joins the first ring whose fabric has that position. A - # container the host agents saw on that Spark without a known engine is that endpoint's own - # server, so its "GPU in use" row gives way to the endpoint's card, which then also names the - # stopped install records that row carried for the Spark. - here: dict = {} - for external in externals: - position = external.row.get("position") - if fabric and position is not None and external.id not in placed and position < fabric["size"]: - here[position] = self.external_ring_member(external, source, now, color) - placed.add(external.id) - color += 1 - kept = [] - for member in members: - if member["gpu_job"] and set(member["arc"]["positions"]) <= set(here): - for position in member["arc"]["positions"]: - known = {r["id"] for r in here[position]["stopped_records"]} - here[position]["stopped_records"] += [r for r in member["stopped_records"] - if r["id"] not in known] - else: - kept.append(member) - members = kept + list(here.values()) - members.sort(key=lambda m: m["arc"]["first"]) - groups.append({"id": source.ring_id(), "name": self.ring_name(source), "kind": "ring", - "members": members}) - if fabric: - rings.append(self.ring(source, members, now)) - events = list(self.events)[::-1][:60] - quiet, viewed = self.quiet, self.viewed(now) - cpu = list(self.cycle_cpu) - cursor = self.history_seq - externals = [self.external_member(e, now) for e in externals if e.id not in placed] - external_problem = self.external_problem - problems = [s.problem for s in self.sources if s.problem] - topology = {"source": "fabric" if rings else "none", "detail": "; ".join(problems) or None, - "rings": len(rings)} - counters = self.client.counters() - return {"schema": SCHEMA, "title": rings[0]["name"] if len(rings) == 1 else "SparkRing", - "generated_at": now, "service_started": self.started, - "history_cursor": cursor, - "poll_seconds": METRICS_VIEWED_SECONDS, "groups": groups, "rings": rings, - "ring": rings[0] if len(rings) == 1 else None, "topology": topology, "events": events, - "node": self.node_summary(), - "external": externals, "external_problem": external_problem, - "collector": {"quiet": quiet, "viewed": viewed, "cycles": self.cycles, - "metrics_seconds": METRICS_VIEWED_SECONDS if viewed else None, - "models_seconds": MODELS_SECONDS, - "cpu_ms_per_cycle": round(sum(cpu) / len(cpu) * 1000, 2) if cpu else None, - "requests": counters["requests"], "received_bytes": counters["received_bytes"], - "uptime_seconds": now - self.started}} - - def ring_name(self, source) -> str: - fabric = source.fabric - if not fabric: - return "fabric" - return source.display_name or fabric.get("cluster") or "sparkring" - - def member(self, model: Model, now: float, color: int) -> dict: - row, fabric = model.row, model.source.fabric or {"positions": []} - hostnames = {p["position"]: p for p in fabric["positions"]} - positions = row["positions"] - runtime = model.runtime or {} - metrics = model.metrics or {} - serving = model.state == "serving" - nodes = runtime.get("nodes") or [] - head_position = row.get("head_position", positions[0]) - head = hostnames.get(head_position, {}) - port = row["api_port"] or row.get("head_port") - endpoint = row.get("display_url") or f"http://{row['api_host']}:{port}/v1" - if not row["api_host"] or not port: - endpoint = None - spark_starting = self.startup_status(model) if not row["stopped"] else None - starting = spark_starting if not serving else None - if starting: - since = starting.get("started_at") - since = since if number(since) and since > 0 else None - elif serving: - # Runtime startup and process start are recorded events. An older - # runtime snapshot must not carry a prior run's age across a restart. - starts = [t for t in (runtime.get("started_at"), metrics.get("started")) - if number(t) and t > 0] - since = max(starts) if starts else row.get("serving_at") - elif model.state == "stopped": - since = row.get("stopped_at") if row["stopped"] else None - elif model.state in startup.PHASES or model.state == "not_ready": - since = None - else: - since = model.state_since - capacity = dict(model.capacity) if model.capacity else None - if capacity and runtime.get("settings"): - capacity["max_num_seqs"] = runtime["settings"].get("max_num_seqs") - launch = row.get("launch") or {} - 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, {}) - up = True if serving else (False if model.state == "offline" and position == positions[0] else None) - sparks.append({"name": spark.get("hostname", str(position)), "address": spark.get("address"), - "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 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, - "ownership_label": "Not installed by SparkRing: no automatic recovery, no install record" if row.get("unmanaged") else None, - "group_note": row.get("group_note"), "containers": row["containers"] if row.get("unmanaged") else [], - "stopped_records": row.get("stopped_records", []), - "startup": starting, - "spark_startup": spark_starting, - "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 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, - "counters": {"source": "metrics", "at": model.metrics_at, "run_id": metrics.get("started"), - "values": {key: value for key, value in metrics.items() - if isinstance(value, (int, float))}} if model.metrics else None, - "plugin_counters": self.plugin_snapshot(model, now), - "totals": {"finished": metrics.get("finished"), "preemptions": metrics.get("preemptions"), - "output_tokens": metrics.get("gen"), "prompt_tokens": metrics.get("prompt")} - if model.metrics else None, - "thinking": thinking.deployment_text(thought) if thought else None, - "thinking_default": thought, "thinking_provenance": thinking.provenance_text(thought), - "settings": runtime.get("settings"), "nodes": nodes, "capacity": capacity if serving else None, - "workers": ({"received": len(positions), "expected": row.get("expected_sparks") or len(positions)} - if flare else runtime.get("workers")), - "image": runtime.get("image"), "transport": runtime.get("transport"), - "sparks": sparks, - "history": [], - "arc": {"positions": positions, "first": positions[0], "last": positions[-1], "size": len(positions), - "run": run_name(positions), "source": "agent" if row.get("unmanaged") else "deployment", - "source_label": "agent launch facts" if row.get("unmanaged") else "deployment record", - "inferred": False, "detail": None, "color": color}, - "ring": model.source.ring_id(), - "head": {"position": head_position, "name": head.get("hostname"), "address": row["api_host"], "port": port, - "container": container}, - "logs": log_commands(head.get("hostname"), container), - "runtime_read": model.runtime is not None, - "recovery": {k: v for k, v in self.recovery[row["id"]].items() if k != "telemetry"} - if row["id"] in self.recovery else None, - } - - def ring(self, source: Source, members: list, now: float) -> dict: - fabric = source.fabric - owners: dict = {} - for member in members: - for position in member["arc"]["positions"]: - owners.setdefault(position, []).append(member["id"]) - local = socket.gethostname() - # A position's first member is the one that serves it; a stopped record sharing the position follows. - states = {m["id"]: m["state"] for m in members} - positions = [] - for row in fabric["positions"]: - reports = [d for d in [self.node_status, *self.node_reports] if isinstance(d, dict) - and row.get("node_id") and d.get("node_id") == row["node_id"] - and number(d.get("observed_at"))] - cached = max(reports, key=lambda d: d["observed_at"], default={}) - busy = sorted(owners.get(row["position"]) or [], key=lambda i: states.get(i) != "serving") - serving = any(m["state"] == "serving" and m["id"] in busy for m in members) - up = True if serving or row["hostname"] == local else None - positions.append({"position": row["position"], "name": row["hostname"], - "short": row["hostname"].removeprefix("spark-"), "address": row["address"], - "up": up, "since": None, "member": busy[0] if busy else None, "members": busy, - "run": None, "ports": row.get("ports", {}), - "observed_at": cached.get("observed_at"), - **spark_cached_details(cached)}) - first = fabric["positions"][0]["hostname"] - return {"id": source.ring_id(), "name": self.ring_name(source), "node_a": first, - "short": first.removeprefix("spark-"), "size": fabric["size"], "closed": fabric["closed"], - "source": "fabric", - "fabric": {"id": fabric["id"], "cluster": fabric["cluster"], "shape": fabric["shape"], - "verified": fabric["verified"], "read_from": [str(source.fabric_path)]}, - "positions": positions, "runs": [], - "discovery": {"ports": sorted({m["head"]["port"] for m in members if m["head"]["port"]}), - "every_seconds": METRICS_VIEWED_SECONDS if self.last_view and self.viewed(now) - else None, "at": now}} - - def node_summary(self) -> dict | None: - status = self.node_status - if not isinstance(status, dict): - return None - return {key: status.get(key) for key in ("hostname", "state", "next_action", "observed_at", "warnings", "error")} - - -def recovery_findings(path: Path) -> dict: - """{deployment directory name: {state, summary, next_action, checked_at, enabled}} from the - recovery timer's sparkring-recovery/v1 record; empty when it is absent or unreadable.""" - try: - document = read_json(path) - except (OSError, ValueError): - return {} - if not isinstance(document, dict) or document.get("schema") != "sparkring-recovery/v1": - return {} - found = {} - for directory, record in (document.get("deployments") or {}).items(): - if not isinstance(record, dict): - continue - finding = record.get("finding") if isinstance(record.get("finding"), dict) else {} - found[Path(str(directory)).name] = { - "state": finding.get("state"), "summary": finding.get("summary"), - "next_action": finding.get("next_action"), "checked_at": record.get("checked_at"), - "enabled": record.get("enabled", True), "stopped": bool(record.get("stopped")), - "telemetry": finding.get("telemetry")} - return found - - -def start_command(row): - """Name the saved deployment, including inactive records that share a slice.""" - if row.get("unmanaged"): - return None - profile, identity = row.get("profile"), row.get("id", "") - if isinstance(profile, str) and profile and (identity == profile or identity.startswith(profile + "-")): - command = ["sudo", "sparkring", "up", profile] - instance = identity[len(profile):].removeprefix("-") - if instance: - command += ["--instance", instance] - else: - command = ["sudo", "sparkring", "up", "--on", ",".join(map(str, row["positions"]))] - return shlex.join(command) - - -def log_commands(hostname, container) -> dict: - """How the operator prints a model's log on demand: the commands, not their output. - - The dashboard holds no SSH key and no Docker access; the operator runs these on the - head Spark with their own login, so nothing reads a log unless someone asks.""" - if not container: - return {"enabled": False, "host": hostname, "commands": []} - return {"enabled": True, "host": hostname, "commands": [f"sudo docker logs -f --tail {LOG_LINES} {container}"]} - - -# -- process placement ------------------------------------------------------------------------- -def efficiency_cpus(root: Path | None = None, cpuinfo: Path | None = None) -> set | None: - """The CPUs outside the fastest class (on GB10 the Cortex-A725 cores), or None on a host whose - cores are all of one class: runtime.host.host_load.efficiency_cpus, which the host agent's and - the recovery timer's placement drop-ins use too.""" - from runtime.host import host_load - return host_load.efficiency_cpus(root, cpuinfo) - - -def lower_priority(cpu_list: str | None = None) -> list: - """Move this thread, and the threads it starts later, to idle CPU scheduling, nice 19 and the - efficiency cores (or `cpu_list`); returns what changed. - - Call it before any other thread starts: Linux applies each setting to the calling thread and - new threads inherit it. Each step is skipped where the platform lacks it. The systemd unit - (packaging/debian/sparkring-dashboard.service) sets the same limits; doing it here as well - covers a dashboard started by hand or on another host.""" - done = [] - if hasattr(os, "sched_setscheduler") and hasattr(os, "SCHED_IDLE"): - try: - os.sched_setscheduler(0, os.SCHED_IDLE, os.sched_param(0)) - done.append("idle scheduling") - except OSError: - pass - if hasattr(os, "nice"): - try: - os.nice(max(0, 19 - os.nice(0))) - done.append("nice 19") - except OSError: - pass - if hasattr(os, "sched_setaffinity"): - from spark_transport.sircl.sparkring_sircl import cpus - chosen = set(cpus.parse_cpu_list(cpu_list)) if cpu_list else efficiency_cpus() - if chosen: - try: - os.sched_setaffinity(0, chosen) - done.append("CPUs " + cpus.format_cpu_list(chosen)) - except OSError: - pass - return done - - -# -- the web server ---------------------------------------------------------------------------- -def page_bytes(path: Path = PAGE) -> tuple[bytes, str]: - """The page and its Content-Security-Policy: its inline script and style admitted by hash only.""" - text = Path(path).read_text(encoding="utf-8") - text = text.replace("// VIEWER_RATES", Path(__file__).with_name("dashboard_rates.js").read_text(encoding="utf-8")) - policies = [] - for tag, directive in (("script", "script-src"), ("style", "style-src")): - match = re.search(rf"<{tag}>(.*?)", text, flags=re.S) - digest = base64.b64encode(hashlib.sha256(match.group(1).encode()).digest()).decode() - policies.append(f"{directive} 'sha256-{digest}'") - csp = "; ".join(["default-src 'none'", *policies, "style-src-attr 'unsafe-inline'", "connect-src 'self'", - "img-src 'self' data:", "base-uri 'none'", "frame-ancestors 'none'", "form-action 'none'"]) - return text.encode("utf-8"), csp - - -def host_allowed(header: str | None, names) -> bool: - """Whether a request's Host header names this server: an IP literal, `localhost` or one of `names`. - - A browser on the LAN that a hostile web page points at the dashboard through DNS - rebinding sends that page's host name, which is refused. `localhost` is no page's name: - browsers resolve it to loopback themselves.""" - if not header: - return False - host = header.strip() - if host.startswith("["): - host = host[1:host.find("]")] if "]" in host else host - else: - host = host.rsplit(":", 1)[0] if host.count(":") == 1 else host - return _ip(host) or host.lower() == "localhost" or host.lower() in names - - -def make_handler(collector: Collector, page: bytes, csp: str, names=frozenset(), password: str | None = None, - manager=None): - headers = {"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", - "X-Frame-Options": "DENY"} - expected = (None if password is None - else ("Basic " + base64.b64encode(f"sparkring:{password}".encode("utf-8")).decode("ascii")).encode("utf-8")) - - class Handler(BaseHTTPRequestHandler): - server_version = "sparkring-dashboard" - - def do_GET(self): - if not host_allowed(self.headers.get("Host"), names): - return self._send(421, b"This dashboard answers to its IP address or a name given with --name.\n", - "text/plain; charset=utf-8") - auth_header = self.headers.get("Authorization") - auth_ok = (auth_header is not None - and hmac.compare_digest(auth_header.encode("utf-8", "replace"), expected)) if expected is not None else True - if (expected is not None and not auth_ok - and not (manager and manager.authenticated(self.headers))): - self.send_response(401) - self.send_header("WWW-Authenticate", 'Basic realm="SparkRing dashboard", charset="UTF-8"') - self.send_header("Content-Length", "0") - self.end_headers() - return None - path, _, query = self.path.partition("?") - params = {k: v[-1] for k, v in urllib.parse.parse_qs(query).items()} - if path == "/": - return self._send(200, page, "text/html; charset=utf-8", {"Content-Security-Policy": csp}) - if path == "/api/status": - if params.get("viewer") != "passive": # sparkring dashboard tui --passive - collector.mark_viewed() - try: - since = int(params["since"]) if "since" in params else None - except ValueError: - return self._json(400, {"error": "Invalid history cursor"}) - snapshot = collector.snapshot(since=since) - return self._json(200, {**snapshot, "manage": True} if manager else snapshot) - if path == "/api/history": - body = json.dumps(collector.history_snapshot(), separators=(",", ":")).encode() - extra = {"Vary": "Accept-Encoding"} - if "gzip" in self.headers.get("Accept-Encoding", ""): - body = gzip.compress(body, compresslevel=1, mtime=0) - extra["Content-Encoding"] = "gzip" - return self._send(200, body, "application/json", extra) - if path == "/api/manage" and manager: - try: - return self._json(200, manager.session(self.headers)) - except PermissionError as error: - return self._json(401, {"error": str(error)}) - if path == "/api/refresh": - accepted = collector.request_runtime(params.get("model", "")) - return self._json(202 if accepted else 429, {"accepted": accepted}) - if path == "/healthz": - return self._send(200, b"ok\n", "text/plain") - return self._send(404, b"not found\n", "text/plain") - - def _refuse(self): - self._send(405, b"read-only\n", "text/plain", {"Allow": "GET"}) - - do_PUT = do_DELETE = do_PATCH = _refuse - - def do_POST(self): - if manager is None: - return self._refuse() - if not host_allowed(self.headers.get("Host"), names): - return self._json(421, {"error": "Host refused"}) - if not manager.authenticated(self.headers): - return self._json(401, {"error": "Authentication required"}) - if self.headers.get("Content-Type") != "application/json" or self.headers.get("Transfer-Encoding"): - return self._json(415, {"error": "Use a bounded JSON request"}) - try: - length = int(self.headers.get("Content-Length", "0")) - if not 0 < length <= 8192: - return self._json(413, {"error": "Action request is too large or empty"}) - self.connection.settimeout(15) - raw = self.rfile.read(length) - if len(raw) != length: - raise ValueError("Incomplete request") - result = manager.dispatch(self.path, self.headers, json.loads(raw)) - return self._json(200, result) - except PermissionError as error: - return self._json(403, {"error": str(error)}) - except (ValueError, KeyError, TypeError) as error: - return self._json(400, {"error": str(error)}) - except OSError as error: - return self._json(503, {"error": "Helper unavailable: " + str(error)}) - - def _json(self, code, value): - self._send(code, json.dumps(value, separators=(",", ":")).encode(), "application/json") - - def _send(self, code, body, kind, extra=None): - self.send_response(code) - for name, value in {**headers, **(extra or {}), "Content-Type": kind, - "Content-Length": str(len(body))}.items(): - self.send_header(name, value) - self.end_headers() - self.wfile.write(body) - - def log_message(self, *args): - pass - - return Handler - - -def is_loopback_bind(bind: str) -> bool: - """Whether ``bind`` names a loopback interface (``127.0.0.0/8``, ``::1``, or ``localhost``).""" - text = bind.strip() - if text.lower() == "localhost": - return True - try: - return ipaddress.ip_address(text).is_loopback - except ValueError: - return False - - -def default_bind(source: Source, *, authenticated: bool = False, - allow_unauthenticated_lan: bool = False) -> str: - """Default listen address: ``127.0.0.1`` unless authentication (``--password-file``) or - ``--allow-unauthenticated-lan`` is enabled, in which case Node A uses its LAN address - from the fabric document (else its management address).""" - if not authenticated and not allow_unauthenticated_lan: - return "127.0.0.1" - rows = (source.fabric or {}).get("positions") or [] - if rows and socket.gethostname() == rows[0]["hostname"]: - return rows[0].get("lan_address") or rows[0].get("address") or "127.0.0.1" - return "127.0.0.1" - -def service_url(fabric_path: Path = FABRIC_PATH, *, authenticated: bool = False, +__all__ = [ + "CLOCK_STEP_SECONDS", "CONTAINER_RE", "COUNTERS", "Collector", "DEFAULT_PORT", + "EXTERNAL_ID_RE", "EXTERNAL_KINDS", "EXTERNAL_PATH", "EXTERNAL_SCHEMA", "External", + "FABRIC_PATH", "FAILED_SECONDS", "FILES_SECONDS", "FLARE_COUNTERS", "FLARE_GAUGES", + "FLARE_JSON_KEYS", "FLARE_METRICS_PROBLEM", "FLARE_SERIES", "Fetched", + "HISTORY_DELTA_SAMPLES", "HISTORY_DEPLOYMENTS", "HISTORY_SAMPLES", "HISTORY_SECONDS", + "HISTORY_SPACING", "HISTORY_VALUES", "HOSTNAME_RE", "HTTP_TIMEOUT", "HistoryStore", + "LABELS", "LABEL_ESCAPE_RE", "LABEL_RE", "LOG_LINES", "MAX_EVENTS", "MAX_FILE_BYTES", + "MAX_RESPONSE_BYTES", "METRICS_VIEWED_SECONDS", "MODELS_SECONDS", "MODEL_TAIL_WORDS", + "Model", "NODE_REPORTS_PATH", "NODE_STATUS_PATH", "NoRedirect", "PAGE", + "QUIET_HOLDERS", "QUIET_LABEL_RE", "QUIET_PATH", "QUIET_SCHEMA", "QUIET_TTL_SECONDS", + "READ_ACCEPT", "READ_PATHS", "RECOVERY_PATH", "RUNTIME_REFRESH_SECONDS", + "ReadOnlyClient", "RequestRefused", "SCHEMA", "SETTING_KEYS", "SITE_PATH", + "SITE_SCHEMA", "Source", "ThreadingHTTPServer", "VIEWER_SECONDS", "_failure_kind", + "_ip", "_process_alive", "argparse", "capacity_from_cache_info", "chat_defaults", + "default_bind", "deployments_from_site", "efficiency_cpus", "external_rows", + "fabric_from_document", "hmac", "host_allowed", "is_loopback_bind", "known", + "layout_label", "listen_addresses", "log_commands", "lower_priority", "main", + "make_handler", "open_servers", "os", "page_bytes", "parallelism", + "parse_flare_as_metrics", "parse_flare_metrics", "parse_labels", "parse_metrics", + "quiet", "quiet_hold", "quiet_holders_directory", "quiet_release", "quiet_state", + "read_external", "read_json", "read_runtime_status", "read_transport", + "recovery_findings", "reload_on_hangup", "rendezvous_head", "request_url", + "run_name", "serve", "service_url", "short_model", "spark_cached_details", + "start_command", "thinking", "thinking_line", "thinking_record", "thinking_state", + "time", "unmanaged_groups", "url_of", +] + + +def service_url(fabric_path: Path | None = None, *, authenticated: bool = False, allow_unauthenticated_lan: bool = False) -> str: - """The address of the dashboard service on this Spark, by the service's default bind rule - (``default_bind``): loopback by default, or Node A's LAN address when authenticated or - explicitly opted in.""" - source = Source(fabric_path, SITE_PATH) - source.refresh() - bind = default_bind(source, authenticated=authenticated, - allow_unauthenticated_lan=allow_unauthenticated_lan) - literal = f"[{bind}]" if ":" in bind else bind - return f"http://{literal}:{DEFAULT_PORT}" - - -def listen_addresses(bind: str) -> list: - """The addresses to listen on: `bind`, then 127.0.0.1 unless `bind` is a loopback address or a - wildcard (0.0.0.0, ::), which already admits loopback connections.""" - try: - literal = ipaddress.ip_address(bind) - except ValueError: - return [bind, "127.0.0.1"] # a host name: its address is not known here - if literal.is_loopback or literal.is_unspecified: - return [bind] - return [bind, "127.0.0.1"] - - -def open_servers(addresses, port: int, handler, *, log=None) -> list: - """One HTTP server per address. The first address is the configured one and its failure raises; - a later one that cannot be bound (port taken, no such address) costs one line on stderr.""" - servers = [] - for index, address in enumerate(addresses): - family = socket.AF_INET6 if ":" in address else socket.AF_INET - server_class = type("DashboardServer", (ThreadingHTTPServer,), {"address_family": family}) - try: - server = server_class((address, port), handler) - except OSError as error: - if index == 0: - raise - (log or (lambda line: print(line, file=sys.stderr, flush=True)))( - f"sparkring dashboard: not listening on {address}:{port} ({error}); " - f"{addresses[0]}:{port} serves the page") - continue - server.daemon_threads = True - servers.append(server) - return servers - - -def url_of(address: str, port: int) -> str: - return f"http://[{address}]:{port}/" if ":" in address else f"http://{address}:{port}/" - - -def reload_on_hangup(collector: Collector, signals=signal) -> bool: - """Make SIGHUP (systemctl reload) re-read the host files at the collector's next cycle; False on - a platform without SIGHUP. Python's default for SIGHUP ends the process, and systemd counts an - end by SIGHUP as clean, so a reload before this ran would leave the service stopped: serve - installs it before anything else.""" - if not hasattr(signals, "SIGHUP"): - return False - signals.signal(signals.SIGHUP, lambda number, frame: collector.request_reload()) - return True + """The address of the dashboard service on this Spark, by ``default_bind``.""" + return _server.service_url( + FABRIC_PATH if fabric_path is None else fabric_path, + authenticated=authenticated, + allow_unauthenticated_lan=allow_unauthenticated_lan, + site_path=SITE_PATH, + ) def serve(args) -> int: - manager = None - if getattr(args, "manage", False): - if not hasattr(os, "geteuid") or os.geteuid() == 0: - raise ValueError("Dashboard manage mode must run as an unprivileged user") - if not args.manage_token_file or args.fabric or args.site: - raise ValueError("Manage mode requires --manage-token-file and this controller's default fabric/site") - from runtime.host.dashboard_actions import Manager - manager = Manager(Path(args.manage_token_file).read_text(encoding="utf-8").strip()) + """Run the dashboard collector and HTTP server.""" + manager = _server.build_manager(args) pairs = list(zip(args.fabric, args.site)) if args.fabric else [(FABRIC_PATH, SITE_PATH)] sources = [Source(Path(f), Path(s)) for f, s in pairs] - client = ReadOnlyClient() - collector = Collector(sources, client, quiet_path=Path(args.quiet_file), + collector = Collector(sources, ReadOnlyClient(), quiet_path=Path(args.quiet_file), node_status_path=None if args.no_node_status else NODE_STATUS_PATH, recovery_path=RECOVERY_PATH) reload_on_hangup(collector) placement = lower_priority(args.cpus) collector.cycle() - password = None - if args.password_file: - password = Path(args.password_file).read_text(encoding="utf-8").strip() - if not password: - raise ValueError(f"{args.password_file} is empty") - allow_unauthenticated_lan = bool(getattr(args, "allow_unauthenticated_lan", False)) - requested_bind = getattr(args, "bind", None) or getattr(args, "host", None) - if requested_bind: - if not is_loopback_bind(requested_bind) and password is None and not allow_unauthenticated_lan: - raise ValueError( - f"Refusing to bind unauthenticated dashboard to non-loopback address {requested_bind!r}; " - "configure --password-file PATH or opt in explicitly with --allow-unauthenticated-lan" - ) - bind = requested_bind - else: - bind = default_bind(sources[0], authenticated=password is not None, - allow_unauthenticated_lan=allow_unauthenticated_lan) + auth = _server.resolve_password(args.password_file) + bind = _server.resolve_bind(args, sources[0], auth) page, csp = page_bytes() names = frozenset(name.lower() for name in args.name or ()) - servers = open_servers(listen_addresses(bind), args.port, make_handler(collector, page, csp, names, password, manager)) - stop = threading.Event() - threading.Thread(target=collector.run, args=(stop,), daemon=True, name="collector").start() - for server in servers[1:]: - threading.Thread(target=server.serve_forever, daemon=True, name="listener").start() - where = " and ".join(url_of(server.server_address[0], server.server_address[1]) for server in servers) - print(f"SparkRing dashboard on {where} ({', '.join(placement) or 'default priority'}); " - f"{len(collector.models)} model API(s) from {len(sources)} fabric(s)", flush=True) - try: - servers[0].serve_forever() - finally: - stop.set() - return 0 - - -def quiet_holders_directory(quiet_path: Path) -> Path: - return Path(quiet_path).parent / QUIET_HOLDERS - - -def _process_alive(pid) -> bool: - """Whether process `pid` of this host runs. Only POSIX can ask without side effects; elsewhere - a holder's process counts as running and its time to live ends it.""" - if os.name != "posix": - return True - try: - os.kill(pid, 0) - except ProcessLookupError: - return False - except PermissionError: - return True # another user's process, such as a root harness seen by the dashboard's user - return True - - -def quiet_state(quiet_path: Path, now: float, *, alive=_process_alive) -> dict: - """{"quiet", "operator", "holders"}: whether quiet mode is held, by the operator's quiet file and - by which live measurement holders.""" - operator = Path(quiet_path).exists() - holders = [] - try: - entries = sorted(quiet_holders_directory(quiet_path).glob("*.json")) - except OSError: - entries = [] - for entry in entries: - try: - holder = json.loads(entry.read_text(encoding="utf-8")) - except (OSError, ValueError): - continue - if not isinstance(holder, dict) or holder.get("schema") != QUIET_SCHEMA: - continue - until, pid = holder.get("until"), holder.get("pid") - if not isinstance(until, (int, float)) or until <= now: - continue - if type(pid) is int and pid > 0 and holder.get("host") == socket.gethostname() and not alive(pid): - continue - holders.append({"id": entry.stem, "label": holder.get("label"), "pid": pid, "since": holder.get("since"), - "until": until}) - return {"quiet": operator or bool(holders), "operator": operator, "holders": holders} - - -def quiet_hold(quiet_path: Path, label: str, *, pid=None, ttl=QUIET_TTL_SECONDS, now=None) -> dict: - """Hold quiet mode for one measurement; returns its holder id and whether quiet mode was already held.""" - if not QUIET_LABEL_RE.fullmatch(label or ""): - raise ValueError(f"a holder label is 1 to 40 letters, digits, '.', '_' or '-', not {label!r}") - if not (type(ttl) is int and 1 <= ttl <= 7 * 24 * 3600): - raise ValueError("a holder's time to live is 1 s to 7 days") - now = time.time() if now is None else now - before = quiet_state(quiet_path, now) - directory = quiet_holders_directory(quiet_path) - directory.mkdir(parents=True, exist_ok=True) - holder_id = f"{label}-{pid or 0}-{os.urandom(4).hex()}" - path = directory / f"{holder_id}.json" - temporary = path.with_name(path.name + ".writing") - temporary.write_text(json.dumps({"schema": QUIET_SCHEMA, "label": label, "pid": pid, "host": socket.gethostname(), - "since": now, "until": now + ttl}) + "\n", encoding="utf-8") - temporary.replace(path) - return {"holder": holder_id, "was_quiet": before["quiet"], "until": now + ttl} - - -def quiet_release(quiet_path: Path, holder_id: str) -> dict: - """End one measurement's hold; quiet mode stays on while the operator or another holder holds it.""" - if not QUIET_LABEL_RE.fullmatch(holder_id.split("-", 1)[0]) or "/" in holder_id or "\\" in holder_id: - raise ValueError(f"not a quiet holder id: {holder_id!r}") - (quiet_holders_directory(quiet_path) / f"{holder_id}.json").unlink(missing_ok=True) - return {"released": holder_id, "still_quiet": quiet_state(quiet_path, time.time())["quiet"]} - - -def quiet(args) -> int: - path = Path(args.quiet_file) - if args.state == "on": - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text("The SparkRing dashboard sends no request while this file exists.\n", encoding="utf-8") - print(f"Dashboard paused: {path} exists; it sends no request until sparkring dashboard quiet off.") - elif args.state == "off": - path.unlink(missing_ok=True) - holders = quiet_state(path, time.time())["holders"] - print("Dashboard collecting again." if not holders else - "The operator's pause is off; the dashboard stays quiet while these measurements hold it: " - + ", ".join(f"{h['label']} (pid {h['pid']})" for h in holders)) - elif args.state == "status": - print(json.dumps(quiet_state(path, time.time()), indent=2)) - elif args.state == "hold": - print(json.dumps(quiet_hold(path, args.label, pid=args.pid, ttl=args.ttl))) - else: - print(json.dumps(quiet_release(path, args.holder))) - return 0 + servers = open_servers(listen_addresses(bind), args.port, + make_handler(collector, page, csp, names, auth, manager)) + return _server.run_servers(collector, servers, placement, len(sources)) def main(argv=None) -> int: diff --git a/runtime/host/dashboard_client.py b/runtime/host/dashboard_client.py new file mode 100644 index 00000000..b7338d9a --- /dev/null +++ b/runtime/host/dashboard_client.py @@ -0,0 +1,131 @@ +"""Read-only HTTP egress client for ``sparkring dashboard``. + +``ReadOnlyClient.get`` is the dashboard's single network egress choke-point: +GET requests without a body, restricted to ``READ_PATHS``, directed only to +addresses named in host files, with redirects disabled (``NoRedirect``), +environment proxies ignored, and a hard response byte cap and deadline. +""" +from __future__ import annotations + +import collections +import socket +import threading +import time +import urllib.error +import urllib.request + +# The only paths the collector requests: the model list, serving-engine Prometheus metrics, +# and the runtime-status plugin's JSON report. Each is a GET that runs no model. +READ_PATHS = frozenset({"/metrics", "/v1/models", "/v1/sparkring/status"}) +READ_ACCEPT = { + "/metrics": "text/plain", + "/v1/models": "application/json", + "/v1/sparkring/status": "application/json", +} +HTTP_TIMEOUT = 2.0 +MAX_RESPONSE_BYTES = 8 * 1024 * 1024 + + +class RequestRefused(ValueError): + """A request the dashboard must never send: not a GET, not a read path, or not a known address.""" + + +def request_url(host, port, path, allowed_hosts) -> str: + """The URL of one permitted read; RequestRefused for anything else. + + `path` must be exactly one of READ_PATHS (no query, no other path), `host` one of + `allowed_hosts` (the addresses the host files name) and `port` a TCP port.""" + if path not in READ_PATHS: + raise RequestRefused(f"the dashboard reads only {', '.join(sorted(READ_PATHS))}, not {path!r}") + if host not in allowed_hosts: + raise RequestRefused(f"{host!r} is not an address the fabric document or site file names") + if type(port) is not int or not 0 < port < 65536: + raise RequestRefused(f"{port!r} is not a TCP port") + literal = f"[{host}]" if ":" in host else host + return f"http://{literal}:{port}{path}" + + +class Fetched: + """The outcome of one read: `body` on success, else `failure` (refused, timeout, unreachable, + http) with `code` for an HTTP error status.""" + + def __init__(self, body=None, failure=None, code=None): + self.body, self.failure, self.code = body, failure, code + + @property + def ok(self) -> bool: + return self.failure is None + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + """A read endpoint cannot widen the permitted address, port or path by redirecting.""" + + def redirect_request(self, request, fp, code, message, headers, newurl): + return None + + +class ReadOnlyClient: + """Sends the collector's GET requests and counts them; the module's only network egress. + + `opener` is a urllib opener; the default ignores proxy settings from the environment, so + requests to Spark addresses never leave through a proxy.""" + + def __init__(self, opener=None, timeout=HTTP_TIMEOUT): + self.opener = opener or urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) + self.timeout = timeout + self.allowed: frozenset = frozenset() + self.lock = threading.Lock() + self.requests = collections.Counter() # path -> requests sent + self.received = 0 # response bytes + + def allow(self, hosts) -> None: + self.allowed = frozenset(hosts) + + def get(self, host, port, path) -> Fetched: + url = request_url(host, port, path, self.allowed) + request = urllib.request.Request(url, method="GET", headers={ + "User-Agent": "sparkring-dashboard", "Accept": READ_ACCEPT[path]}) + if request.get_method() != "GET" or request.data is not None: + raise RequestRefused("the dashboard sends GET requests without a body only") + with self.lock: + self.requests[path] += 1 + try: + with self.opener.open(request, timeout=self.timeout) as response: + deadline = time.monotonic() + self.timeout + chunks, size = [], 0 + # read1 performs at most one underlying socket read. A peer that + # drips bytes cannot keep an unbounded read() alive indefinitely. + while size <= MAX_RESPONSE_BYTES: + if time.monotonic() >= deadline: + raise TimeoutError("metrics response deadline exceeded") + chunk = response.read1(min(65536, MAX_RESPONSE_BYTES + 1 - size)) + if not chunk: + break + chunks.append(chunk) + size += len(chunk) + body = b"".join(chunks) + except urllib.error.HTTPError as error: + return Fetched(failure="http", code=error.code) + except urllib.error.URLError as error: + return Fetched(failure=_failure_kind(error.reason)) + except (TimeoutError, socket.timeout): + return Fetched(failure="timeout") + except OSError as error: + return Fetched(failure=_failure_kind(error)) + with self.lock: + self.received += len(body) + if len(body) > MAX_RESPONSE_BYTES: + return Fetched(failure="too_large") + return Fetched(body=body) + + def counters(self) -> dict: + with self.lock: + return {"requests": dict(self.requests), "received_bytes": self.received} + + +def _failure_kind(reason) -> str: + if isinstance(reason, ConnectionRefusedError): + return "refused" + if isinstance(reason, (TimeoutError, socket.timeout)): + return "timeout" + return "unreachable" diff --git a/runtime/host/dashboard_collector.py b/runtime/host/dashboard_collector.py new file mode 100644 index 00000000..7adfb47e --- /dev/null +++ b/runtime/host/dashboard_collector.py @@ -0,0 +1,1029 @@ +"""Periodic snapshot collector, history ring-buffer, and ring/member state assembly.""" +from __future__ import annotations + +import collections +from concurrent.futures import ThreadPoolExecutor +import json +from pathlib import Path +import socket +import sys +import threading +import time + +from runtime.common import engine_adapter, thinking +from runtime.host import startup +from runtime.host.dashboard_client import Fetched, ReadOnlyClient +from runtime.host.dashboard_parsers import ( + FLARE_METRICS_PROBLEM, + LABELS, + capacity_from_cache_info, + layout_label, + parse_flare_as_metrics, + parse_flare_metrics, + parse_metrics, + read_runtime_status, + run_name, + short_model, +) +from runtime.host.dashboard_quiet import QUIET_PATH, quiet_state +from runtime.host.dashboard_rates import number, plugin_fresh +from runtime.host.dashboard_sources import ( + EXTERNAL_PATH, + SITE_SCHEMA, + Source, + deployments_from_site, + log_commands, + parallelism, + read_external, + read_json, + recovery_findings, + spark_cached_details, + start_command, + thinking_state, + unmanaged_groups, +) + +SCHEMA = "sparkring-dashboard/v1" +NODE_STATUS_PATH = Path("/run/sparkring/status.json") +NODE_REPORTS_PATH = Path("/var/lib/sparkring/dashboard/nodes.json") +RECOVERY_PATH = Path("/var/lib/sparkring/recovery.json") + +METRICS_VIEWED_SECONDS = 2.0 +HISTORY_SECONDS = 3 * 3600 +HISTORY_SAMPLES = 2161 +HISTORY_SPACING = 5.0 +HISTORY_DEPLOYMENTS = 8 +HISTORY_DELTA_SAMPLES = 120 +HISTORY_VALUES = ( + "gen", "prompt", "accepted", "drafts", "draft_tokens", "steps", "ttft_sum", "ttft_count", + "pc_hits", "pc_queries", "step_seconds", "step_accepted", "running", "waiting", "kv", +) +MODELS_SECONDS = 60.0 +VIEWER_SECONDS = 6.0 +FILES_SECONDS = 30.0 +RUNTIME_REFRESH_SECONDS = 300.0 +FAILED_SECONDS = 15.0 # a model API that does not answer is asked again after this long +MAX_EVENTS = 200 +CLOCK_STEP_SECONDS = 2.0 # a cycle whose clock reads this much earlier than the last one's saw a step back + + +class Model: + """One deployment's API endpoint: raw observations and state.""" + + def __init__(self, source: Source, row: dict): + self.source = source + self.row = row + self.key = (source.ring_id(), row["id"]) + self.id = f"{source.ring_id()}:{row['id']}" + self.state = None + self.state_since = None + self.model = row.get("model") + self.max_model_len = None + self.metrics = None + self.capacity = None + self.runtime = None + self.run_key = None # identifies the model run whose runtime status was read + self.runtime_due = True + self.runtime_requested_at = None + self.next_metrics = 0.0 + self.next_models = 0.0 + self.last_ok = None + self.models_ok_at = None + self.metrics_at = None + self.history_sample = None + + def observe_metrics(self, metrics: dict, now: float) -> None: + self.metrics = metrics + self.metrics_at = now + self.capacity = capacity_from_cache_info(metrics.get("cache_info")) or self.capacity + if metrics.get("model_name"): + self.model = metrics["model_name"] + run_key = (self.model, metrics.get("started")) + if run_key != self.run_key: + self.run_key, self.runtime_due = run_key, True + self.last_ok = now + + +class External: + """One endpoint of the external list: what its /metrics and /v1/models said, and its state.""" + + def __init__(self, row: dict): + self.row = row + self.id = "external:" + row["id"] + self.state = None + self.state_since = None + self.model = None + self.root = None + self.max_model_len = None + self.metrics = None + self.metrics_at = None + self.sample = None # (generated_tokens, at) of the previous /metrics read + self.output_tps = None + self.next_metrics = 0.0 + self.next_models = 0.0 + + def observe_metrics(self, metrics: dict, now: float) -> None: + generated = metrics.get("generated_tokens") + if generated is not None and self.sample is not None and now > self.sample[1] and generated >= self.sample[0]: + self.output_tps = (generated - self.sample[0]) / (now - self.sample[1]) + if generated is not None: + self.sample = (generated, now) + else: + self.sample, self.output_tps = None, None + self.metrics, self.metrics_at = metrics, now + + +class HistoryStore: + """Bounded per-deployment raw counter ring-buffer with restart/gap boundaries.""" + + def __init__(self): + self.rows: dict = {} + self.seq: int = 0 + self.gaps: set = set() + + def prune(self, active_models, now: float) -> None: + for model_id in list(self.rows): + if model_id not in active_models: + del self.rows[model_id] + continue + rows = self.rows[model_id] + while rows and rows[0]["counters"]["at"] < now - HISTORY_SECONDS: + rows.popleft() + while rows and rows[-1]["observed_at"] > now: + rows.pop() + self.gaps.intersection_update(active_models) + + def remember(self, model: Model, plugin: dict | None, now: float) -> None: + """Retain only bounded raw numeric fields, never rates or mutable source documents. + + Each sample carries exactly one source. A fresh stat-logger snapshot is + stored as the plugin payload alone; only a cycle without one stores the + /metrics read, so the label and the values can never diverge and no + sample mixes plugin and /metrics counters. + """ + if model.id not in self.rows: + if len(self.rows) >= HISTORY_DEPLOYMENTS: + return + self.rows[model.id] = collections.deque(maxlen=HISTORY_SAMPLES) + rows = self.rows[model.id] + if model.state != "serving" or (not plugin and not number(model.metrics_at)): + self.gaps.add(model.id) + return + metrics = model.metrics or {} + if plugin: + sample = {k: plugin[k] for k in (*HISTORY_VALUES, "at", "monotonic") if number(plugin.get(k))} | { + "source": "plugin", "schema": "sparkring-stats/v1", "run_id": plugin["run_id"], + "step_timing": bool(plugin.get("step_timing"))} + else: + sample = {"source": "metrics", "at": model.metrics_at, "run_id": metrics.get("started"), + "values": {k: metrics[k] for k in HISTORY_VALUES if number(metrics.get(k))}} + at = sample["at"] + if not number(at) or now - at > (180 if plugin else 125): + self.gaps.add(model.id) + return + # Inspect every live observation before thinning the archive. A reset + # between retained rows still creates a boundary, even if its counters + # have already exceeded the last archived value by the next archive tick. + last = model.history_sample + if last: + before = last.get("values", last) + values = sample.get("values", sample) + if ((last["source"], last["run_id"]) != (sample["source"], sample["run_id"]) + or sample.get("monotonic", at) < last.get("monotonic", last["at"]) + or any(number(values.get(k)) and number(before.get(k)) and values[k] < before[k] + for k in HISTORY_VALUES if k not in ("running", "waiting", "kv"))): + self.gaps.add(model.id) + model.history_sample = sample + # Snapshot identity is independent of the collector's read time and fallback reads. + previous = rows[-1]["counters"] if rows else None + if previous and (rows[-1]["source"], previous["run_id"], + previous.get("monotonic", previous["at"])) == ( + sample["source"], sample["run_id"], sample.get("monotonic", at)): + return + if previous and model.id not in self.gaps and 0 <= at - previous["at"] < HISTORY_SPACING: + return + self.seq += 1 + rows.append({"seq": self.seq, "observed_at": now, "source": sample["source"], + "counters": sample, "boundary": model.id in self.gaps}) + self.gaps.discard(model.id) + + def delta(self, model_id: str, since: int | None) -> list: + rows = self.rows.get(model_id, ()) + items = list(rows)[-1:] if since is None else [r for r in rows if r["seq"] > since] + if len(items) > HISTORY_DELTA_SAMPLES: + items = items[-HISTORY_DELTA_SAMPLES:] + items[0] = {**items[0], "boundary": True} + return items + + def snapshot(self, active_models, now: float, service_started: float) -> dict: + self.prune(active_models, now) + return {"generated_at": now, "service_started": service_started, "history_cursor": self.seq, + "counter_history": {key: list(rows) for key, rows in self.rows.items()}} + + +class Collector: + """Decides which reads are due, sends them through the client and keeps the results.""" + + def __init__(self, sources, client: ReadOnlyClient, *, quiet_path: Path = QUIET_PATH, + node_status_path: Path | None = NODE_STATUS_PATH, recovery_path: Path | None = RECOVERY_PATH, + node_reports_path: Path | None = NODE_REPORTS_PATH, + live_path=Path("/run/sparkring/dashboard-live.json"), + viewer_path=Path("/run/sparkring-dashboard/viewer"), + external_path: Path | None = EXTERNAL_PATH, + clock=time.time, cpu_clock=time.process_time): + self.sources = list(sources) + self.client = client + self.external_path = Path(external_path) if external_path else None + self.externals: dict = {} # endpoint id -> External, from the external list file + self.external_stamp = None + self.external_problem = None + self.quiet_path = Path(quiet_path) if quiet_path else None + self.node_status_path = Path(node_status_path) if node_status_path else None + self.recovery_path = Path(recovery_path) if recovery_path else None + self.node_reports_path = Path(node_reports_path) if node_reports_path else None + self.node_reports = [] + self.live_path, self.viewer_path = live_path, viewer_path + self.live_telemetry = {} + self.live_startup, self.operations = {}, [] + self.next_lease = 0 + self.recovery: dict = {} # deployment directory name -> the recovery timer's latest finding + self.clock, self.cpu_clock = clock, cpu_clock + self.lock = threading.Lock() + self.models: dict = {} + self.events: collections.deque = collections.deque(maxlen=MAX_EVENTS) + self.started = clock() + self.last_view = None + self.next_files = 0.0 + self.reload_requested = threading.Event() # SIGHUP: re-read the host files at the next cycle + self.last_cycle = None + self.quiet = False + self.node_status = None + self.cycles = 0 + self.cycle_cpu = collections.deque(maxlen=120) # CPU seconds of recent cycles that sent requests + self.history_store = HistoryStore() + self.history = self.history_store.rows + self.history_gaps = self.history_store.gaps + + @property + def history_seq(self) -> int: + return self.history_store.seq + + @history_seq.setter + def history_seq(self, value: int) -> None: + self.history_store.seq = value + + # -- inputs ---------------------------------------------------------------------------- + def viewed(self, now) -> bool: + return self.last_view is not None and now - self.last_view <= VIEWER_SECONDS + + def mark_viewed(self, now=None) -> None: + """A browser fetched the status: poll at the viewed cadence from now on.""" + now = self.clock() if now is None else now + with self.lock: + was = self.viewed(now) + self.last_view = now + if self.viewer_path and now >= self.next_lease: + try: + self.viewer_path.touch() + except OSError: + pass + self.next_lease = now + METRICS_VIEWED_SECONDS + if not was: + for model in self.models.values(): + model.next_metrics = min(model.next_metrics, now) + + def request_runtime(self, model_id: str, now=None) -> bool: + """Read one model's runtime status again at the next cycle; at most once per RUNTIME_REFRESH_SECONDS.""" + now = self.clock() if now is None else now + with self.lock: + model = self.models.get(model_id) + if model is None or (model.runtime_requested_at is not None + and now - model.runtime_requested_at < RUNTIME_REFRESH_SECONDS): + return False + model.runtime_requested_at, model.runtime_due = now, True + return True + + def request_reload(self) -> None: + """Re-read every host file at the next cycle (the SIGHUP handler; systemctl reload).""" + self.reload_requested.set() + + def read_status_files(self) -> None: + self.node_reports = [] + if self.node_reports_path is not None: + try: + doc = read_json(self.node_reports_path) + if doc.get("schema") == "sparkring-dashboard-nodes/v1" and isinstance(doc.get("nodes"), list): + self.node_reports = doc["nodes"][:256] + except (OSError, ValueError, AttributeError): + pass + if self.node_status_path is not None: + try: + self.node_status = read_json(self.node_status_path) + except (OSError, ValueError): + self.node_status = None + if self.recovery_path is not None: + self.recovery = recovery_findings(self.recovery_path) + self.reload_externals() + + def reload_externals(self) -> None: + """Re-read the external list when its stamp changed; keep each listed endpoint's state across re-reads.""" + if self.external_path is None: + return + try: + stat = self.external_path.stat() + stamp = (stat.st_dev, stat.st_ino, stat.st_mtime_ns, stat.st_size) + except OSError: + stamp = None + if stamp == self.external_stamp and self.external_stamp is not None: + return + self.external_stamp = stamp + try: + rows = read_external(self.external_path) + self.external_problem = None + except (OSError, ValueError) as error: + rows, self.external_problem = [], str(error) + with self.lock: + wanted = {row["id"]: row for row in rows} + for identifier in [i for i in self.externals if i not in wanted]: + del self.externals[identifier] + for identifier, row in wanted.items(): + current = self.externals.get(identifier) + if current is None or (current.row["host"], current.row["port"]) != (row["host"], row["port"]): + self.externals[identifier] = External(row) + else: + current.row = row + + def reload_sources(self, force: bool = False) -> None: + """Re-read each fabric's document and site file whose stamp changed (all of them when + `force`), and follow the deployments they list: a model per row, kept across re-reads.""" + for source in self.sources: + source.refresh(force) + hosts, wanted = set(), {} + for source in self.sources: + unmanaged = unmanaged_groups(source.fabric, [*self.node_reports, self.node_status], source.deployments, + self.last_cycle if self.last_cycle is not None else self.clock()) if source.fabric else [] + hidden = {r["id"] for group in unmanaged for r in group["stopped_records"]} + pending = deployments_from_site({"schema": SITE_SCHEMA, "deployments": [op["deployment"] for op in self.operations]}, + len(source.fabric["positions"])) if source is self.sources[0] and source.fabric else [] + occupied = {p for row in pending for p in row["positions"]} + rows = [r for r in source.deployments if r["id"] not in hidden and not occupied.intersection(r["positions"])] + for row in rows + pending + [r for r in unmanaged if not occupied.intersection(r["positions"])]: + if row["api_host"]: + hosts.add(row["api_host"]) + wanted[(source.ring_id(), row["id"])] = (source, row) + with self.lock: + hosts.update(external.row["host"] for external in self.externals.values()) + self.client.allow(hosts) + with self.lock: + for model_id in [m for m, model in self.models.items() if model.key not in wanted]: + del self.models[model_id] + known = {model.key: model for model in self.models.values()} + for key, (source, row) in wanted.items(): + if key in known: + if (known[key].row.get("api_host"), known[key].row.get("api_port"), known[key].row.get("containers")) != ( + row.get("api_host"), row.get("api_port"), row.get("containers")) and row.get("unmanaged"): + fresh = Model(source, row) + self.models[fresh.id] = fresh + self.history_gaps.add(fresh.id) + known[key].row = row + else: + model = Model(source, row) + self.models[model.id] = model + + # -- one cycle ------------------------------------------------------------------------- + def clock_went_back(self, now: float) -> None: + """The wall clock stepped back, as an NTP correction after boot or a manual date does. + + Every schedule here is kept in that clock, so each read would otherwise wait out the whole + step: the reads fall due now. Raw observations from the clock's future are invalidated, + and a viewer or a state that the old clock dated later than now is dated now.""" + print(f"sparkring dashboard: the clock went back by {self.last_cycle - now:.0f} s; reads rescheduled", + file=sys.stderr, flush=True) + self.next_files = now + self.next_lease = now + with self.lock: + self.history_gaps.update(self.models) + if self.last_view is not None and self.last_view > now: + self.last_view = now + for model in self.models.values(): + model.next_metrics = min(model.next_metrics, now) + model.next_models = min(model.next_models, now) + if model.runtime_requested_at is not None and model.runtime_requested_at > now: + model.runtime_requested_at = None + if model.state_since is not None and model.state_since > now: + model.state_since = now + model.metrics_at = None + + def cycle(self, now=None) -> None: + now = self.clock() if now is None else now + if self.last_cycle is not None and now < self.last_cycle - CLOCK_STEP_SECONDS: + self.clock_went_back(now) + self.last_cycle = now + # Host files first, in quiet mode too: two stats a second, and no request to any Spark. + forced = self.reload_requested.is_set() + if forced: + self.reload_requested.clear() + if forced or now >= self.next_files: + self.read_status_files() + self.next_files = now + FILES_SECONDS + self.read_live(now) + self.reload_sources(forced) + # Quiet mode is checked on every cycle (a stat and a small directory listing a second), so a + # hold takes effect before a measurement that starts right after it. + self.quiet = bool(self.quiet_path and quiet_state(self.quiet_path, now)["quiet"]) + with self.lock: + self.prune_history(now) + if self.quiet: + with self.lock: + self.history_gaps.update(self.models) + return + before = self.cpu_clock() + sent = False + with self.lock: + models = list(self.models.values()) + viewed = self.viewed(now) + # One outstanding request per group, at most eight workers. Independent + # heads cannot serialize healthy samples behind a slow head's timeout. + if len(models) > 1 and viewed: + with ThreadPoolExecutor(max_workers=8, thread_name_prefix="dashboard-metrics") as pool: + sent = any(list(pool.map(lambda model: self.poll(model, now, viewed), models))) + else: + for model in models: + sent = self.poll(model, now, viewed) or sent + with self.lock: + externals = list(self.externals.values()) + for external in externals: + sent = self.poll_external(external, now, viewed) or sent + with self.lock: + for model in models: + if viewed: + self.remember(model, now) + else: + self.history_gaps.add(model.id) + if sent: + self.cycle_cpu.append(self.cpu_clock() - before) + self.cycles += 1 + + def read_live(self, now): + self.live_telemetry, self.live_startup, self.operations = {}, {}, [] + if not self.viewed(now) or not self.live_path or (self.quiet_path and quiet_state(self.quiet_path, now)["quiet"]): + return + try: + live = read_json(self.live_path) + if number(live.get("at")) and -5 <= now - live["at"] <= 6: + self.live_telemetry = live.get("telemetry", {}) + raw = live.get("startup", {}) + self.live_startup = startup.project(raw, list(raw)[:8], now) + self.operations = [op for op in live.get("operations", [])[:8] + if isinstance(op, dict) and isinstance(op.get("deployment"), dict) + and op.get("phase") in startup.PHASES and number(op.get("started_at")) + and number(op.get("at")) and -5 <= now - op["at"] <= 6] + except (OSError, ValueError, AttributeError, TypeError): + pass + + def startup_status(self, model): + deployment = model.row.get("deployment_id") + ranks = startup.group(self.live_startup.get(deployment, []), model.row["positions"]) + operation = next((op for op in self.operations if op["deployment"].get("deployment_id") == deployment), None) + if operation: + # A previous run's containers must not hide checkpoint preparation. + if not ranks or ranks["started_at"] < operation["started_at"] or ranks["phase"] == "starting": + return {k: v for k, v in operation.items() if k != "deployment"} + ranks["started_at"] = min(operation["started_at"], ranks["started_at"]) + return ranks + + def poll(self, model: Model, now: float, viewed: bool) -> bool: + """Send the reads that are due for one model; True when any request was sent. + + A model whose /metrics answer is serving: vLLM's API server listens only once its engine + is ready. A refused connection is a stopped model, a timeout an unreachable Spark and an + HTTP error a model still starting. A /metrics answer that names a different model means + another deployment of an overlapping slot holds the port, and this one is idle. A deployment + 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 + if row["stopped"]: + 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) + if starting and (starting["phase"] == "failed" or starting["started_at"] > (model.metrics_at or 0)) and model.state == "serving": + model.next_metrics = min(model.next_metrics, now) + sent = False + 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) + 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 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: + model.metrics = None + model.metrics_at = None + else: + state = "serving" + with self.lock: + model.observe_metrics(metrics, now) + model.next_metrics = now + cadence + else: + state = {"refused": "stopped", "timeout": "offline", "unreachable": "offline"}.get( + fetched.failure, "not_ready") + if row["stopped"]: + state = "stopped" # the records say its last operation stopped it + 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: + model.next_models = now + MODELS_SECONDS + listed = self.models_listed(self.client.get(host, port, "/v1/models")) + if listed: + state = "serving" + with self.lock: + 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 + with self.lock: + model.metrics = None + model.metrics_at = None + model.next_metrics = now + max(cadence, FAILED_SECONDS) + model.api_state = state + state = getattr(model, "api_state", model.state) + if starting and (state != "serving" or starting["phase"] in ("installing", "failed")): + state = "starting" if starting["phase"] == "ready" else starting["phase"] + self.set_state(model, state, now) + if model.state == "serving" and now >= model.next_models: + sent = True + model.next_models = now + MODELS_SECONDS + listed = self.models_listed(self.client.get(host, port, "/v1/models")) + if listed: + with self.lock: + 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 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") + runtime = None + if fetched.ok: + try: + runtime = read_runtime_status(json.loads(fetched.body)) + except (ValueError, AttributeError, TypeError): + runtime = None + with self.lock: + model.runtime = runtime + return sent + + def poll_external(self, external: External, now: float, viewed: bool) -> bool: + """Send the reads due for one external endpoint; True when any request was sent. + + An endpoint whose /metrics answers is serving; a refused connection means nothing listens, + a timeout an unreachable host and an HTTP error a server that is not ready. /v1/models is + read once a minute while it serves, for the model's name, root and context length.""" + if not viewed: + return False + row = external.row + host, port = row["host"], row["port"] + sent = False + if external.state == "serving" and external.metrics_at is not None: + external.next_metrics = min(external.next_metrics, external.metrics_at + METRICS_VIEWED_SECONDS) + if now >= external.next_metrics: + sent = True + fetched = self.client.get(host, port, "/metrics") + if fetched.ok: + metrics = parse_flare_metrics(fetched.body.decode("utf-8", "replace")) if row["kind"] == "flare" else {} + with self.lock: + external.observe_metrics(metrics, now) + state = "serving" + external.next_metrics = now + METRICS_VIEWED_SECONDS + else: + state = {"refused": "stopped", "timeout": "offline", "unreachable": "offline"}.get(fetched.failure, "not_ready") + with self.lock: + external.metrics, external.metrics_at, external.output_tps, external.sample = None, None, None, None + external.next_metrics = now + max(METRICS_VIEWED_SECONDS, FAILED_SECONDS) + self.set_external_state(external, state, now) + if external.state == "serving" and now >= external.next_models: + sent = True + external.next_models = now + MODELS_SECONDS + listed = self.models_listed(self.client.get(host, port, "/v1/models")) + if listed: + with self.lock: + external.model = listed.get("id") or external.model + external.root = listed.get("root") or external.root + external.max_model_len = listed.get("max_model_len") or external.max_model_len + return sent + + def set_external_state(self, external: External, state: str, now: float) -> None: + with self.lock: + if state == external.state: + return + previous, external.state, external.state_since = external.state, state, now + if previous is not None or state == "serving": + self.events.append({"at": now, "stack": external.row["label"], "text": LABELS[state], + "kind": state}) + + def external_member(self, external: External, now: float) -> dict: + """One external endpoint as the page shows it: identity, state and the figures of its last read.""" + row, metrics = external.row, external.metrics or {} + serving = external.state == "serving" + + def ratio(numerator, denominator): + top, bottom = metrics.get(numerator), metrics.get(denominator) + return (top / bottom) if top is not None and bottom else None + + stats = None + if serving and metrics: + kv_total, kv_free = metrics.get("kv_tokens_total"), metrics.get("kv_tokens_free") + stats = {"output_tps": external.output_tps, + "tokens_last_minute": metrics.get("tokens_last_minute"), + "active_requests": metrics.get("active_requests"), "pending_requests": metrics.get("pending_requests"), + "request_capacity": metrics.get("request_capacity"), + "kv_in_use": ((kv_total - kv_free) / kv_total) if kv_total and kv_free is not None else None, + "kv_tokens_total": kv_total, "kv_tokens_cached": metrics.get("kv_tokens_cached"), + "uptime_seconds": metrics.get("uptime_seconds"), + "generated_tokens": metrics.get("generated_tokens"), "prefill_tokens": metrics.get("prefill_tokens"), + "requests_completed": metrics.get("requests_completed"), "requests_failed": metrics.get("requests_failed"), + "http_requests": metrics.get("http_requests"), + "draft_acceptance": ratio("drafts_accepted", "drafts_offered"), + "row_cache_hit_rate": (metrics["row_cache_hits"] / (metrics["row_cache_hits"] + metrics["row_cache_misses"]) + if metrics.get("row_cache_hits") is not None and metrics.get("row_cache_misses") is not None + and metrics["row_cache_hits"] + metrics["row_cache_misses"] else None), + "prefix_hit_rate": ratio("prefix_hits", "prefix_lookups")} + return {"id": external.id, "label": row["label"], "kind": row["kind"], "host": row["host"], "port": row["port"], + "position": row.get("position"), + "endpoint": f"http://{row['host']}:{row['port']}/v1", "metrics_url": f"http://{row['host']}:{row['port']}/metrics", + "state": external.state, "state_label": LABELS[external.state], "state_since": external.state_since, + "model": external.model, "root": external.root, "max_model_len": external.max_model_len, + "metrics_problem": FLARE_METRICS_PROBLEM if serving and row["kind"] == "flare" and not metrics else None, + "metrics_at": external.metrics_at, "stats": stats} + + def external_ring_member(self, external: External, source: Source, now: float, color: int) -> dict: + """An external endpoint placed on a ring, in the shape of member(): a one-Spark group at its listed + position, with the endpoint's figures as ``live`` and its card document under the same keys as + external_member().""" + card = self.external_member(external, now) + row, stats = external.row, card["stats"] + position = row["position"] + spark = next((p for p in source.fabric["positions"] if p["position"] == position), {}) + serving = external.state == "serving" + runtime_name = "Flare" if row["kind"] == "flare" else "OpenAI API" + return { + **card, + "name": run_name([position]), "profile": None, "start_command": None, + "unmanaged": False, "gpu_job": False, "launch": {}, + "ownership_label": "Not installed by SparkRing: no automatic recovery, no install record", + "group_note": None, "containers": [], "stopped_records": [], + "startup": None, "spark_startup": None, + "model_short": short_model(external.model), "details_url": None, + "layout": {"label": runtime_name, "count": 1, "tp": 1, "dcp": None}, + "live": {"output_tps": stats["output_tps"], "running": stats["active_requests"], + "waiting": stats["pending_requests"], "kv": stats["kv_in_use"], "read_at": external.metrics_at} + if stats else None, + "counters": None, "plugin_counters": None, "counter_samples": [], + "totals": {"finished": stats["requests_completed"], "preemptions": None, + "output_tokens": stats["generated_tokens"], "prompt_tokens": stats["prefill_tokens"]} + if stats else None, + "thinking": None, "thinking_default": None, "thinking_provenance": None, + "settings": None, "nodes": [], "capacity": None, "workers": None, "image": None, "transport": None, + "sparks": [{"name": spark.get("hostname", str(position)), "address": spark.get("address"), + "lan_address": spark.get("lan_address"), "up": True if serving else None, + "position": position, "container": None}], + "history": [], + "arc": {"positions": [position], "first": position, "last": position, "size": 1, + "run": run_name([position]), "source": "external", "source_label": "external endpoint list", + "inferred": False, "detail": None, "color": color}, + "ring": source.ring_id(), + "head": {"position": position, "name": spark.get("hostname"), "address": row["host"], "port": row["port"], + "container": None}, + "logs": log_commands(spark.get("hostname"), None), + "runtime_read": False, "recovery": None, "external": True, + } + + @staticmethod + def models_listed(fetched: Fetched) -> dict | None: + if not fetched.ok: + return None + try: + data = json.loads(fetched.body).get("data") or [] + except (ValueError, AttributeError): + return None + return data[0] if data and isinstance(data[0], dict) else None + + def set_state(self, model: Model, state: str, now: float) -> None: + with self.lock: + if state == model.state: + return + previous, model.state, model.state_since = model.state, state, now + if state != "serving": + model.runtime = None if state != "not_ready" else model.runtime + text = LABELS[state] + (f": {model.model}" if state == "serving" and model.model else "") + if previous is not None or state == "serving": + self.events.append({"at": now, "stack": run_name(model.row["positions"]), "text": text, + "kind": state}) + + def run(self, stop: threading.Event) -> None: + while not stop.is_set(): + cycle_started = time.monotonic() + try: + self.cycle() + except Exception as error: # one bad response must not stop the page + print(f"sparkring dashboard: collection failed: {error!r}", file=sys.stderr, flush=True) + stop.wait(max(0.05, 1.0 - (time.monotonic() - cycle_started))) + + # -- the status document ----------------------------------------------------------------- + def plugin_snapshot(self, model, now): + fallback = {"run_id": (model.metrics or {}).get("started")} + deployment = model.row.get("deployment_id") + # The root agent forwards head snapshots through the existing SSH path. + # This service reads only its local projection and the inventory cache. + reports = [self.node_status, *self.node_reports] + candidates = [self.live_telemetry.get(deployment)] + [report["telemetry"].get(deployment) for report in reports + if isinstance(report, dict) and isinstance(report.get("telemetry"), dict)] + candidates.append((self.recovery.get(model.row["id"]) or {}).get("telemetry")) + fresh = [p for p in candidates if plugin_fresh(p, fallback, now) + and (not self.viewed(now) or now - p["at"] <= 12)] + chosen = max(fresh, key=lambda p: p["at"], default=None) + metrics = model.metrics or {} + if (chosen and number(model.metrics_at) and model.metrics_at > chosen["at"] + and metrics.get("running") == 0 and metrics.get("waiting") == 0 + and (chosen["running"] != 0 or chosen["waiting"] != 0)): + return None # a newer idle observation must not inherit a busy plugin interval + return chosen + + def prune_history(self, now): + self.history_store.prune(self.models, now) + + def remember(self, model, now): + self.history_store.remember(model, self.plugin_snapshot(model, now), now) + + def history_snapshot(self, now=None): + now = self.clock() if now is None else now + with self.lock: + return self.history_store.snapshot(self.models, now, self.started) + + def snapshot(self, now=None, since=None) -> dict: + """The sparkring-dashboard/v1 document: the fields the page reads, in the shape it reads them.""" + now = self.clock() if now is None else now + with self.lock: + models = list(self.models.values()) + groups, rings = [], [] + color = 0 + externals = sorted(self.externals.values(), key=lambda e: e.row["id"]) + placed: set = set() + for source in self.sources: + fabric = source.fabric + members = [] + for model in sorted(models, key=lambda m: (min(m.row["positions"]), m.id)): + if model.source is source: + member = self.member(model, now, color) + member["counter_samples"] = self.history_store.delta(model.id, since) + members.append(member) + color += 1 + # An endpoint listed with a position joins the first ring whose fabric has that position. A + # container the host agents saw on that Spark without a known engine is that endpoint's own + # server, so its "GPU in use" row gives way to the endpoint's card, which then also names the + # stopped install records that row carried for the Spark. + here: dict = {} + for external in externals: + position = external.row.get("position") + if fabric and position is not None and external.id not in placed and position < fabric["size"]: + here[position] = self.external_ring_member(external, source, now, color) + placed.add(external.id) + color += 1 + kept = [] + for member in members: + if member["gpu_job"] and set(member["arc"]["positions"]) <= set(here): + for position in member["arc"]["positions"]: + known = {r["id"] for r in here[position]["stopped_records"]} + here[position]["stopped_records"] += [r for r in member["stopped_records"] + if r["id"] not in known] + else: + kept.append(member) + members = kept + list(here.values()) + members.sort(key=lambda m: m["arc"]["first"]) + groups.append({"id": source.ring_id(), "name": self.ring_name(source), "kind": "ring", + "members": members}) + if fabric: + rings.append(self.ring(source, members, now)) + events = list(self.events)[::-1][:60] + quiet, viewed = self.quiet, self.viewed(now) + cpu = list(self.cycle_cpu) + cursor = self.history_seq + externals = [self.external_member(e, now) for e in externals if e.id not in placed] + external_problem = self.external_problem + problems = [s.problem for s in self.sources if s.problem] + topology = {"source": "fabric" if rings else "none", "detail": "; ".join(problems) or None, + "rings": len(rings)} + counters = self.client.counters() + return {"schema": SCHEMA, "title": rings[0]["name"] if len(rings) == 1 else "SparkRing", + "generated_at": now, "service_started": self.started, + "history_cursor": cursor, + "poll_seconds": METRICS_VIEWED_SECONDS, "groups": groups, "rings": rings, + "ring": rings[0] if len(rings) == 1 else None, "topology": topology, "events": events, + "node": self.node_summary(), + "external": externals, "external_problem": external_problem, + "collector": {"quiet": quiet, "viewed": viewed, "cycles": self.cycles, + "metrics_seconds": METRICS_VIEWED_SECONDS if viewed else None, + "models_seconds": MODELS_SECONDS, + "cpu_ms_per_cycle": round(sum(cpu) / len(cpu) * 1000, 2) if cpu else None, + "requests": counters["requests"], "received_bytes": counters["received_bytes"], + "uptime_seconds": now - self.started}} + + def ring_name(self, source) -> str: + fabric = source.fabric + if not fabric: + return "fabric" + return source.display_name or fabric.get("cluster") or "sparkring" + + def member(self, model: Model, now: float, color: int) -> dict: + row, fabric = model.row, model.source.fabric or {"positions": []} + hostnames = {p["position"]: p for p in fabric["positions"]} + positions = row["positions"] + runtime = model.runtime or {} + metrics = model.metrics or {} + serving = model.state == "serving" + nodes = runtime.get("nodes") or [] + head_position = row.get("head_position", positions[0]) + head = hostnames.get(head_position, {}) + port = row["api_port"] or row.get("head_port") + endpoint = row.get("display_url") or f"http://{row['api_host']}:{port}/v1" + if not row["api_host"] or not port: + endpoint = None + spark_starting = self.startup_status(model) if not row["stopped"] else None + starting = spark_starting if not serving else None + if starting: + since = starting.get("started_at") + since = since if number(since) and since > 0 else None + elif serving: + # Runtime startup and process start are recorded events. An older + # runtime snapshot must not carry a prior run's age across a restart. + starts = [t for t in (runtime.get("started_at"), metrics.get("started")) + if number(t) and t > 0] + since = max(starts) if starts else row.get("serving_at") + elif model.state == "stopped": + since = row.get("stopped_at") if row["stopped"] else None + elif model.state in startup.PHASES or model.state == "not_ready": + since = None + else: + since = model.state_since + capacity = dict(model.capacity) if model.capacity else None + if capacity and runtime.get("settings"): + capacity["max_num_seqs"] = runtime["settings"].get("max_num_seqs") + launch = row.get("launch") or {} + 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, {}) + up = True if serving else (False if model.state == "offline" and position == positions[0] else None) + sparks.append({"name": spark.get("hostname", str(position)), "address": spark.get("address"), + "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 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, + "ownership_label": "Not installed by SparkRing: no automatic recovery, no install record" if row.get("unmanaged") else None, + "group_note": row.get("group_note"), "containers": row["containers"] if row.get("unmanaged") else [], + "stopped_records": row.get("stopped_records", []), + "startup": starting, + "spark_startup": spark_starting, + "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 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, + "counters": {"source": "metrics", "at": model.metrics_at, "run_id": metrics.get("started"), + "values": {key: value for key, value in metrics.items() + if isinstance(value, (int, float))}} if model.metrics else None, + "plugin_counters": self.plugin_snapshot(model, now), + "totals": {"finished": metrics.get("finished"), "preemptions": metrics.get("preemptions"), + "output_tokens": metrics.get("gen"), "prompt_tokens": metrics.get("prompt")} + if model.metrics else None, + "thinking": thinking.deployment_text(thought) if thought else None, + "thinking_default": thought, "thinking_provenance": thinking.provenance_text(thought), + "settings": runtime.get("settings"), "nodes": nodes, "capacity": capacity if serving else None, + "workers": ({"received": len(positions), "expected": row.get("expected_sparks") or len(positions)} + if flare else runtime.get("workers")), + "image": runtime.get("image"), "transport": runtime.get("transport"), + "sparks": sparks, + "history": [], + "arc": {"positions": positions, "first": positions[0], "last": positions[-1], "size": len(positions), + "run": run_name(positions), "source": "agent" if row.get("unmanaged") else "deployment", + "source_label": "agent launch facts" if row.get("unmanaged") else "deployment record", + "inferred": False, "detail": None, "color": color}, + "ring": model.source.ring_id(), + "head": {"position": head_position, "name": head.get("hostname"), "address": row["api_host"], "port": port, + "container": container}, + "logs": log_commands(head.get("hostname"), container), + "runtime_read": model.runtime is not None, + "recovery": {k: v for k, v in self.recovery[row["id"]].items() if k != "telemetry"} + if row["id"] in self.recovery else None, + } + + def ring(self, source: Source, members: list, now: float) -> dict: + fabric = source.fabric + owners: dict = {} + for member in members: + for position in member["arc"]["positions"]: + owners.setdefault(position, []).append(member["id"]) + local = socket.gethostname() + # A position's first member is the one that serves it; a stopped record sharing the position follows. + states = {m["id"]: m["state"] for m in members} + positions = [] + for row in fabric["positions"]: + reports = [d for d in [self.node_status, *self.node_reports] if isinstance(d, dict) + and row.get("node_id") and d.get("node_id") == row["node_id"] + and number(d.get("observed_at"))] + cached = max(reports, key=lambda d: d["observed_at"], default={}) + busy = sorted(owners.get(row["position"]) or [], key=lambda i: states.get(i) != "serving") + serving = any(m["state"] == "serving" and m["id"] in busy for m in members) + up = True if serving or row["hostname"] == local else None + positions.append({"position": row["position"], "name": row["hostname"], + "short": row["hostname"].removeprefix("spark-"), "address": row["address"], + "up": up, "since": None, "member": busy[0] if busy else None, "members": busy, + "run": None, "ports": row.get("ports", {}), + "observed_at": cached.get("observed_at"), + **spark_cached_details(cached)}) + first = fabric["positions"][0]["hostname"] + return {"id": source.ring_id(), "name": self.ring_name(source), "node_a": first, + "short": first.removeprefix("spark-"), "size": fabric["size"], "closed": fabric["closed"], + "source": "fabric", + "fabric": {"id": fabric["id"], "cluster": fabric["cluster"], "shape": fabric["shape"], + "verified": fabric["verified"], "read_from": [str(source.fabric_path)]}, + "positions": positions, "runs": [], + "discovery": {"ports": sorted({m["head"]["port"] for m in members if m["head"]["port"]}), + "every_seconds": METRICS_VIEWED_SECONDS if self.last_view and self.viewed(now) + else None, "at": now}} + + def node_summary(self) -> dict | None: + status = self.node_status + if not isinstance(status, dict): + return None + return {key: status.get(key) for key in ("hostname", "state", "next_action", "observed_at", "warnings", "error")} diff --git a/runtime/host/dashboard_parsers.py b/runtime/host/dashboard_parsers.py new file mode 100644 index 00000000..dbe76403 --- /dev/null +++ b/runtime/host/dashboard_parsers.py @@ -0,0 +1,353 @@ +"""Pure metric, Flare, and runtime-status parsers for ``sparkring dashboard``. + +Zero network I/O, zero filesystem I/O, and zero mutable state: every function +translates Prometheus exposition text, Flare JSON/text snapshots, or +``sparkring-runtime-status/v1`` documents into plain dictionaries and labels. +""" +from __future__ import annotations + +import json +import re + +from runtime.common.transport_names import collective_name +from runtime.host.dashboard_rates import number + +COUNTERS = { + "vllm:generation_tokens_total": "gen", + "vllm:prompt_tokens_total": "prompt", + "vllm:spec_decode_num_accepted_tokens_total": "accepted", + "vllm:spec_decode_num_drafts_total": "drafts", + "vllm:spec_decode_num_draft_tokens_total": "draft_tokens", + "vllm:num_preemptions_total": "preemptions", + "vllm:time_to_first_token_seconds_sum": "ttft_sum", + "vllm:time_to_first_token_seconds_count": "ttft_count", + "vllm:prefix_cache_queries_total": "pc_queries", + "vllm:prefix_cache_hits_total": "pc_hits", + "sglang:generation_tokens_total": "gen", + "sglang:prompt_tokens_total": "prompt", + "sglang:time_to_first_token_seconds_sum": "ttft_sum", + "sglang:time_to_first_token_seconds_count": "ttft_count", +} +SETTING_KEYS = ( + "tensor_parallel_size", "decode_context_parallel_size", "max_model_len", "max_num_seqs", "max_num_batched_tokens", + "cache_dtype", "quantization", "speculative_method", "num_speculative_tokens", + "reasoning_parser", "tool_call_parser", "default_chat_template_kwargs", + "kv_cache_memory_bytes", "prefix_caching_enabled", +) +LABELS = { + "busy": "Busy: API unavailable", "serving": "Serving", "not_ready": "Not ready", "stopped": "No model running", + "offline": "Offline", "idle": "Idle", None: "Checking", + "installing": "Installing", "starting": "Starting", "loading": "Loading weights", + "compiling": "Compiling", "tuning": "Tuning B12X", "graphs": "Capturing CUDA graphs", "failed": "Failed", +} +MODEL_TAIL_WORDS = { + "csf", "nvfp4", "fp8", "fp4", "mxfp8", "mxfp4", "int4", "int8", "awq", "gptq", "bf16", + "fp16", "qad", "spark", "attention", "gguf", "nf3", "exl3", +} +LABEL_RE = re.compile(r'([A-Za-z_][A-Za-z0-9_]*)="((?:[^"\\]|\\.)*)"') +LABEL_ESCAPE_RE = re.compile(r"\\(.)") + +# Flare's /metrics series the external cards show (ghcr.io/local-inference-lab/flare). Gauges are read as +# they are; counters are read as they are and the generation counter also gives a rate between two reads. +FLARE_GAUGES = { + "flare_active_requests": "active_requests", + "flare_pending_requests": "pending_requests", + "flare_http_request_capacity": "request_capacity", + "flare_uptime_seconds": "uptime_seconds", + "flare_generated_tokens_last_minute": "tokens_last_minute", + "flare_total_kv_tokens": "kv_tokens_total", + "flare_free_kv_tokens": "kv_tokens_free", + "flare_cached_kv_tokens": "kv_tokens_cached", +} +FLARE_COUNTERS = { + "flare_generated_tokens_total": "generated_tokens", + "flare_prefill_tokens_total": "prefill_tokens", + "flare_requests_completed_total": "requests_completed", + "flare_requests_failed_total": "requests_failed", + "flare_requests_cancelled_total": "requests_cancelled", + "flare_preemptions_total": "preemptions", + "flare_speculative_offered_drafts_total": "drafts_offered", + "flare_speculative_accepted_drafts_total": "drafts_accepted", + "flare_verification_draft_tokens_total": "draft_tokens", + "flare_engram_row_cache_hits_total": "row_cache_hits", + "flare_engram_row_cache_misses_total": "row_cache_misses", + "flare_cache_lookups_total": "prefix_lookups", + "flare_cache_hits_total": "prefix_hits", + "flare_http_requests_total": "http_requests", +} +FLARE_SERIES = {**FLARE_GAUGES, **FLARE_COUNTERS} +# Helios JSON snapshots use field names rather than Prometheus series names. +FLARE_JSON_KEYS = { + "flare_generated_tokens_total": "generated_tokens", + "flare_prefill_tokens_total": "prefill_tokens", + "flare_active_requests": "active", + "flare_pending_requests": "pending", + "flare_requests_completed_total": "completed", + "flare_requests_failed_total": "failed", + "flare_speculative_accepted_drafts_total": "accepted_drafts", + "flare_verification_draft_tokens_total": "verification_drafts", +} +FLARE_METRICS_PROBLEM = "No recognized numeric Flare metrics in /metrics response." + + +def parse_labels(text: str) -> dict: + """'a="x",b="y"' -> {"a": "x", "b": "y"}, with the exposition format's escapes undone.""" + return {key: LABEL_ESCAPE_RE.sub(lambda m: "\n" if m.group(1) == "n" else m.group(1), value) + for key, value in LABEL_RE.findall(text)} + + +def _iter_prometheus_lines(text: str): + """Yield ``(name, labels, rest)`` for each non-comment Prometheus exposition line.""" + for line in text.splitlines(): + if not line or line[0] == "#": + continue + brace = line.find("{") + if brace != -1: + end = line.rfind("}") + if end < brace: + continue + yield line[:brace], line[brace + 1:end], line[end + 1:] + else: + name, _, rest = line.partition(" ") + yield name, "", rest + + +def _parse_sample_value(rest: str) -> float | None: + parts = rest.split() + if not parts: + return None + try: + return float(parts[0]) + except ValueError: + return None + + +def parse_metrics(text: str) -> dict: + """Serving-engine series the page uses, summed across engines; KV use takes the maximum. + + `cache_info` holds the first engine's vllm:cache_config_info labels; `model_name` the + model_name label of the first vLLM series; `started` the API process's + process_start_time_seconds, which identifies one model run.""" + out: dict = {"finished": {}, "cache_info": None, "model_name": None, "started": None} + kv = None + for name, labels, rest in _iter_prometheus_lines(text): + if name == "vllm:cache_config_info": + if out["cache_info"] is None: + out["cache_info"] = parse_labels(labels) + continue + value = _parse_sample_value(rest) + if value is None: + continue + if out["model_name"] is None and name.startswith(("vllm:", "sglang:")) and 'model_name="' in labels: + out["model_name"] = parse_labels(labels).get("model_name") + if name in COUNTERS: + key = COUNTERS[name] + out[key] = out.get(key, 0.0) + value + elif name in ("vllm:num_requests_running", "sglang:num_running_reqs"): + out["running"] = out.get("running", 0.0) + value + elif name in ("vllm:num_requests_waiting", "sglang:num_queue_reqs"): + out["waiting"] = out.get("waiting", 0.0) + value + elif name in ("vllm:kv_cache_usage_perc", "vllm:gpu_cache_usage_perc", "sglang:token_usage"): + kv = value if kv is None else max(kv, value) + elif name == "vllm:request_success_total": + reason = parse_labels(labels).get("finished_reason") or "other" + out["finished"][reason] = out["finished"].get(reason, 0.0) + value + elif name == "process_start_time_seconds": + out["started"] = value + out["kv"] = kv + return out + + +def parse_flare_metrics(text: str) -> dict: + """Flare's Prometheus series or JSON snapshot mapped to the same short names. + + Labelled text series are summed over labels. Only recognized numeric JSON fields + are used; absent series stay absent, including fields that only the text API emits.""" + out: dict = {} + try: + document = json.loads(text) + except (ValueError, RecursionError): + pass + else: + if not isinstance(document, dict): + return out + for name, key in FLARE_SERIES.items(): + value = document.get(name, document.get(FLARE_JSON_KEYS.get(name))) + if number(value): + out[key] = value + page_tokens = document.get("page_tokens") + if number(page_tokens): + for field, series in (("total_pages", "flare_total_kv_tokens"), + ("free_pages", "flare_free_kv_tokens"), + ("cached_pages", "flare_cached_kv_tokens")): + pages = document.get(field) + if number(pages): + out.setdefault(FLARE_SERIES[series], pages * page_tokens) + return out + for name, _, rest in _iter_prometheus_lines(text): + key = FLARE_SERIES.get(name) + if key is None: + continue + value = _parse_sample_value(rest) + if value is None: + continue + out[key] = out.get(key, 0.0) + value + return out + + +def parse_flare_as_metrics(text: str) -> dict: + """Flare's series in the shape the model cards and history already read. + + ``parse_metrics`` serves vLLM and SGLang; this adapter keeps Flare's own + names as separate series where they are useful and maps the shared + counters. ``started`` stays None: Flare publishes uptime but no start + time, and deriving one would split history on every restart. + """ + flare = parse_flare_metrics(text) + out: dict = {"finished": {}, "cache_info": None, "model_name": None, "started": None} + out["metrics_problem"] = None if flare else FLARE_METRICS_PROBLEM + for source, key in (("generated_tokens", "gen"), ("prefill_tokens", "prompt"), + ("drafts_accepted", "accepted"), ("drafts_offered", "drafts"), + ("draft_tokens", "draft_tokens"), ("prefix_hits", "pc_hits"), + ("prefix_lookups", "pc_queries"), ("preemptions", "preemptions"), + ("active_requests", "running"), ("pending_requests", "waiting"), + ("request_capacity", "request_capacity"), ("uptime_seconds", "uptime_seconds"), + ("tokens_last_minute", "tokens_last_minute"), ("kv_tokens_total", "kv_tokens_total"), + ("kv_tokens_free", "kv_tokens_free"), ("kv_tokens_cached", "kv_tokens_cached")): + if source in flare: + out[key] = flare[source] + total, free = flare.get("kv_tokens_total"), flare.get("kv_tokens_free") + if total and free is not None: + out["kv"] = (total - free) / total + for source, key in (("requests_completed", "stop"), ("requests_failed", "error"), + ("requests_cancelled", "abort")): + if source in flare: + out["finished"][key] = flare[source] + return out + + +def capacity_from_cache_info(info: dict | None) -> dict | None: + """The KV cache budget from vllm:cache_config_info, or None when the gauge lacks it. + + The gauge carries kv_cache_size_tokens, kv_cache_max_concurrency and kv_cache_memory_bytes, + the figures of the engine's "GPU KV cache size" startup line; no log needs to be read.""" + if not info: + return None + + def coerce(key, cast): + try: + return cast(info[key]) + except (KeyError, TypeError, ValueError): + return None # absent, or vLLM's "None" for an unset value + + tokens = coerce("kv_cache_size_tokens", int) + if tokens is None: + return None + return {"kv_tokens": tokens, "concurrency": coerce("kv_cache_max_concurrency", float), + "kv_bytes": coerce("kv_cache_memory_bytes", int), + "gpu_memory_utilization": coerce("gpu_memory_utilization", float), + "block_size": coerce("block_size", int), "max_num_seqs": None, "max_model_len": None, + "mm": None, "source": "metrics"} + + +def known(field): + return field.get("value") if isinstance(field, dict) and field.get("state") == "known" else None + + +def read_transport(doc: dict) -> dict | None: + """The transport of the TP group's collectives and the b12x bundle the image carries. + + runtime-status 0.3.6 and later report `tp_collective_transport` per worker; for older + images the label comes from the TP group's resident backend facts. `label` is the + transport's display name (``runtime.common.transport_names``). + + `bundle` (and its older alias `profile`) names the b12x RoCEnante bundle in the image, + whichever transport runs; `bundle_in_use` is True when RoCEnante carries the + collectives, False when another transport does and None when that is not known. The + page and the terminal view show the transport, never the bundle name.""" + backend = rocenante = nccl_available = nccl_disabled = collective = sircl_version = None + for rank in (doc.get("workers") or {}).get("ranks") or []: + transport = rank.get("transport") or {} + tp_group = (transport.get("groups") or {}).get("TP") or {} + backend = backend or known(tp_group.get("b12x_backend")) + if rocenante is None: + rocenante = known((tp_group.get("rocenante") or {}).get("enabled")) + nccl = tp_group.get("nccl") or {} + if nccl_available is None: + nccl_available = known(nccl.get("available")) + if nccl_disabled is None: + nccl_disabled = known(nccl.get("disabled")) + for effective in (rank.get("effective") or {}, transport.get("effective") or {}): + collective = collective or known(effective.get("tp_collective_transport")) + sircl_version = sircl_version or known(effective.get("tp_sircl_version")) + provenance = doc.get("provenance") or {} + bundle = known((provenance.get("b12x_comm_bundle") or {}).get("name")) or known(provenance.get("transport_profile")) + running = collective + if collective is None: + if isinstance(backend, str) and "sircl" in backend.lower(): + running = "sircl" + elif rocenante is True: + running = "rocenante" + elif not backend and nccl_available and not nccl_disabled: + running = "nccl" + label = collective_name(running) if running is not None else (str(backend) if backend else None) + if label is None and bundle is None: + return None + nccl_on = None if nccl_available is None and nccl_disabled is None else bool(nccl_available) and not nccl_disabled + in_use = None if running is None else running == "rocenante" + return {"label": label, "collective": collective, "sircl_version": sircl_version if collective == "sircl" else None, + "nccl": nccl_on, "bundle": bundle, "profile": bundle, "bundle_in_use": in_use, "source": "runtime"} + + +def read_runtime_status(doc: dict) -> dict: + """The fields of a sparkring-runtime-status/v1 document the page shows.""" + effective = doc.get("effective") or {} + arguments = (doc.get("configured") or {}).get("arguments") or {} + + def value(key): + found = known(effective.get(key)) + return known(arguments.get(key)) if found is None else found + + workers = doc.get("workers") or {} + nodes, image = [], None + for rank in workers.get("ranks") or []: + identity = rank.get("identity") or {} + image = image or known(identity.get("image_id")) + resources = rank.get("resources") or {} + memory = resources.get("memory") or {} + root = next((fs for fs in resources.get("filesystems") or [] if "/" in (fs.get("paths") or [])), {}) + nodes.append({"rank": known(identity.get("rank")), "node": resources.get("node"), + "memory_total": memory.get("total_bytes"), "memory_available": memory.get("available_bytes"), + "disk_total": root.get("total_bytes"), + "disk_available": root.get("available_bytes", root.get("free_bytes"))}) + started = doc.get("startup_snapshot_at_unix_ns") + return {"settings": {key: value(key) for key in SETTING_KEYS}, "nodes": nodes, + "workers": {"expected": workers.get("expected_count"), "received": workers.get("received_count")}, + "image": image.split(":")[-1][:12] if isinstance(image, str) else None, + "started_at": started / 1e9 if isinstance(started, (int, float)) else None, + "tp": value("tensor_parallel_size"), "dp": value("data_parallel_size"), + "pp": value("pipeline_parallel_size"), "transport": read_transport(doc)} + + +def short_model(model) -> str | None: + """Model family without its packaging tail: 'GLM-5.3-Flash-NVFP4-Spark-TP2' -> 'GLM-5.3-Flash'.""" + if not model: + return None + kept = [] + for part in str(model).split("/")[-1].split("-"): + low = part.lower() + if kept and (low in MODEL_TAIL_WORDS or re.fullmatch(r"(tp|dcp)\d+", low) or re.fullmatch(r"[\d.]+bpw", low)): + break + kept.append(part) + return "-".join(kept) or str(model) + + +def layout_label(size) -> str | None: + if not isinstance(size, int) or size < 1: + return None + return f"TP{size} {'ring' if size >= 4 else 'pair'}" + + +def run_name(positions) -> str: + """'tp4-7-2' for the arc 7, 0, 1, 2; the run naming the lab tooling and SIRCL use.""" + return f"tp{len(positions)}-{positions[0]}-{positions[-1]}" diff --git a/runtime/host/dashboard_quiet.py b/runtime/host/dashboard_quiet.py new file mode 100644 index 00000000..26d1ddfd --- /dev/null +++ b/runtime/host/dashboard_quiet.py @@ -0,0 +1,156 @@ +"""Quiet-mode holds and low-priority process placement for ``sparkring dashboard``. + +Quiet mode pauses all network requests from the next one-second cycle on, either +through the operator's quiet file (``QUIET_PATH``) or through per-measurement +holder files (``quiet_hold`` / ``quiet_release``) with PID and TTL expiry. +``lower_priority`` moves the process to ``SCHED_IDLE``, nice 19, and the +efficiency cores reported by ``runtime.host.host_load``. +""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import re +import socket +import time + +QUIET_PATH = Path("/run/sparkring/dashboard.quiet") +# One file per measurement that holds quiet mode, beside QUIET_PATH (quiet_holders_directory). +QUIET_HOLDERS = "dashboard-quiet" +QUIET_SCHEMA = "sparkring-dashboard-quiet/v1" +QUIET_TTL_SECONDS = 12 * 3600 +QUIET_LABEL_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,39}") + + +def efficiency_cpus(root: Path | None = None, cpuinfo: Path | None = None) -> set | None: + """The CPUs outside the fastest class (on GB10 the Cortex-A725 cores), or None on a host whose + cores are all of one class: runtime.host.host_load.efficiency_cpus, which the host agent's and + the recovery timer's placement drop-ins use too.""" + from runtime.host import host_load + return host_load.efficiency_cpus(root, cpuinfo) + + +def lower_priority(cpu_list: str | None = None) -> list: + """Move this thread, and the threads it starts later, to idle CPU scheduling, nice 19 and the + efficiency cores (or `cpu_list`); returns what changed. + + Call it before any other thread starts: Linux applies each setting to the calling thread and + new threads inherit it. Each step is skipped where the platform lacks it. The systemd unit + (packaging/debian/sparkring-dashboard.service) sets the same limits; doing it here as well + covers a dashboard started by hand or on another host.""" + done = [] + if hasattr(os, "sched_setscheduler") and hasattr(os, "SCHED_IDLE"): + try: + os.sched_setscheduler(0, os.SCHED_IDLE, os.sched_param(0)) + done.append("idle scheduling") + except OSError: + pass + if hasattr(os, "nice"): + try: + os.nice(max(0, 19 - os.nice(0))) + done.append("nice 19") + except OSError: + pass + if hasattr(os, "sched_setaffinity"): + from runtime.host import host_load + chosen = set(host_load.parse_cpu_list(cpu_list)) if cpu_list else efficiency_cpus() + if chosen: + try: + os.sched_setaffinity(0, chosen) + done.append("CPUs " + host_load.format_cpu_list(chosen)) + except OSError: + pass + return done + + +def quiet_holders_directory(quiet_path: Path) -> Path: + return Path(quiet_path).parent / QUIET_HOLDERS + + +def _process_alive(pid) -> bool: + """Whether process `pid` of this host runs. Only POSIX can ask without side effects; elsewhere + a holder's process counts as running and its time to live ends it.""" + if os.name != "posix": + return True + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True # another user's process, such as a root harness seen by the dashboard's user + return True + + +def quiet_state(quiet_path: Path, now: float, *, alive=_process_alive) -> dict: + """{"quiet", "operator", "holders"}: whether quiet mode is held, by the operator's quiet file and + by which live measurement holders.""" + operator = Path(quiet_path).exists() + holders = [] + try: + entries = sorted(quiet_holders_directory(quiet_path).glob("*.json")) + except OSError: + entries = [] + for entry in entries: + try: + holder = json.loads(entry.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + if not isinstance(holder, dict) or holder.get("schema") != QUIET_SCHEMA: + continue + until, pid = holder.get("until"), holder.get("pid") + if not isinstance(until, (int, float)) or until <= now: + continue + if type(pid) is int and pid > 0 and holder.get("host") == socket.gethostname() and not alive(pid): + continue + holders.append({"id": entry.stem, "label": holder.get("label"), "pid": pid, "since": holder.get("since"), + "until": until}) + return {"quiet": operator or bool(holders), "operator": operator, "holders": holders} + + +def quiet_hold(quiet_path: Path, label: str, *, pid=None, ttl=QUIET_TTL_SECONDS, now=None) -> dict: + """Hold quiet mode for one measurement; returns its holder id and whether quiet mode was already held.""" + if not QUIET_LABEL_RE.fullmatch(label or ""): + raise ValueError(f"a holder label is 1 to 40 letters, digits, '.', '_' or '-', not {label!r}") + if not (type(ttl) is int and 1 <= ttl <= 7 * 24 * 3600): + raise ValueError("a holder's time to live is 1 s to 7 days") + now = time.time() if now is None else now + before = quiet_state(quiet_path, now) + directory = quiet_holders_directory(quiet_path) + directory.mkdir(parents=True, exist_ok=True) + holder_id = f"{label}-{pid or 0}-{os.urandom(4).hex()}" + path = directory / f"{holder_id}.json" + temporary = path.with_name(path.name + ".writing") + temporary.write_text(json.dumps({"schema": QUIET_SCHEMA, "label": label, "pid": pid, "host": socket.gethostname(), + "since": now, "until": now + ttl}) + "\n", encoding="utf-8") + temporary.replace(path) + return {"holder": holder_id, "was_quiet": before["quiet"], "until": now + ttl} + + +def quiet_release(quiet_path: Path, holder_id: str) -> dict: + """End one measurement's hold; quiet mode stays on while the operator or another holder holds it.""" + if not QUIET_LABEL_RE.fullmatch(holder_id.split("-", 1)[0]) or "/" in holder_id or "\\" in holder_id: + raise ValueError(f"not a quiet holder id: {holder_id!r}") + (quiet_holders_directory(quiet_path) / f"{holder_id}.json").unlink(missing_ok=True) + return {"released": holder_id, "still_quiet": quiet_state(quiet_path, time.time())["quiet"]} + + +def quiet(args) -> int: + path = Path(args.quiet_file) + if args.state == "on": + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("The SparkRing dashboard sends no request while this file exists.\n", encoding="utf-8") + print(f"Dashboard paused: {path} exists; it sends no request until sparkring dashboard quiet off.") + elif args.state == "off": + path.unlink(missing_ok=True) + holders = quiet_state(path, time.time())["holders"] + print("Dashboard collecting again." if not holders else + "The operator's pause is off; the dashboard stays quiet while these measurements hold it: " + + ", ".join(f"{h['label']} (pid {h['pid']})" for h in holders)) + elif args.state == "status": + print(json.dumps(quiet_state(path, time.time()), indent=2)) + elif args.state == "hold": + print(json.dumps(quiet_hold(path, args.label, pid=args.pid, ttl=args.ttl))) + else: + print(json.dumps(quiet_release(path, args.holder))) + return 0 diff --git a/runtime/host/dashboard_server.py b/runtime/host/dashboard_server.py new file mode 100644 index 00000000..9134aa48 --- /dev/null +++ b/runtime/host/dashboard_server.py @@ -0,0 +1,302 @@ +"""HTTP server, page assembly with SHA-256 CSP, auth, and bind guards for ``sparkring dashboard``. + +Preserves all read-only and security invariants: DNS-rebinding ``Host`` header +checks (421), loopback-by-default bind with fail-closed refusal of unauthenticated +non-loopback binds, constant-time Basic authentication (``hmac.compare_digest``), +SHA-256 Content-Security-Policy hashes, strict security headers, 8 KiB bounded +manage-mode POST dispatch, and ``SIGHUP`` reload handling. +""" +from __future__ import annotations + +import base64 +import gzip +import hashlib +import hmac +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import ipaddress +import json +import os +from pathlib import Path +import re +import signal +import socket +import sys +import threading +import urllib.parse + +from runtime.host.dashboard_collector import Collector +from runtime.host.dashboard_sources import FABRIC_PATH, SITE_PATH, Source, _ip + +PAGE = Path(__file__).with_name("dashboard.html") +DEFAULT_PORT = 8090 + + +def page_bytes(path: Path = PAGE) -> tuple[bytes, str]: + """The page and its Content-Security-Policy: its inline script and style admitted by hash only.""" + text = Path(path).read_text(encoding="utf-8") + text = text.replace("// VIEWER_RATES", Path(__file__).with_name("dashboard_rates.js").read_text(encoding="utf-8")) + policies = [] + for tag, directive in (("script", "script-src"), ("style", "style-src")): + match = re.search(rf"<{tag}>(.*?)", text, flags=re.S) + digest = base64.b64encode(hashlib.sha256(match.group(1).encode()).digest()).decode() + policies.append(f"{directive} 'sha256-{digest}'") + csp = "; ".join(["default-src 'none'", *policies, "style-src-attr 'unsafe-inline'", "connect-src 'self'", + "img-src 'self' data:", "base-uri 'none'", "frame-ancestors 'none'", "form-action 'none'"]) + return text.encode("utf-8"), csp + + +def host_allowed(header: str | None, names) -> bool: + """Whether a request's Host header names this server: an IP literal, `localhost` or one of `names`. + + A browser on the LAN that a hostile web page points at the dashboard through DNS + rebinding sends that page's host name, which is refused. `localhost` is no page's name: + browsers resolve it to loopback themselves.""" + if not header: + return False + host = header.strip() + if host.startswith("["): + host = host[1:host.find("]")] if "]" in host else host + else: + host = host.rsplit(":", 1)[0] if host.count(":") == 1 else host + return _ip(host) or host.lower() == "localhost" or host.lower() in names + + +def make_handler(collector: Collector, page: bytes, csp: str, names=frozenset(), password: str | None = None, + manager=None): + headers = {"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer", + "X-Frame-Options": "DENY"} + expected = (None if password is None + else ("Basic " + base64.b64encode(f"sparkring:{password}".encode("utf-8")).decode("ascii")).encode("utf-8")) + + class Handler(BaseHTTPRequestHandler): + server_version = "sparkring-dashboard" + + def do_GET(self): + if not host_allowed(self.headers.get("Host"), names): + return self._send(421, b"This dashboard answers to its IP address or a name given with --name.\n", + "text/plain; charset=utf-8") + auth_header = self.headers.get("Authorization") + auth_ok = (auth_header is not None + and hmac.compare_digest(auth_header.encode("utf-8", "replace"), expected)) if expected is not None else True + if (expected is not None and not auth_ok + and not (manager and manager.authenticated(self.headers))): + self.send_response(401) + self.send_header("WWW-Authenticate", 'Basic realm="SparkRing dashboard", charset="UTF-8"') + self.send_header("Content-Length", "0") + self.end_headers() + return None + path, _, query = self.path.partition("?") + params = {k: v[-1] for k, v in urllib.parse.parse_qs(query).items()} + if path == "/": + return self._send(200, page, "text/html; charset=utf-8", {"Content-Security-Policy": csp}) + if path == "/api/status": + if params.get("viewer") != "passive": # sparkring dashboard tui --passive + collector.mark_viewed() + try: + since = int(params["since"]) if "since" in params else None + except ValueError: + return self._json(400, {"error": "Invalid history cursor"}) + snapshot = collector.snapshot(since=since) + return self._json(200, {**snapshot, "manage": True} if manager else snapshot) + if path == "/api/history": + body = json.dumps(collector.history_snapshot(), separators=(",", ":")).encode() + extra = {"Vary": "Accept-Encoding"} + if "gzip" in self.headers.get("Accept-Encoding", ""): + body = gzip.compress(body, compresslevel=1, mtime=0) + extra["Content-Encoding"] = "gzip" + return self._send(200, body, "application/json", extra) + if path == "/api/manage" and manager: + try: + return self._json(200, manager.session(self.headers)) + except PermissionError as error: + return self._json(401, {"error": str(error)}) + if path == "/api/refresh": + accepted = collector.request_runtime(params.get("model", "")) + return self._json(202 if accepted else 429, {"accepted": accepted}) + if path == "/healthz": + return self._send(200, b"ok\n", "text/plain") + return self._send(404, b"not found\n", "text/plain") + + def _refuse(self): + self._send(405, b"read-only\n", "text/plain", {"Allow": "GET"}) + + do_PUT = do_DELETE = do_PATCH = _refuse + + def do_POST(self): + if manager is None: + return self._refuse() + if not host_allowed(self.headers.get("Host"), names): + return self._json(421, {"error": "Host refused"}) + if not manager.authenticated(self.headers): + return self._json(401, {"error": "Authentication required"}) + if self.headers.get("Content-Type") != "application/json" or self.headers.get("Transfer-Encoding"): + return self._json(415, {"error": "Use a bounded JSON request"}) + try: + length = int(self.headers.get("Content-Length", "0")) + if not 0 < length <= 8192: + return self._json(413, {"error": "Action request is too large or empty"}) + self.connection.settimeout(15) + raw = self.rfile.read(length) + if len(raw) != length: + raise ValueError("Incomplete request") + result = manager.dispatch(self.path, self.headers, json.loads(raw)) + return self._json(200, result) + except PermissionError as error: + return self._json(403, {"error": str(error)}) + except (ValueError, KeyError, TypeError) as error: + return self._json(400, {"error": str(error)}) + except OSError as error: + return self._json(503, {"error": "Helper unavailable: " + str(error)}) + + def _json(self, code, value): + self._send(code, json.dumps(value, separators=(",", ":")).encode(), "application/json") + + def _send(self, code, body, kind, extra=None): + self.send_response(code) + for name, value in {**headers, **(extra or {}), "Content-Type": kind, + "Content-Length": str(len(body))}.items(): + self.send_header(name, value) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + return Handler + + +def is_loopback_bind(bind: str) -> bool: + """Whether ``bind`` names a loopback interface (``127.0.0.0/8``, ``::1``, or ``localhost``).""" + text = bind.strip() + if text.lower() == "localhost": + return True + try: + return ipaddress.ip_address(text).is_loopback + except ValueError: + return False + + +def default_bind(source: Source, *, authenticated: bool = False, + allow_unauthenticated_lan: bool = False) -> str: + """Default listen address: ``127.0.0.1`` unless authentication (``--password-file``) or + ``--allow-unauthenticated-lan`` is enabled, in which case Node A uses its LAN address + from the fabric document (else its management address).""" + if not authenticated and not allow_unauthenticated_lan: + return "127.0.0.1" + rows = (source.fabric or {}).get("positions") or [] + if rows and socket.gethostname() == rows[0]["hostname"]: + return rows[0].get("lan_address") or rows[0].get("address") or "127.0.0.1" + return "127.0.0.1" + + +def service_url(fabric_path: Path = FABRIC_PATH, *, authenticated: bool = False, + allow_unauthenticated_lan: bool = False, site_path: Path = SITE_PATH) -> str: + """The address of the dashboard service on this Spark, by the service's default bind rule + (``default_bind``): loopback by default, or Node A's LAN address when authenticated or + explicitly opted in.""" + source = Source(fabric_path, site_path) + source.refresh() + bind = default_bind(source, authenticated=authenticated, + allow_unauthenticated_lan=allow_unauthenticated_lan) + literal = f"[{bind}]" if ":" in bind else bind + return f"http://{literal}:{DEFAULT_PORT}" + + +def listen_addresses(bind: str) -> list: + """The addresses to listen on: `bind`, then 127.0.0.1 unless `bind` is a loopback address or a + wildcard (0.0.0.0, ::), which already admits loopback connections.""" + try: + literal = ipaddress.ip_address(bind) + except ValueError: + return [bind, "127.0.0.1"] # a host name: its address is not known here + if literal.is_loopback or literal.is_unspecified: + return [bind] + return [bind, "127.0.0.1"] + + +def open_servers(addresses, port: int, handler, *, log=None) -> list: + """One HTTP server per address. The first address is the configured one and its failure raises; + a later one that cannot be bound (port taken, no such address) costs one line on stderr.""" + servers = [] + for index, address in enumerate(addresses): + family = socket.AF_INET6 if ":" in address else socket.AF_INET + server_class = type("DashboardServer", (ThreadingHTTPServer,), {"address_family": family}) + try: + server = server_class((address, port), handler) + except OSError as error: + if index == 0: + raise + (log or (lambda line: print(line, file=sys.stderr, flush=True)))( + f"sparkring dashboard: not listening on {address}:{port} ({error}); " + f"{addresses[0]}:{port} serves the page") + continue + server.daemon_threads = True + servers.append(server) + return servers + + +def url_of(address: str, port: int) -> str: + return f"http://[{address}]:{port}/" if ":" in address else f"http://{address}:{port}/" + + +def reload_on_hangup(collector: Collector, signals=signal) -> bool: + """Make SIGHUP (systemctl reload) re-read the host files at the collector's next cycle; False on + a platform without SIGHUP. Python's default for SIGHUP ends the process, and systemd counts an + end by SIGHUP as clean, so a reload before this ran would leave the service stopped: serve + installs it before anything else.""" + if not hasattr(signals, "SIGHUP"): + return False + signals.signal(signals.SIGHUP, lambda number, frame: collector.request_reload()) + return True + + +def build_manager(args): + """Validate --manage prerequisites and construct the privileged-helper Manager, or None.""" + if not getattr(args, "manage", False): + return None + if not hasattr(os, "geteuid") or os.geteuid() == 0: + raise ValueError("Dashboard manage mode must run as an unprivileged user") + if not args.manage_token_file or args.fabric or args.site: + raise ValueError("Manage mode requires --manage-token-file and this controller's default fabric/site") + from runtime.host.dashboard_actions import Manager + return Manager(Path(args.manage_token_file).read_text(encoding="utf-8").strip()) + + +def resolve_password(password_file) -> str | None: + if not password_file: + return None + password = Path(password_file).read_text(encoding="utf-8").strip() + if not password: + raise ValueError(f"{password_file} is empty") + return password + + +def resolve_bind(args, primary_source: Source, password: str | None) -> str: + """Resolve and validate the listen address, failing closed for unauthenticated non-loopback binds.""" + allow_unauthenticated_lan = bool(getattr(args, "allow_unauthenticated_lan", False)) + requested_bind = getattr(args, "bind", None) or getattr(args, "host", None) + if requested_bind: + if not is_loopback_bind(requested_bind) and password is None and not allow_unauthenticated_lan: + raise ValueError( + f"Refusing to bind unauthenticated dashboard to non-loopback address {requested_bind!r}; " + "configure --password-file PATH or opt in explicitly with --allow-unauthenticated-lan" + ) + return requested_bind + return default_bind(primary_source, authenticated=password is not None, + allow_unauthenticated_lan=allow_unauthenticated_lan) + + +def run_servers(collector: Collector, servers: list, placement: list, source_count: int) -> int: + """Start the collector and secondary listener threads and block serving on the primary listener.""" + stop = threading.Event() + threading.Thread(target=collector.run, args=(stop,), daemon=True, name="collector").start() + for server in servers[1:]: + threading.Thread(target=server.serve_forever, daemon=True, name="listener").start() + where = " and ".join(url_of(server.server_address[0], server.server_address[1]) for server in servers) + print(f"SparkRing dashboard on {where} ({', '.join(placement) or 'default priority'}); " + f"{len(collector.models)} model API(s) from {source_count} fabric(s)", flush=True) + try: + servers[0].serve_forever() + finally: + stop.set() + return 0 diff --git a/runtime/host/dashboard_sources.py b/runtime/host/dashboard_sources.py new file mode 100644 index 00000000..958f00e8 --- /dev/null +++ b/runtime/host/dashboard_sources.py @@ -0,0 +1,501 @@ +"""Read-only host file parsers and discovery sources for ``sparkring dashboard``. + +Reads the fabric document, exported site file, external endpoint list, host-agent +observations, and recovery findings with bounded file sizes (``MAX_FILE_BYTES``) +and strict identifier/IP validation. Starts no subprocesses and opens no sockets. +""" +from __future__ import annotations + +from functools import lru_cache +import hashlib +import ipaddress +import json +from pathlib import Path +import re +import shlex + +from runtime.common import serving, thinking +from runtime.host.dashboard_parsers import run_name +from runtime.host.dashboard_rates import number + +SITE_SCHEMA = "sparkring-dashboard-site/v1" +SITE_PATH = Path("/var/lib/sparkring/dashboard/site.json") +# Endpoints served outside the installer (sparkring dashboard external): read-only cards. +EXTERNAL_PATH = Path("/var/lib/sparkring/dashboard/external.json") +EXTERNAL_SCHEMA = "sparkring-dashboard-external/v1" +EXTERNAL_KINDS = ("flare", "openai") +EXTERNAL_ID_RE = re.compile(r"[a-z0-9][a-z0-9-]{0,39}") +FABRIC_PATH = Path("/etc/sparkring/fabric/topology.json") +MAX_FILE_BYTES = 1024 * 1024 +LOG_LINES = 40 +CONTAINER_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}") +HOSTNAME_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9-]{1,63})*") + + +def read_json(path: Path): + """A small JSON host file, or raises OSError/ValueError.""" + with open(path, "rb") as stream: + data = stream.read(MAX_FILE_BYTES + 1) + if len(data) > MAX_FILE_BYTES: + raise ValueError(f"{path} is larger than {MAX_FILE_BYTES} bytes") + return json.loads(data.decode("utf-8")) + + +def _ip(value) -> bool: + try: + ipaddress.ip_address(str(value)) + except ValueError: + return False + return True + + +def read_external(path) -> list: + """The endpoints the file at ``path`` lists, validated; [] when the file is absent. + + The document is ``sparkring-dashboard-external/v1``: ``endpoints``, each with an ``id`` + (lowercase letters, digits and hyphens, at most 40 characters, distinct), a ``label`` (at most 80 + characters), a ``kind`` (``flare`` or ``openai``), a ``host`` (an IP address), a ``port`` and an + optional ``position``: the ring position of the Spark that serves it, which places the endpoint on + the ring figure among the ring's own models. Raises ValueError for a document that is not of that + form.""" + try: + document = read_json(Path(path)) + except FileNotFoundError: + return [] + return external_rows(document, path) + + +def external_rows(document, path="external list") -> list: + """The validated endpoints of an external-list ``document`` (read_external's rules); ``path`` names it in errors.""" + if not isinstance(document, dict) or document.get("schema") != EXTERNAL_SCHEMA: + raise ValueError(f"{path}: expected {EXTERNAL_SCHEMA}") + rows = document.get("endpoints") + if not isinstance(rows, list): + raise ValueError(f"{path}: endpoints must be a list") + out, seen = [], set() + for row in rows: + if not isinstance(row, dict): + raise ValueError(f"{path}: each endpoint is an object") + identifier = row.get("id") + if not isinstance(identifier, str) or not EXTERNAL_ID_RE.fullmatch(identifier) or identifier in seen: + raise ValueError(f"{path}: endpoint id {identifier!r} is not a distinct short lowercase name") + label = row.get("label") + if not isinstance(label, str) or not label.strip() or len(label) > 80: + raise ValueError(f"{path}: endpoint {identifier} needs a label of at most 80 characters") + kind = row.get("kind", "openai") + if kind not in EXTERNAL_KINDS: + raise ValueError(f"{path}: endpoint {identifier} kind must be one of {', '.join(EXTERNAL_KINDS)}") + host, port = row.get("host"), row.get("port") + if not isinstance(host, str) or not _ip(host): + raise ValueError(f"{path}: endpoint {identifier} host must be an IP address") + if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535: + raise ValueError(f"{path}: endpoint {identifier} port must be 1 to 65535") + entry = {"id": identifier, "label": label.strip(), "kind": kind, "host": host, "port": port} + position = row.get("position") + if position is not None: + if not isinstance(position, int) or isinstance(position, bool) or position < 0: + raise ValueError(f"{path}: endpoint {identifier} position must be a ring position, 0 or more") + entry["position"] = position + seen.add(identifier) + out.append(entry) + return out + + +def fabric_from_document(document: dict) -> dict: + """The parts of a sparkring-fabric/v1 document the dashboard uses; ValueError when unusable. + + The full validator (runtime.common.fabric_document.validate) also checks every port and + cable. The dashboard retains cable address ownership to resolve repeated rendezvous + addresses without assuming that neighbouring containers belong to one model.""" + if not isinstance(document, dict) or document.get("schema") != "sparkring-fabric/v1": + raise ValueError("not a sparkring-fabric/v1 document") + size, positions, shape = document.get("size"), document.get("positions"), document.get("shape") + if shape not in ("cycle", "path", "pair") or not isinstance(size, int) or size < 2 \ + or not isinstance(positions, list) or len(positions) != size: + raise ValueError("the fabric document's shape, size and positions do not agree") + rows = [] + for index, row in enumerate(positions): + if not isinstance(row, dict) or row.get("position") != index: + raise ValueError(f"position {index} is missing or out of order") + hostname = row.get("hostname") + if not isinstance(hostname, str) or not HOSTNAME_RE.fullmatch(hostname): + raise ValueError(f"position {index} has no usable hostname") + address = (row.get("management") or {}).get("address") + addresses = [address, row.get("lan_address")] + for port in (row.get("ports") or {}).values(): + for function in (port.get("functions") or {}).values(): + addresses.append(str(function.get("address") or "").split("/")[0]) + neighbors = [] + for port in (row.get("ports") or {}).values(): + peer = port.get("peer") or {} + remote_position = peer.get("position") + if type(remote_position) is not int or not 0 <= remote_position < size: + continue + remote_port = (positions[remote_position].get("ports") or {}).get(str(peer.get("port")), {}) + for function in (remote_port.get("functions") or {}).values(): + remote_address = str(function.get("address") or "").split("/")[0] + if _ip(remote_address): + neighbors.append({"position": remote_position, "address": remote_address}) + rows.append({"position": index, "hostname": hostname, "node_id": row.get("node_id"), + "neighbors": neighbors, "ports": row.get("ports") or {}, + "addresses": [a for a in addresses if _ip(a)], + "address": address if _ip(address) else None, + "lan_address": row.get("lan_address") if _ip(row.get("lan_address")) else None}) + verified = document.get("verified") + return {"id": document.get("id") if isinstance(document.get("id"), str) else None, + "cluster": document.get("cluster") if isinstance(document.get("cluster"), str) else None, + "shape": shape, "closed": shape == "cycle", "size": size, "positions": rows, + "verified": verified.get("result") if isinstance(verified, dict) else None} + + +def spark_cached_details(document): + """Allow-listed optional node facts; never collect hardware data for the viewer.""" + gpu = document.get("gpu") or {} + gpu = {k: gpu[k] for k in ("memory_used_bytes", "memory_total_bytes", "temperature_c") + if isinstance(gpu, dict) and number(gpu.get(k)) and gpu[k] >= 0} + control = document.get("control") + links = document.get("links", control.get("peers", []) if isinstance(control, dict) else []) + links = links if isinstance(links, list) else [] + links = [{k: row[k][:128] if isinstance(row[k], str) else row[k] for k in ("netdev", "carrier", "operstate") + if isinstance(row.get(k), (str, bool))} for row in links[:16] if isinstance(row, dict)] + containers = document.get("containers") or [] + containers = containers if isinstance(containers, list) else [] + containers = [{k: row[k][:128] for k in ("name", "state", "health") if isinstance(row.get(k), str)} + for row in containers[:32] if isinstance(row, dict)] + return {"gpu": gpu, "links": links, "containers": containers} + + +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. 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 = [] + for row in site.get("deployments") or []: + if not isinstance(row, dict): + 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 + 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"])] + 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 + + +@lru_cache(maxsize=128) +def thinking_record(profile, checkpoint): + """Resolve shipped thinking records once per profile/checkpoint, without host access.""" + try: + return thinking.of(profile, checkpoint) + except (OSError, ValueError, KeyError): + return None + + +def chat_defaults(row, settings): + """Observed runtime kwargs take precedence over launch facts and saved settings, even when empty.""" + for source in (settings or {}, row.get("launch") or {}, row.get("settings") or {}): + value = source.get("default_chat_template_kwargs") + if isinstance(value, str): + try: + value = json.loads(value) + except ValueError: + continue + if isinstance(value, dict): + return value + return None + + +def thinking_state(row, settings): + """Effective thinking and provenance from observations, then saved/profile defaults.""" + unmanaged = row.get("unmanaged") + profile, checkpoint = row.get("profile"), row.get("checkpoint") + record = None if unmanaged or not isinstance(profile, str) or ( + checkpoint is not None and not isinstance(checkpoint, str)) else thinking_record(profile, checkpoint) + if not unmanaged and record is None: + return None + kwargs = chat_defaults(row, settings) + chosen = {} + enabled = False + if kwargs is None: + chosen = serving.effective(profile, row.get("serving"), checkpoint) if not unmanaged else {} + else: + off = record and record["off"] + enabled = bool(off) and all(kwargs.get(k) is True for k in off) + if (off and all(kwargs.get(k) == v for k, v in off.items()) + or (unmanaged or record["name"] == "deepseek-v41-encoder") and ( + kwargs.get("enable_thinking") is False or kwargs.get("thinking") is False + or kwargs.get("reasoning_effort") == "none")): + chosen = {"thinking": "off"} + elif kwargs.get("reasoning_effort") is not None and ( + unmanaged or thinking.accepts(record, kwargs["reasoning_effort"])): + chosen = {"reasoning_effort": kwargs["reasoning_effort"]} + elif unmanaged and (kwargs.get("enable_thinking") is True or kwargs.get("thinking") is True): + chosen = {"thinking": "on"} + if unmanaged: + return {"thinking": chosen.get("thinking", "on" if "reasoning_effort" in chosen else "unknown"), + "level": chosen.get("reasoning_effort"), "chosen": bool(chosen), "levels": [], + "model": {"thinking": "unknown", "level": None}} + state = thinking.deployment_default(record, chosen) + if enabled and state["thinking"] != "off": + state.update(thinking="on", chosen=True) + return state + + +def thinking_line(row, settings): + """Shared display text; unknown installed checkpoints have no line.""" + state = thinking_state(row, settings) + return thinking.deployment_text(state) if state else None + + +def rendezvous_head(fabric, container, observed): + """Resolve a master to a Spark, preferring ownership on the worker's cable. + + Unique fabric/host addresses also identify masters reached through relays. + Legacy reports without address ownership may use a single observed rank zero; + multiple possible owners are never combined into an invented distributed run. + """ + master = container.get("master_addr") + positions = {p["position"]: p for p in fabric["positions"]} + local = positions[container["position"]] + owners = {p["position"] for p in positions.values() + if master in p.get("addresses", [p.get("address")]) + or master == p.get("hostname")} + if container.get("node_rank") == 0: + return container["position"] if not owners or container["position"] in owners else None + neighbors = {n["position"] for n in local.get("neighbors", []) if n["address"] == master} + if len(neighbors) == 1: + return next(iter(neighbors)) + if len(owners) == 1: + return next(iter(owners)) + if owners or neighbors: + return None + heads = {c["position"] for c in observed if c.get("node_rank") == 0 + and (c.get("engine"), c.get("master_addr"), c.get("master_port")) == + (container.get("engine"), master, container.get("master_port"))} + return next(iter(heads)) if len(heads) == 1 else None + + +def parallelism(facts): + """Display only parallel sizes present in the public launch 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): + """Join fresh launch facts by head Spark, or GPU jobs by image and rendezvous.""" + from runtime.host.node_containers import MAX_CONTAINERS, thinking_kwargs + groups, observed = {}, [] + known = {(c["position"], c["name"]) for row in deployments if not row["stopped"] for c in row["containers"]} + for position in fabric["positions"]: + candidates = [d for d in documents if isinstance(d, dict) and d.get("node_id") == position.get("node_id") + and position.get("node_id")] + candidates = [d for d in candidates if number(d.get("observed_at"))] + if not candidates: + continue + doc = max(candidates, key=lambda d: d["observed_at"]) + interval = doc.get("interval_seconds") + interval = min(3600, max(30, interval)) if number(interval) else 30 + if not -5 <= now - doc["observed_at"] <= max(90, interval * 2 + 30): + continue + rows = doc.get("model_containers") + for container in rows[:MAX_CONTAINERS] if isinstance(rows, list) else []: + if not isinstance(container, dict) or container.get("managed") is not False: + continue + name = container.get("name") + if not isinstance(name, str) or not CONTAINER_RE.fullmatch(name) or (position["position"], name) in known: + continue + # 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", "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")) + if kwargs is not None: + c["default_chat_template_kwargs"] = kwargs + master = c.get("master_addr") + if master: + try: + parsed = ipaddress.ip_address(master) + master = None if parsed.is_loopback or parsed.is_unspecified else str(parsed) + except ValueError: + master = master.lower().rstrip(".") + if master == "localhost": + master = None + c["master_addr"] = master + observed.append(c) + for c in observed: + head = rendezvous_head(fabric, c, observed) if c.get("master_addr") and c.get("master_port") else None + key = (("gpu-job", c.get("image_id") or c.get("image"), c["master_addr"], c["master_port"]) + if c.get("engine") == "unknown" and c.get("master_addr") and c.get("master_port") else + (c.get("engine"), "head", head, c["master_port"]) if head is not None else + ("single", c["position"], c["name"])) + groups.setdefault(key, []).append(c) + result = [] + for key, containers in groups.items(): + containers.sort(key=lambda c: (c.get("node_rank", 65536), c["position"], c["name"])) + positions = sorted({c["position"] for c in containers}) + ranks = {c["node_rank"] for c in containers if "node_rank" in c} + expected = max([c.get("nnodes", 1) for c in containers] + [max(ranks, default=0) + 1]) + heads = [c for c in containers if c.get("engine") in ("vllm", "sglang", "flare") + and c.get("node_rank", 0 if expected == 1 else -1) == 0 and not c["headless"]] + head = heads[0] if len(heads) == 1 else None + info = head or containers[0] + head_position = head["position"] if head else None + head_spark = next((p for p in fabric["positions"] if p["position"] == head_position), {}) + bind = (head or {}).get("api_bind") + loopback = bind in ("127.0.0.1", "::1", "localhost") + host = (head_spark.get("address") if not bind or bind in ("0.0.0.0", "::") else + bind if bind in head_spark.get("addresses", [head_spark.get("address")]) else None) + complete = len(ranks) == expected and len(positions) >= expected + if expected == 1: + complete = True + summary = (None if complete else + "head Spark not reporting" if info.get("engine") == "flare" and 0 not in ranks + else f"incomplete: {len(positions)} of {expected} Sparks reporting") + digest = hashlib.sha256(json.dumps(key).encode()).hexdigest()[:20] + result.append({"id": "unmanaged-" + digest, "unmanaged": True, "model": head.get("served_model") if head else None, + "positions": positions, "head_position": head_position, "api_host": host, + "api_port": head.get("api_port") if head and host else None, + "head_port": head.get("api_port") if head else None, "api_local": loopback, + "stopped": False, "containers": containers, "launch": info, + "expected_sparks": expected, "group_note": summary, + "stopped_records": [r for r in deployments if r["stopped"] and set(r["positions"]) & set(positions)]}) + return result + + +class Source: + """One fabric's host files: its fabric document and its site file, re-read when they change.""" + + def __init__(self, fabric_path: Path, site_path: Path): + self.fabric_path, self.site_path = Path(fabric_path), Path(site_path) + self.stamps = None + self.fabric = None + self.deployments: list = [] + self.problem = None + self.display_name = None + + def _stamp(self, path): + """(device, inode, modification time, size): a file replaced by rename gets another inode + even when its time and size repeat.""" + try: + stat = path.stat() + return (stat.st_dev, stat.st_ino, stat.st_mtime_ns, stat.st_size) + except OSError: + return None + + def refresh(self, force: bool = False) -> bool: + """Re-read both files when either one's stamp changed, or when `force`; True when they were + re-read.""" + stamps = (self._stamp(self.fabric_path), self._stamp(self.site_path)) + if stamps == self.stamps and not force: + return False + self.stamps = stamps + self.display_name = None + try: + self.fabric = fabric_from_document(read_json(self.fabric_path)) + except (OSError, ValueError) as error: + self.fabric, self.deployments = None, [] + self.problem = f"fabric document {self.fabric_path}: {error}" + return True + try: + site = read_json(self.site_path) + self.deployments = deployments_from_site(site, self.fabric["size"]) + from runtime.host import ring_name + if site.get("display_name") is not None: + self.display_name = ring_name.validate(site["display_name"]) + self.problem = None + except FileNotFoundError: + self.deployments = [] + self.problem = (f"no site file at {self.site_path}; on Node A, sudo sparkring dashboard export " + "writes it from the deployment records") + except (OSError, ValueError) as error: + self.deployments = [] + self.problem = f"site file {self.site_path}: {error}" + return True + + def ring_id(self) -> str: + cluster = (self.fabric or {}).get("cluster") or "fabric" + return "ring-" + re.sub(r"[^A-Za-z0-9_.-]", "-", cluster)[:40] + + +def recovery_findings(path: Path) -> dict: + """{deployment directory name: {state, summary, next_action, checked_at, enabled}} from the + recovery timer's sparkring-recovery/v1 record; empty when it is absent or unreadable.""" + try: + document = read_json(path) + except (OSError, ValueError): + return {} + if not isinstance(document, dict) or document.get("schema") != "sparkring-recovery/v1": + return {} + found = {} + for directory, record in (document.get("deployments") or {}).items(): + if not isinstance(record, dict): + continue + finding = record.get("finding") if isinstance(record.get("finding"), dict) else {} + found[Path(str(directory)).name] = { + "state": finding.get("state"), "summary": finding.get("summary"), + "next_action": finding.get("next_action"), "checked_at": record.get("checked_at"), + "enabled": record.get("enabled", True), "stopped": bool(record.get("stopped")), + "telemetry": finding.get("telemetry")} + return found + + +def start_command(row): + """Name the saved deployment, including inactive records that share a slice.""" + if row.get("unmanaged"): + return None + profile, identity = row.get("profile"), row.get("id", "") + if isinstance(profile, str) and profile and (identity == profile or identity.startswith(profile + "-")): + command = ["sudo", "sparkring", "up", profile] + instance = identity[len(profile):].removeprefix("-") + if instance: + command += ["--instance", instance] + else: + command = ["sudo", "sparkring", "up", "--on", ",".join(map(str, row["positions"]))] + return shlex.join(command) + + +def log_commands(hostname, container) -> dict: + """How the operator prints a model's log on demand: the commands, not their output. + + The dashboard holds no SSH key and no Docker access; the operator runs these on the + head Spark with their own login, so nothing reads a log unless someone asks.""" + if not container: + return {"enabled": False, "host": hostname, "commands": []} + return {"enabled": True, "host": hostname, "commands": [f"sudo docker logs -f --tail {LOG_LINES} {container}"]} diff --git a/runtime/host/host_load.py b/runtime/host/host_load.py index 088b4a4d..ae5e8a3c 100644 --- a/runtime/host/host_load.py +++ b/runtime/host/host_load.py @@ -148,6 +148,35 @@ def save(settings, *, root="/") -> None: # -- placement -------------------------------------------------------------------------------- +def parse_cpu_list(text: str) -> list[int]: + """``0-3,8,10-11`` as a sorted list.""" + cpus: set[int] = set() + for item in text.strip().split(","): + item = item.strip() + if not item: + continue + first, _, last = item.partition("-") + cpus.update(range(int(first), int(last or first) + 1)) + return sorted(cpus) + + +def format_cpu_list(cpus) -> str: + """The inverse of :func:`parse_cpu_list`, with ranges.""" + ordered = sorted(set(cpus)) + parts: list[str] = [] + start = previous = None + for cpu in ordered: + if previous is not None and cpu == previous + 1: + previous = cpu + continue + if start is not None: + parts.append(f"{start}" if start == previous else f"{start}-{previous}") + start = previous = cpu + if start is not None: + parts.append(f"{start}" if start == previous else f"{start}-{previous}") + return ",".join(parts) + + def efficiency_cpus(root: Path | None = None, cpuinfo: Path | None = None) -> set | None: """The online CPUs outside the fastest class (on GB10 the ten Cortex-A725 cores), or None on a host whose cores are all of one class. @@ -163,12 +192,11 @@ def efficiency_cpus(root: Path | None = None, cpuinfo: Path | None = None) -> se def drop_in_text(cpus) -> str: - from spark_transport.sircl.sparkring_sircl import cpus as classifier lines = ["# Written by sparkring node host-load (placement efficiency): the CPUs outside the fastest", "# class, at idle priority. sudo sparkring node host-load set placement=default removes it.", "[Service]"] if cpus: - lines.append("CPUAffinity=" + classifier.format_cpu_list(cpus)) + lines.append("CPUAffinity=" + format_cpu_list(cpus)) lines += ["Nice=19", "CPUSchedulingPolicy=idle", "IOSchedulingClass=idle"] return "\n".join(lines) + "\n" From 36abf10b945671bcefd4ce9d4fdf95c91f51ba20 Mon Sep 17 00:00:00 2001 From: FujitsuPolycom <87842395+FujitsuPolycom@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:19:12 -0600 Subject: [PATCH 2/2] Split dashboard.html into zero-bundler dashboard_assets with SHA-256 CSP assembly --- runtime/host/dashboard.html | 1632 +------------------ runtime/host/dashboard_assets/app.js | 373 +++++ runtime/host/dashboard_assets/cards.js | 270 +++ runtime/host/dashboard_assets/charts.js | 167 ++ runtime/host/dashboard_assets/dashboard.css | 344 ++++ runtime/host/dashboard_assets/ring.js | 479 ++++++ runtime/host/dashboard_server.py | 13 +- runtime/host/test_dashboard_actions.py | 3 +- runtime/host/test_dashboard_modular.py | 70 + 9 files changed, 1721 insertions(+), 1630 deletions(-) create mode 100644 runtime/host/dashboard_assets/app.js create mode 100644 runtime/host/dashboard_assets/cards.js create mode 100644 runtime/host/dashboard_assets/charts.js create mode 100644 runtime/host/dashboard_assets/dashboard.css create mode 100644 runtime/host/dashboard_assets/ring.js create mode 100644 runtime/host/test_dashboard_modular.py diff --git a/runtime/host/dashboard.html b/runtime/host/dashboard.html index 07c7541d..dd3d164a 100644 --- a/runtime/host/dashboard.html +++ b/runtime/host/dashboard.html @@ -6,350 +6,7 @@ SparkRing @@ -412,1289 +69,10 @@

Events

diff --git a/runtime/host/dashboard_assets/app.js b/runtime/host/dashboard_assets/app.js new file mode 100644 index 00000000..ea8dd727 --- /dev/null +++ b/runtime/host/dashboard_assets/app.js @@ -0,0 +1,373 @@ +const viewerRates = new ViewerRates(); +"use strict"; +let data = null, receivedAt = 0, failing = false; + +let hoverId = null, selectedId = null; +const $ = (id) => document.getElementById(id); +const esc = (v) => String(v == null ? "" : v).replace(/[&<>"']/g, (c) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); +const has = (v) => v !== null && v !== undefined; +const int = (n) => has(n) ? Math.round(n).toLocaleString() : "–"; +const one = int; +const acceptancePct = f => has(f) ? (f * 100).toFixed(1) + "%" : "\u2013"; +const acceptedStep = f => has(f) ? f.toFixed(1) : "\u2013"; +const small = (n, places = 2) => !has(n) ? "–" : n < 10 ? n.toFixed(places) : int(n); +const rate = (n) => has(n) ? Math.round(n).toLocaleString() : "–"; // token rates: whole tokens per second +const pct = (f) => has(f) ? Math.round(f * 100) + "%" : "–"; +const gb = (b) => !has(b) ? "–" : b >= 1e12 ? small(b / 1e12, 1) + " TB" : Math.round(b / 1e9) + " GB"; +const clip = (s, n) => s && s.length > n ? s.slice(0, n - 1).replace(/[-_.]+$/, "") + "…" : (s || ""); +// Serving groups are told apart by color; the service assigns each group its index (arc.color). +const PALETTE = ["var(--g1)", "var(--g2)", "var(--g3)", "var(--g4)"]; +const JOB_COLOR = "var(--muted)"; +const gcolor = (i) => PALETTE[(i || 0) % PALETTE.length]; +const isFlare = m => !!(m && ((m.external && m.kind === "flare") || (m.unmanaged && (m.flare || m.launch?.engine === "flare")))); +const memberColor = m => isFlare(m) ? "var(--flare)" : m.unmanaged || m.gpu_job ? JOB_COLOR : gcolor(m.arc?.color); +const FLAME_PATH = "M12 2c.5 4.2-5 6.6-5 11.4a5 5 0 0 0 10 0c0-2.5-1.3-4.1-2.3-5.2-.2 1.7-1.1 2.8-2 2.8-1.2 0-1.8-1.2-1.3-2.6C12.8 6.6 12.3 4.2 12 2z"; +const FLAME = ``; +// Folded cards, by member id; kept in this browser only. +let folded = new Set(); +try { folded = new Set(JSON.parse(localStorage.getItem("sparkring-folded") || "[]")); } catch (_) { /* Storage is optional. */ } +function foldButton(id, name) { + const open = !folded.has(id); + return ``; +} +function toggleFold(id) { + if (folded.has(id)) folded.delete(id); else folded.add(id); + try { localStorage.setItem("sparkring-folded", JSON.stringify([...folded])); } catch (_) { /* Storage is optional. */ } + scheduleRender(); +} +const span = (positions) => !positions || !positions.length ? "" : + positions.length === 1 ? String(positions[0]) : + positions.some((p, i) => i && p > positions[i - 1] + 1) ? positions.join(", ") : positions[0] + "–" + positions[positions.length - 1]; +const sparkCount = n => `${n} Spark${n === 1 ? "" : "s"}`; +const positionText = p => `position${p.length === 1 ? "" : "s"} ${span(p)}`; +const parallelism = f => ["tp", "dcp", "pp", "dp"].filter(k => has(f[k])).map(k => k.toUpperCase() + f[k]).join(" / "); +const gpuSummary = s => (s.containers || []).map(c => `container ${c.name}${c.image || c.image_id ? ", image " + (c.image || c.image_id) : ""}`).join("; "); +function dur(s) { + if (!has(s) || s < 0) return ""; + s = Math.round(s); + if (s < 60) return s + " s"; + const m = Math.floor(s / 60); + if (m < 60) return m + " min"; + const h = Math.floor(m / 60); + if (h < 48) return h + " h " + (m % 60) + " min"; + return Math.floor(h / 24) + " d " + (h % 24) + " h"; +} +function clock(t) { + const d = new Date(t * 1000), today = new Date(); + const time = d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); + return d.toDateString() === today.toDateString() ? time + : d.toLocaleDateString([], { month: "short", day: "numeric" }) + " " + time; +} +const serverNow = () => data ? data.generated_at + (Date.now() / 1000 - receivedAt) : Date.now() / 1000; + +// -- theme ------------------------------------------------------------------------------- +// A stored choice overrides the system theme; without one the page follows the system. +try { + const stored = localStorage.getItem("sparkring-theme"); + if (stored === "light" || stored === "dark") document.documentElement.dataset.theme = stored; +} catch (_) { /* Storage is optional. */ } +document.getElementById("theme").addEventListener("click", () => { + const root = document.documentElement; + const current = root.dataset.theme || (matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark"); + root.dataset.theme = current === "light" ? "dark" : "light"; + try { localStorage.setItem("sparkring-theme", root.dataset.theme); } catch (_) { /* Storage is optional. */ } +}); + +function render() { + if (document.hidden) return; + if (!data) { + setHidden($("banner"), !failing); + if (failing) text($("banner"), "Can't reach the dashboard service."); + return; + } + setHidden($("manage"), !data.manage); + setHidden($("banner"), !failing); + if (failing) text($("banner"), data ? `Can't reach the dashboard service. Showing what it reported at ${clock(data.generated_at)}.` : "Can't reach the dashboard service."); + const now = serverNow(); + const groups = data.groups || []; + const ringMembers = groups.filter((g) => g.kind === "ring").flatMap((g) => g.members || []); + const fixedMembers = groups.filter((g) => g.kind !== "ring").flatMap((g) => g.members || []); + const stacks = ringMembers.concat(fixedMembers); + const parts = []; + const rings = ringsOf(data); + if (rings.length) { + const n = ringMembers.filter((s) => s.state === "serving").length; + const {busy} = ringCounts(rings, ringMembers); + const size = rings.reduce((a, r) => a + (r.size || 0), 0); + parts.push(`${n} serving group${n === 1 ? "" : "s"}${rings.length > 1 ? ` on ${rings.length} rings` : ""}`, + `${busy} of ${sparkCount(size)} busy`); + } + if (fixedMembers.length) parts.push(`${fixedMembers.filter((s) => s.state === "serving").length} of ${fixedMembers.length} profiles serving`); + if (!rings.length) { + const {running, tps} = servingTotals(stacks); + parts.push(`${int(running)} request${running === 1 ? "" : "s"} running`, `${rate(tps)} tok/s out`); + if (perRequest(tps, running) !== null) parts.push(`${rate(perRequest(tps, running))} tok/s per request`); + } + text($("summary"), parts.join(" · ")); + renderRings(rings, ringMembers, now); + refreshSpark(); + // Preserve arrival order even if discovery changes its ordering. + const incoming = new Map(stacks.map(s => [s.id, s])); + for (const card of [...$("stacks").children]) { + if (!incoming.has(card.dataset.member)) { views.delete(card.dataset.member); card.remove(); } + } + const order = [...$("stacks").children].map(c => c.dataset.member); + for (const s of stacks) if (!order.includes(s.id)) order.push(s.id); + patch($("stacks"), order.map(id => card(incoming.get(id), now)).join("")); + renderExternal(data.external || [], now); + updateGraphControls(); + for (const s of stacks) updateGraphs(s); + applyHighlight(); + const ev = (data.events || []).map((e) => `
  • + ${esc(e.stack)} ${esc(e.text)}
  • `).join("") + || '
  • No changes since the service started.
  • '; + patch($("events"), ev); + const c = data.collector || {}; + text($("footer"), c.quiet ? "Paused" : c.viewed ? "2 s samples \u00b7 6 s rates" : "No active viewer"); +} + +// Text writes keep existing nodes, so unchanged selections and focus survive. +function text(el, value) { + const next = String(value); + if (el.textContent === next) return; + if (el.childNodes.length === 1 && el.firstChild.nodeType === Node.TEXT_NODE) el.firstChild.nodeValue = next; + else el.textContent = next; +} +function attr(el, name, value) { + if (el.getAttribute(name) !== String(value)) el.setAttribute(name, value); +} +function setHidden(el, value) { + if (el.hidden !== value) el.hidden = value; +} +function nodeKey(n) { + if (n.nodeType !== Node.ELEMENT_NODE) return n.nodeName; + return n.tagName + ":" + (n.dataset.key || n.dataset.graph || n.dataset.controls || n.dataset.ring || + (n.classList.contains("node") ? n.querySelector(".num")?.textContent : n.dataset.member) || n.id || n.classList[0] || ""); +} +function reconcile(parent, source) { + const available = [...parent.childNodes], used = new Set(); + let cursor = parent.firstChild; + for (const next of [...source.childNodes]) { + const key = nodeKey(next); + let node = available.find(n => !used.has(n) && nodeKey(n) === key); + if (!node) node = next.cloneNode(true); + used.add(node); + if (node !== cursor) parent.insertBefore(node, cursor); + cursor = node.nextSibling; + if (node.nodeType === Node.TEXT_NODE) { + if (node.nodeValue !== next.nodeValue) node.nodeValue = next.nodeValue; + } else if (node.nodeType === Node.ELEMENT_NODE) { + for (const a of [...node.attributes]) { + if (a.name === "open" && node.tagName === "DETAILS") continue; + if (!next.hasAttribute(a.name)) node.removeAttribute(a.name); + } + for (const a of next.attributes) { + if (a.name === "class" && node.hasAttribute("data-member")) { + const classes = a.value.split(" ").concat(node.classList.contains("hot") ? ["hot"] : [], node.classList.contains("sel") ? ["sel"] : []); + attr(node, a.name, classes.join(" ")); + } else attr(node, a.name, a.value); + } + if (!next.hasAttribute("data-island")) reconcile(node, next); + } + } + for (const node of available) if (!used.has(node)) node.remove(); +} +function patch(el, html) { + if (el.lastMarkup === html) return; + el.lastMarkup = html; + // Only detached templates are parsed. Live subtrees are never replaced. + const template = document.createElement("template"); + template.innerHTML = html; + reconcile(el, template.content); +} +let frame = null, dirty = false; +function scheduleRender(full = true) { + dirty ||= full; + if (document.hidden || frame !== null) return; + frame = requestAnimationFrame(() => { + frame = null; + if (document.hidden) return; + if (dirty) { dirty = false; render(); } + tick(); + }); +} +function tick() { + if (document.hidden) return; + attr($("live"), "class", "live " + (failing ? "bad" : data ? "ok" : "")); + if (data) text($("fresh"), failing ? "Not updating" : "Live · updated " + dur(Date.now() / 1000 - receivedAt) + " ago"); + const now = serverNow(); + for (const el of document.querySelectorAll("[data-age]")) text(el, Number(el.dataset.age) ? (el.dataset.prefix || "") + dur(now - Number(el.dataset.age)) : ""); + for (const el of document.querySelectorAll("[data-controls]")) { + const v = graphView; + text(el.querySelector(".pause-age"), v.paused === null ? "Live" : "Paused · " + dur(now - v.paused) + " ago"); + } +} +document.addEventListener("visibilitychange", () => { + if (!document.hidden) { + for (const box of document.querySelectorAll("[data-graph]")) { + if (viewFor(box.dataset.graphMember).paused === null) box.plotSignature = null; + } + scheduleRender(); + } +}); + +let historyLoaded = false, historyCursor = null; +async function refresh() { + try { + if (!historyLoaded) { + historyLoaded = true; + try { + const response = await fetch("/api/history", { cache: "no-store" }); + if (response.ok) { + const history = await response.json(); + viewerRates.seed(history); historyCursor = history.history_cursor ?? null; + } + } catch (_) { /* Live collection remains available if history cannot be loaded. */ } + } + const r = await fetch("/api/status" + (historyCursor === null ? "" : `?since=${historyCursor}`), { cache: "no-store" }); + if (!r.ok) throw new Error("HTTP " + r.status); + const doc = await r.json(); + data = viewerRates.apply(doc); + historyCursor = doc.history_cursor ?? null; + receivedAt = Date.now() / 1000; + failing = false; + scheduleRender(); + } catch (e) { + failing = true; + scheduleRender(); + } + setTimeout(refresh, ((data && data.poll_seconds) || 5) * 1000); +} + +// Asks the collector to read this model's runtime status once more (accepted at most every +// few minutes per model): each read makes the model's workers report through the engine. +async function rereadSettings(btn) { + btn.disabled = true; + try { + const r = await fetch(`/api/refresh?model=${encodeURIComponent(btn.dataset.model)}`, { cache: "no-store" }); + btn.textContent = r.status === 202 ? "Requested" : "Recently read"; + } catch (e) { btn.textContent = "Not reachable"; } + setTimeout(() => { btn.textContent = "Re-read settings"; btn.disabled = false; }, 4000); +} + +async function copy(text, btn) { + let ok = false; + try { + if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(text); ok = true; } + } catch (e) { ok = false; } + if (!ok) { + const ta = document.createElement("textarea"); + ta.value = text; ta.setAttribute("readonly", ""); ta.style.position = "fixed"; ta.style.opacity = "0"; + document.body.appendChild(ta); ta.select(); + try { ok = document.execCommand("copy"); } catch (e) { ok = false; } + ta.remove(); + } + btn.textContent = ok ? "Copied" : "Select and copy"; + setTimeout(() => { btn.textContent = "Copy"; }, 1500); +} + +let manageTicket = null; +let manageVersion = 0; +function clearManageReview() { + manageVersion += 1; + manageTicket = null; + $("manage-confirm").disabled = true; +} +async function management(path, body) { + const token = $("manage-token").value; + const headers = { Authorization: `Bearer ${token}` }; + const session = await fetch("/api/manage", { headers, cache: "no-store" }); + const auth = await session.json(); + if (!session.ok) throw new Error(auth.error || "Authentication failed"); + const response = await fetch(path, { method: "POST", cache: "no-store", + headers: { ...headers, "Content-Type": "application/json", "X-CSRF-Token": auth.csrf }, + body: JSON.stringify(body) }); + const result = await response.json(); + if (!response.ok) throw new Error(result.error || "Action refused"); + return result; +} +$("manage").addEventListener("input", clearManageReview); +$("manage-preview").addEventListener("click", async () => { + clearManageReview(); + const version = manageVersion; + const button = $("manage-preview"); + button.disabled = true; + $("manage-message").textContent = "Reading the plan and activity…"; + try { + const action = $("manage-action").value; + const request = { action, on: $("manage-on").value.trim() }; + if (action === "install") { + request.profile = $("manage-profile").value.trim(); + request.options = {}; + for (const [id, key] of [["checkpoint", "checkpoint"], ["length", "context-length"], ["memory", "kv-cache-gib"], ["limit", "download-limit"]]) { + const value = $("manage-" + id).value.trim(); + if (value) request.options[key] = value; + } + } + const result = await management("/api/manage/preview", request); + const plan = result.plan || {}; + const warning = plan.activity ? "\nActivity: " + plan.activity.grade + "\n" + plan.activity.message : ""; + $("manage-output").textContent = (result.stderr || "") + warning + (plan.steps ? "\nPlan: " + plan.steps.join(" → ") : "") + (result.follow ? "\n" + result.stdout + "\nFollow in a terminal: " + result.follow : ""); + if (version !== manageVersion) { + $("manage-message").textContent = "The selection changed while the plan was loading. Review it again."; + return; + } + manageTicket = result.confirmation || null; + $("manage-confirm").disabled = !manageTicket; + $("manage-message").textContent = manageTicket ? "Review the plan and activity below. Confirmation applies this exact action." : (result.follow ? "Log snapshot shown. Follow using the terminal command." : "This action cannot proceed; review the result."); + } catch (error) { $("manage-message").textContent = error.message; } + finally { button.disabled = false; } +}); +$("manage-confirm").addEventListener("click", async () => { + const confirmation = manageTicket; + clearManageReview(); + if (!confirmation) return; + $("manage-preview").disabled = true; + $("manage-message").textContent = "Action running. Its slice log is available in another terminal."; + try { + const result = await management("/api/manage/confirm", { confirmation }); + $("manage-output").textContent = (result.stderr || "") + "\n" + (result.stdout || ""); + $("manage-message").textContent = result.code === 0 ? "Action completed." : "Action stopped; see the result."; + } catch (error) { $("manage-message").textContent = error.message + ". Check slice logs before retrying."; } + finally { $("manage-preview").disabled = false; } +}); + +// Hovering a group anywhere (ring, legend, card) highlights it everywhere; clicking selects it. +for (const id of ["ringviz", "legend", "stacks"]) { + const root = $(id); + root.addEventListener("mouseover", (e) => { + const el = e.target.closest("[data-member]"); + const next = el && el.dataset.member ? el.dataset.member : null; + if (next !== hoverId) { hoverId = next; applyHighlight(); } + }); + root.addEventListener("mouseleave", () => { if (hoverId) { hoverId = null; applyHighlight(); } }); +} +for (const id of ["ringviz", "legend"]) { + $(id).addEventListener("click", (e) => { + if (e.target.closest(".node")) return; + const el = e.target.closest("[data-member]"); + if (el && el.dataset.member) selectGroup(el.dataset.member); + }); +} +$("stacks").addEventListener("click", (e) => { + const action = e.target.closest("button[data-action]"); + if (action) { + clearManageReview(); + $("manage-on").value = action.dataset.on; + $("manage-action").value = action.dataset.action; + $("manage-profile").value = action.dataset.profile; + $("manage-message").textContent = "Choose options if needed, then review the plan and activity."; + $("manage").scrollIntoView({ block: "start", behavior: "smooth" }); + } + const fold = e.target.closest("button.fold"); + if (fold) toggleFold(fold.dataset.fold); + const btn = e.target.closest("button.copy"); + if (btn && btn.dataset.copy) copy(btn.dataset.copy, btn); + const reread = e.target.closest("button.reread"); + if (reread) rereadSettings(reread); +}); +initRingEvents(); +initChartEvents(); +setInterval(() => scheduleRender(false), 1000); +refresh(); diff --git a/runtime/host/dashboard_assets/cards.js b/runtime/host/dashboard_assets/cards.js new file mode 100644 index 00000000..24cb3c2f --- /dev/null +++ b/runtime/host/dashboard_assets/cards.js @@ -0,0 +1,270 @@ +// -- cards --------------------------------------------------------------------------------- +const tokfmt = (n) => !has(n) ? null : n >= 1e6 ? int(n / 1e6) + "M" + : n >= 1e3 ? Math.round(n / 1e3) + "k" : String(Math.round(n)); + +function tiles(s) { + const l = s.live || {}, max = s.capacity?.max_num_seqs || s.settings?.max_num_seqs; + return `
    +
    Output tok/s
    ${rate(l.output_tps)}
    +
    Prefill tok/s
    ${rate(l.prefill_tps)}
    +
    Requests running / max
    ${int(l.running)} / ${int(max)}
    +
    KV in use % of tokens
    ${pct(l.kv)}
    +
    `; +} +function metricDetails(s) { + const l = s.live || {}; + return `

    Output ${rate(l.output_tps)} tok/s · Prefill ${rate(l.prefill_tps)} tok/s · ${one(l.steps_ps)} steps/s · ${acceptancePct(l.acceptance)} draft acceptance · Requests ${int(l.running)} running · KV ${pct(l.kv)} of tokens in use

    Output 5 min avg ${rate(l.output_tps_5m)} tok/s · Prefill interval ${l.source === "plugin" ? "exact" : "approximate"} · ${int(l.waiting)} requests waiting · Draft ${one(l.accept_length_5m)} tok/step (last 5 min) ? Sample time ${has(l.read_at) ? esc(clock(l.read_at)) : "unknown"}

    `; +} +function sampleSource(s, now) { + const l = s.live || {}; + return `${l.source === "plugin" ? "plugin" : "/metrics"} · sample ${has(l.read_at) + ? `${dur(now - l.read_at)} ago` : "unknown"}`; +} + +function sparks(s) { + const nodes = {}; + for (const n of s.nodes || []) if (n.node) nodes[n.node] = n; + return `
    ${(s.sparks || []).map((p) => { + const n = nodes[p.name], cls = p.up === true ? "up" : p.up === false ? "down" : ""; + let detail = p.up === false ? "unreachable" : ""; + if (n && p.up !== false) { + detail = [has(n.memory_available) ? gb(n.memory_available) + " RAM free" : "", + has(n.disk_available) ? gb(n.disk_available) + " disk free" : ""].filter(Boolean).join(" · "); + } + const pos = has(p.position) ? `${esc(p.position)}` : ""; + return `${pos}${esc(p.name)}${detail ? `${esc(detail)}` : ""}`; + }).join("")}
    `; +} + +function settings(s) { + const t = s.settings, cap = s.capacity || {}; + if (!t && !Object.keys(cap).length) return ""; + const kvBits = []; + if (cap.kv_bytes || (t && t.kv_cache_memory_bytes)) kvBits.push(gb(cap.kv_bytes || t.kv_cache_memory_bytes)); + if (cap.kv_tokens) kvBits.push("≈ " + tokfmt(cap.kv_tokens) + " tok"); + if (cap.concurrency !== null && cap.concurrency !== undefined) + kvBits.push(small(cap.concurrency) + "× full-ctx reqs"); + const media = cap.mm ? Object.entries(cap.mm).map(([k, v]) => v + " " + k + (v === 1 ? "" : "s")).join(" · ") : null; + // Images with runtime-status 0.3.6 and later report the transport carrying the TP collectives + // (tr.collective, with SIRCL's version); for older images the label is inferred from the TP + // group's backend facts. tr.label is the transport's display name, such as "RoCEnante (b12x)". + // The image's b12x bundle (tr.bundle) names what the image carries, whichever transport runs, + // so the page shows only the transport; the status JSON keeps the bundle. + const tr = s.transport || {}; + const transport = !tr.label ? null : tr.collective + ? tr.label + (tr.sircl_version ? " " + tr.sircl_version : "") + : tr.label + (tr.nccl === false ? " · NCCL off" : ""); + const rows = [ + ["Context", has(cap.max_model_len || s.max_model_len) ? int(cap.max_model_len || s.max_model_len) + " tokens" : null], + ["Max concurrent", has(cap.max_num_seqs || (t && t.max_num_seqs)) ? (cap.max_num_seqs || t.max_num_seqs) + " seqs" : null], + ["Batch tokens", t && has(t.max_num_batched_tokens) ? int(t.max_num_batched_tokens) : null], + ["KV budget", kvBits.length ? kvBits.join(" · ") : null], + ["KV cache type", t ? t.cache_dtype : null], + ["Media / request", media], + ["GPU mem target", has(cap.gpu_memory_utilization) ? Math.round(cap.gpu_memory_utilization * 100) + "%" : null], + ["Draft", t && t.speculative_method ? t.speculative_method + (t.num_speculative_tokens ? " × " + t.num_speculative_tokens : "") : null], + ["Reasoning parser", t ? t.reasoning_parser : null], + ["Tool parser", t ? t.tool_call_parser : null], + ["Chat defaults", t && t.default_chat_template_kwargs ? (typeof t.default_chat_template_kwargs === "string" + ? t.default_chat_template_kwargs : JSON.stringify(t.default_chat_template_kwargs)) : null], + ["Quantization", t ? t.quantization : null], + ["Tensor parallel", t ? t.tensor_parallel_size : null], + ["Collective transport", transport], + ["Image", s.image], + ].filter((r) => has(r[1]) && r[1] !== ""); + return `
    ${rows.map((r) => `
    ${esc(r[0])}
    ${esc(r[1])}
    `).join("")}
    `; +} + +// The recovery timer on Node A checks the active model about once a minute and records its +// finding; the dashboard shows that record and sends no check of its own. +function recoveryLine(s, now) { + const r = s.recovery; + if (!r || !r.summary) return ""; + const age = has(r.checked_at) ? ` · checked ${dur(now - r.checked_at)} ago` : ""; + const cls = r.state && r.state !== "serving" ? ' style="color:var(--warn)"' : ""; + return `

    Recovery check: ${esc(r.summary)}${age}${r.next_action ? " · next: " + esc(r.next_action) : ""}

    `; +} + +function totals(s, now) { + const t = s.totals || {}, f = t.finished || {}, l = s.live || {}; + const done = (f.stop || 0) + (f.length || 0); + const parts = [`${int(done)} requests done`, + `${int(f.error || 0)} failed`, `${int(f.abort || 0)} cancelled`, + `${int(t.preemptions || 0)} preempted`, + `first token ${small(l.ttft_5m, 1)} s avg (${esc(l.source || "/metrics")})`, + `prefix cache ${pct(l.prefix_hit_5m)} hits (/metrics)`, + `${int(s.workers?.received)} of ${int(s.workers?.expected)} ranks reporting`]; + return `
    ${parts.map(p => `${p}`).join("")}
    `; +} + +// -- logs on demand --------------------------------------------------------------------- +// The dashboard reads no log: it holds no SSH key and no Docker access. The panel shows the +// commands that print the head container's log, for the operator to run on that Spark. +function logsPanel(s) { + const l = s.logs || {}; + if (!l.enabled || !(l.commands || []).length) return ""; + return `
    Logs run on ${esc(l.host || "the head Spark")} +
    ${l.commands.map((c) => `
    ${esc(c)}
    `).join("")}
    +
    `; +} + +function unmanagedFacts(s) { + const f = s.launch || {}, flare = isFlare(s); + // A fact the page could not read is left out, never named, as the Spark details are: + // a GPU compute job shows the container's identity alone, and a Flare process lists + // only the rank, rendezvous, served name and API its launch declared. + const known = v => has(v) && v !== "" && String(v).toLowerCase() !== "unknown"; + const tell = (...parts) => parts.filter(Boolean).join(" · "); + const rendezvous = c => !known(c.master_addr) ? (known(c.master_port) ? "master port " + esc(c.master_port) : "") + : "master " + esc(c.master_addr) + (known(c.master_port) ? ":" + esc(c.master_port) : ""); + const api = c => c.headless ? "headless" : !known(c.api_port) ? "" + : known(c.api_bind) ? "API " + esc(c.api_bind) + ":" + esc(c.api_port) : "API port " + esc(c.api_port); + const rank = c => known(c.node_rank) ? "node rank " + esc(c.node_rank) : ""; + const lines = c => { + const identity = tell(`position ${c.position}: ${esc(c.name)}`, + flare ? "flare process" : known(c.image) ? esc(c.image) : "", + known(c.image_id) ? esc(c.image_id) : ""); + if (flare) { + return [identity, tell("engine flare", known(c.served_model) ? "served name " + esc(c.served_model) : "", rank(c)), + tell(rendezvous(c), api(c))]; + } + return s.gpu_job ? [identity] : [identity, + tell(known(c.engine) ? esc(c.engine) : "", known(c.served_model) ? "served name " + esc(c.served_model) : "", + rank(c), known(c.nnodes) ? `${esc(c.nnodes)} node${c.nnodes === 1 ? "" : "s"}` : ""), + tell(esc(parallelism(c)), rendezvous(c), api(c))]; + }; + const summary = s.gpu_job ? "" : flare + ? tell(esc(s.layout.label), "flare process", known(f.served_model) ? esc(f.served_model) : "") + : tell(esc(s.layout.label), known(f.engine) ? esc(f.engine) : "", + known(f.image_id) ? "image " + esc(f.image_id) : ""); + return `

    ${esc(s.ownership_label)}

    + ${s.group_note ? `

    ${esc(s.group_note)}

    ` : ""} + ${s.api_local ? `

    The API is bound to loopback on the head Spark, so this page cannot read live counters. Start it with --host 0.0.0.0 to show them.

    ` : ""} + ${summary ? `

    ${summary}

    ` : ""} +
    ${flare ? "Process" : "Container"} launch facts and install records + ${(s.containers || []).map(c => `

    ${lines(c).filter(Boolean).join("
    ")}

    `).join("")} + ${(s.stopped_records || []).map(r => `

    Stopped install record: ${esc(r.id)} · ${esc(r.model)} · ${esc(positionText(r.positions))}

    `).join("")} +
    `; +} + +function card(s, now) { + if (s.external) return externalCard(s, now); + const st = s.state || "checking", serving = st === "serving"; + const since = s.state_since ? "for " + dur(now - s.state_since) : ""; + const layout = s.layout || {}, arc = s.arc; + const gc = arc ? memberColor(s) : null; + let sub = sparkCount(layout.count ?? (s.sparks || []).length); + if (serving && layout.label) sub = `${esc(layout.label)} · ${sub}`; + else if (st === "idle") sub = `${esc(layout.label || sub)} · not deployed`; + if (s.head && s.head.port) sub += ` · API on ${esc(s.head.name)}:${esc(s.head.port)}`; + if (s.profile) sub += ` · ${esc(s.profile)}`; + let model; + if (s.gpu_job) model = esc("GPU in use · " + gpuSummary(s)); + else if (!s.model) model = 'No model seen yet'; + else if (serving || s.unmanaged) model = esc(s.model); + else model = `${s.startup ? "Model:" : "Last served:"} ${esc(s.model)}`; + const note = (arc ? { + not_ready: "The API port is open but the model isn't answering yet. It is probably still starting.", + stopped: "Nothing listens on this deployment's API port: its model is stopped or still loading.", + offline: "The head Spark does not answer on its API address.", + idle: "Another deployment on an overlapping set of Sparks serves on this port.", + } : { + idle: "Another profile of this ring is using it right now.", + not_ready: "The API port is open but the model isn't answering yet. It is probably still starting.", + stopped: "The head node is up, but this profile isn't serving.", + offline: "This profile's head node doesn't answer on the network.", + })[st]; + const tags = []; + if (arc) { + const rings = ringsOf(data), ring = rings.find((r) => r.id === s.ring); + if (rings.length > 1 && ring) tags.push(`${esc(ring.short || ring.id)} ring`); + if (s.transport && s.transport.label) tags.push(`${esc(s.transport.label)}`); + tags.push(`${esc(positionText(arc.positions))}`); + if (arc.inferred) tags.push(`inferred`); + } + const sizes = s.unmanaged ? layout.label : parallelism({tp: s.settings?.tensor_parallel_size || layout.tp, dcp: s.settings?.decode_context_parallel_size || layout.dcp}) || layout.label; + const endpoint = serving && s.endpoint ? `${esc(s.endpoint)}` : ""; + const start = !serving && !s.startup && !s.unmanaged && s.start_command + ? `${esc(s.start_command)}` : ""; + const r = s.recovery, recovery = !r ? "" : r.enabled === false ? "recovery off" : r.state === "serving" ? "recovery ok" : "recovery " + (r.state || "unknown"); + const recoveryChip = recovery ? `${esc(recovery)}${has(r.checked_at) ? " · " + esc(dur(now - r.checked_at).split(" ").slice(0, 2).join(" ")) + " ago" : ""}` : ""; + const thinking = s.thinking ? `
    Thinking: ${esc(s.thinking)}
    ` : ""; + const modelText = s.name === s.model && !s.gpu_job ? (serving ? "" : `Last served: same model`) : `${model}`; + const open = !folded.has(s.id); + return `
    +
    + ${foldButton(s.id, s.name)}${esc(s.name)} + ${serving ? modelText + (sizes ? `${esc(sizes)}` : "") : ""} + ${tags.join("")} + ${esc(s.startup ? startupLabel(s) : s.state_label)}${esc(since)} + ${s.metrics_problem ? `Metrics unavailable` : ""} + ${!serving ? modelText : ""}${endpoint}${start}${recoveryChip} +
    ${open ? ` + ${startupDetails(s)} + ${s.metrics_problem ? `

    ${esc(s.metrics_problem)}

    ` : ""} + ${serving ? thinking + tiles(s) + `
    ${one(s.live?.steps_ps)} steps/s · ${acceptancePct(s.live?.acceptance)} draft acceptance${has(s.live?.accepted_per_step) ? ` · ${acceptedStep(s.live.accepted_per_step)} accepted tok/step` : ""} · ${sampleSource(s, now)}
    ` + charts(s) + sparks(s) : ""} +
    Details
    +
    ${sub}
    + ${!serving ? thinking + sparks(s) : ""} + ${s.thinking && s.thinking_provenance ? `
    Thinking details

    ${esc(s.thinking_provenance)}

    ` : ""} + ${s.details_url || serving ? `
    ${s.details_url ? `Model status` : ""}${serving ? `` : ""}
    ` : ""} + ${note ? `

    ${esc(note)}

    ` : ""} + ${s.unmanaged ? unmanagedFacts(s) : ""} + ${recoveryLine(s, now)}${settings(s)}${metricDetails(s)}${totals(s, now)}${logsPanel(s)} + ${data.manage && arc && !s.unmanaged ? `
    ${[["install", "Install / swap"], ["down", "Down"], ["restart", "Restart"], ["recovery-on", "Recovery on"], ["recovery-off", "Recovery off"], ["logs", "Follow logs"]].map(([action, title]) => ``).join('')}
    ` : ""} +
    ` : ""} +
    `; +} + +function externalCard(e, now) { + const st = e.state || "checking", serving = st === "serving", s = e.stats || {}; + const kind = e.kind === "flare" ? "Flare" : "OpenAI API", flare = e.kind === "flare"; + const gc = e.arc ? memberColor(e) : null; + const spark = e.head && e.head.name ? `${esc(e.head.name)} · ` : ""; + const where = e.arc ? `${esc(positionText(e.arc.positions))}` : ""; + const open = !folded.has(e.id); + const model = e.model ? esc(e.model) : 'No model seen yet'; + const note = ({ + stopped: "Nothing listens on this endpoint's port.", + offline: "The host does not answer on the network.", + not_ready: "The port is open but the server isn't answering its metrics yet.", + })[st]; + const endpoint = serving ? `${esc(e.endpoint)}` : ""; + const tiles = serving ? `
    +
    Output tok/s
    ${rate(s.output_tps)}
    +
    Tokens last minute
    ${int(s.tokens_last_minute)}
    +
    Requests running / max
    ${int(s.active_requests)} / ${int(s.request_capacity)}
    +
    KV in use % of tokens
    ${pct(s.kv_in_use)}
    +
    ` : ""; + const line = serving ? `
    ${has(s.uptime_seconds) ? "up " + dur(s.uptime_seconds) + " · " : ""}${int(s.requests_completed)} requests completed${has(s.requests_failed) && s.requests_failed ? " · " + int(s.requests_failed) + " failed" : ""}${has(s.draft_acceptance) ? " · " + pct(s.draft_acceptance) + " draft acceptance" : ""}
    ` : ""; + const details = serving ? `

    ${int(s.generated_tokens)} tokens generated · ${int(s.prefill_tokens)} prefilled · ${int(s.pending_requests)} pending${has(s.kv_tokens_total) ? ` · KV ${int(s.kv_tokens_total)} tokens${has(s.kv_tokens_cached) ? `, ${int(s.kv_tokens_cached)} cached` : ""}` : ""}${has(s.row_cache_hit_rate) ? ` · embedding row cache ${pct(s.row_cache_hit_rate)} hits` : ""}${has(s.prefix_hit_rate) ? ` · prefix cache ${pct(s.prefix_hit_rate)} hits` : ""}

    ` : ""; + return `
    +
    + ${foldButton(e.id, e.label)}${flare ? FLAME : ""}${esc(e.label)} + ${serving ? `${model}` : ""} + ${flare ? FLAME : ""}${esc(kind)}${where} + ${esc(e.state_label || "Checking")}${e.state_since ? "for " + dur(now - e.state_since) : ""} + ${e.metrics_problem ? `Metrics unavailable` : ""} + ${!serving ? `${model}` : ""}${endpoint} +
    ${open ? ` +
    ${spark}${esc(kind)} at ${esc(e.host)}:${esc(e.port)}${has(e.max_model_len) ? ` · ${int(e.max_model_len)}-token context` : ""}
    + ${e.metrics_problem ? `

    ${esc(e.metrics_problem)}

    ` : ""} + ${tiles}${line} +
    Details
    +
    ${esc(kind)} at ${esc(e.host)}:${esc(e.port)}${e.root ? ` · ${esc(e.root)}` : ""}${e.metrics_url ? ` · metrics ${esc(e.metrics_url)}` : ""}
    + ${note ? `

    ${esc(note)}

    ` : ""} + ${details} + ${(e.stopped_records || []).map(r => `

    Stopped install record: ${esc(r.id)} · ${esc(r.model)} · ${esc(positionText(r.positions))}

    `).join("")} +

    Not installed by SparkRing: no automatic recovery, no install record. The page reads its /metrics and /v1/models only.

    +
    ` : ""} +
    `; +} + +function renderExternal(list, now) { + const section = $("external-section"); + setHidden(section, !list.length); + if (!list.length) return; + const n = list.filter((e) => e.state === "serving").length; + text($("external-meta"), `${n} of ${list.length} serving · served outside the installer; read-only`); + patch($("external"), list.map((e) => externalCard(e, now)).join("")); +} diff --git a/runtime/host/dashboard_assets/charts.js b/runtime/host/dashboard_assets/charts.js new file mode 100644 index 00000000..1f6a29e8 --- /dev/null +++ b/runtime/host/dashboard_assets/charts.js @@ -0,0 +1,167 @@ +// Each plot owns a persistent SVG; geometry is computed only for a changed snapshot/window. +function chart(history, idx, now, cls, scale, window = "auto", limit = 10800) { + const span = window === "auto" ? limit : Math.min(Number(window), limit); + const start = Math.max(now - span, history[0]?.[0] ?? now - 1); + const width = Math.max(1, now - start), W = 300, H = 80; + const visible = history.filter(h => h[0] >= start && h[0] <= now); + const pts = visible.filter(h => has(h[idx])); + const peak = Math.max(0, ...pts.map(h => h[idx])); + const magnitude = 10 ** Math.floor(Math.log10(Math.max(1, peak * 1.1))); + const top = scale || Math.ceil(Math.max(2, peak * 1.1) / magnitude) * magnitude; + let d = "", prev = null; + for (const h of visible) { + if (!has(h[idx])) { prev = null; continue; } + const x = (h[0] - start) / width * W, y = H - 2 - h[idx] / top * (H - 4); + d += (prev === null || h[0] - prev > 185 ? "M" : "L") + x.toFixed(1) + "," + y.toFixed(1); + prev = h[0]; + } + return { d, peak, top, start, now, rows: pts, + svg: `` }; +} + +const graphNames = { 1: "Output tok/s", 4: "KV cache use", 5: "Prefill tok/s" }; +const windows = [["auto", "Auto"], ["300", "5 min"], ["900", "15 min"], ["3600", "1 h"], ["10800", "3 h"]]; +const views = new Map(); +// One viewer-local window and pause time; each member retains its frozen samples. +const graphView = { window: "auto", paused: null }; +try { graphView.window = localStorage.getItem("sparkring-window") || "auto"; } catch (_) { /* Storage is optional. */ } + +if (!windows.some(w => w[0] === graphView.window)) graphView.window = "auto"; +function viewFor(id) { + if (!views.has(id)) views.set(id, { history: graphView.paused === null ? null : [] }); + return { ...graphView, history: views.get(id).history }; +} +function updateGraphControls() { + const controls = $("page-graphs"); + if (!controls.firstChild) patch(controls, `${windows.map(([v, label]) => + ``).join("")} + `); + for (const b of controls.querySelectorAll("[data-window]")) attr(b, "aria-pressed", String(b.dataset.window === graphView.window)); + const pause = controls.querySelector("[data-pause]"); + text(pause, graphView.paused === null ? "❚❚" : "▶"); + attr(pause, "aria-label", graphView.paused === null ? "Pause graphs" : "Resume graphs"); +} +function options(selected, dialog = false) { + return [...windows, ...(dialog ? [["21600", "6 h"]] : [])].map(([v, label]) => + ``).join(""); +} +function graphBox(s, idx) { + // The plot updater owns children of this island, including pointer state. + return ``; +} +function charts(s) { + return `
    ${[1, 5, 4].map(i => graphBox(s, i)).join("")}
    `; +} +function plotShell(idx, title = "") { + return `${title}
    0
    + +
    `; +} +function drawPlot(box, history, idx, now, window, limit) { + const signature = JSON.stringify([history, window]); + if (box.plotSignature === signature) return; + box.plotSignature = signature; + const g = chart(history, idx, now, "", idx === 4 ? 1 : null, window, limit); + box.plot = g; + attr(box.querySelector("path"), "d", g.rows.length ? g.d : "M0,78L300,78"); + box.classList.toggle("empty", !g.rows.length); + setHidden(box.querySelector(".empty-plot"), !!g.rows.length); + const ys = box.querySelectorAll(".y-axis span"), xs = box.querySelectorAll(".x-axis span"); + const fmt = idx === 4 ? pct : int; + text(ys[1], fmt(g.top / 2)); text(ys[2], fmt(g.top)); + text(xs[0], now - g.start <= 900 ? dur(now - g.start) + " ago" : clock(g.start)); + text(xs[1], now - g.start <= 900 ? "now" : clock(now)); + if (has(box.pointerX)) inspectPointer(box, box.pointerX); +} +function updateGraphs(member) { + const card = [...$("stacks").children].find(c => c.dataset.member === member.id); + const v = viewFor(member.id), now = v.paused ?? serverNow(), history = v.history ?? member.history ?? []; + for (const box of card.querySelectorAll("[data-graph]")) { + const idx = Number(box.dataset.graph); + if (!box.firstChild) patch(box, plotShell(idx, `${graphNames[idx]}`) + ''); + drawPlot(box, history, idx, now, v.window, 10800); + } +} +let graphSelection = null, graphOpener = null; +function exactGraphValue(row, idx) { + return row ? `${new Date(row[0] * 1000).toISOString().replace(/\.\d{3}Z$/, "Z")} \u00b7 ${graphNames[idx]}: ${idx === 4 ? pct(row[idx]) : rate(row[idx])} \u00b7 ${row[6] === "plugin" ? "plugin" : "approx /metrics"}` : "No sample here"; +} +function inspectGraph() { + if (graphSelection) text($("graph-value"), exactGraphValue(graphSelection.rows[Number($("graph-sample").value)], graphSelection.idx)); +} +function drawDialog() { + const g = graphSelection, box = $("graph-body"); + const selectedAt = g.rows?.[Number($("graph-sample").value)]?.[0]; + if (!box.firstChild) patch(box, plotShell(g.idx)); + attr(box.querySelector("svg"), "class", g.idx === 4 ? "c2" : "c1"); + box.plotSignature = null; + drawPlot(box, g.history, g.idx, g.now, $("graph-window").value, 21600); + g.rows = box.plot.rows; + $("graph-sample").max = Math.max(0, g.rows.length - 1); + const selected = g.rows.findIndex(r => r[0] === selectedAt); + $("graph-sample").value = selected < 0 ? Math.max(0, g.rows.length - 1) : selected; + $("graph-sample").disabled = !g.rows.length; + inspectGraph(); +} +function openGraph(box, opener) { + const id = box.dataset.graphMember, idx = Number(box.dataset.graph), v = viewFor(id); + const member = data.groups.flatMap(g => g.members || []).find(m => m.id === id); + graphSelection = { id, idx, history: (v.history ?? member.history ?? []).map(r => [...r]), now: v.paused ?? serverNow() }; + $("graph-dialog").style.setProperty("--gc", memberColor(member)); + graphOpener = opener; + text($("graph-title"), graphNames[idx] + " — frozen snapshot"); + patch($("graph-window"), options(v.window, true)); + $("graph-window").value = v.window; + drawDialog(); $("graph-dialog").showModal(); +} +function pointerSample(clientX, box) { + const rect = box.querySelector("svg").getBoundingClientRect(), g = box.plot; + const target = g.start + Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)) * (g.now - g.start); + const row = g.rows.reduce((best, r) => !best || Math.abs(r[0] - target) < Math.abs(best[0] - target) ? r : best, null); + return row && Math.abs(row[0] - target) <= 185 ? row : null; +} +function inspectPointer(box, clientX) { + box.pointerX = clientX; + text(box.querySelector("output"), exactGraphValue(pointerSample(clientX, box), Number(box.dataset.graph))); +} + +function initChartEvents() { + $("graph-window").addEventListener("change", drawDialog); + $("graph-close").addEventListener("click", () => $("graph-dialog").close()); + $("graph-dialog").addEventListener("close", () => { graphSelection = null; graphOpener?.focus(); }); + $("graph-sample").addEventListener("input", inspectGraph); + $("stacks").addEventListener("pointermove", event => { + const box = event.target.closest("[data-graph]"); + if (box && event.target.closest("svg")) inspectPointer(box, event.clientX); + }); + $("stacks").addEventListener("pointerout", event => { + const box = event.target.closest("[data-graph]"); + if (box && !box.querySelector("svg").contains(event.relatedTarget)) box.pointerX = null; + }); + $("page-graphs").addEventListener("click", event => { + const choice = event.target.closest("[data-window]"); + if (choice) { + graphView.window = choice.dataset.window; + try { localStorage.setItem("sparkring-window", graphView.window); } catch (_) { /* Storage is optional. */ } + scheduleRender(); + return; + } + if (!event.target.closest("[data-pause]") || !data) return; + graphView.paused = graphView.paused === null ? serverNow() : null; + for (const member of data.groups.flatMap(g => g.members || [])) { + views.set(member.id, { history: graphView.paused === null ? null : (member.history || []).map(r => [...r]) }); + } + for (const box of document.querySelectorAll("[data-graph]")) box.plotSignature = null; + scheduleRender(); + }); + $("stacks").addEventListener("click", event => { + const box = event.target.closest("[data-graph]"); + if (box) openGraph(box, box); + }); + $("graph-body").addEventListener("pointermove", event => { + if (!event.target.closest("svg") || !graphSelection) return; + const row = pointerSample(event.clientX, $("graph-body")); + if (!row) { text($("graph-value"), "No sample here"); return; } + $("graph-sample").value = graphSelection.rows.indexOf(row); inspectGraph(); + }); +} diff --git a/runtime/host/dashboard_assets/dashboard.css b/runtime/host/dashboard_assets/dashboard.css new file mode 100644 index 00000000..26e31a07 --- /dev/null +++ b/runtime/host/dashboard_assets/dashboard.css @@ -0,0 +1,344 @@ +:root { + --bg: #0f171c; --surface: #152129; --ink: #e3eaed; --muted: #93a3ac; --line: #2a3943; + --g1: #3fc3cf; --g2: #74d494; --g3: #ac8ef6; --g4: #7aa6f6; --relay: #e3a246; + --ok: #74d494; --warn: #e3a246; --bad: #f08a80; --flare: #ff6a3d; + --panel: var(--surface); --panel2: var(--surface); --fg: var(--ink); --faint: var(--muted); + --line2: var(--line); --code: var(--bg); --accent: var(--g1); --idle: var(--muted); + --ok-bg: color-mix(in srgb, var(--ok) 12%, transparent); + --warn-bg: color-mix(in srgb, var(--warn) 12%, transparent); + --bad-bg: color-mix(in srgb, var(--bad) 12%, transparent); + --idle-bg: color-mix(in srgb, var(--idle) 12%, transparent); + --mono: ui-monospace, "Cascadia Mono", Consolas, monospace; + color-scheme: dark; +} +* { box-sizing: border-box; } +[hidden] { display: none !important; } +html { -webkit-text-size-adjust: 100%; } +body { margin: 0; background: var(--bg); color: var(--fg); + font: 14px/1.45 system-ui, "Segoe UI", sans-serif; padding: 20px 16px 40px; } +.mono, code { font-family: var(--mono); } +.wrap { max-width: 1360px; margin: 0 auto; display: grid; gap: 20px; min-width: 0; } +.top { display: flex; justify-content: space-between; align-items: flex-end; gap: 12px; flex-wrap: wrap; } +h1 { margin: 0; font-size: 1.45rem; font-weight: 650; letter-spacing: -0.01em; overflow-wrap: anywhere; } +#ringtitle { text-transform: none; letter-spacing: normal; overflow-wrap: anywhere; } +.summary { margin: 2px 0 0; color: var(--muted); } +.live { display: flex; align-items: center; gap: 8px; color: var(--muted); font-size: 0.85rem; } +.dot { width: 9px; height: 9px; border-radius: 50%; background: var(--idle); flex: none; } +.live.ok .dot { background: var(--ok); animation: pulse 2s ease-in-out infinite; } +.live.bad .dot { background: var(--bad); } +@keyframes pulse { 50% { opacity: 0.35; } } +@media (prefers-reduced-motion: reduce) { .live.ok .dot { animation: none; } } +.banner { background: var(--bad-bg); color: var(--bad); border-radius: 8px; padding: 10px 14px; font-weight: 500; } + +/* -- ring panel ------------------------------------------------------------------------ */ +.ringpanel { display: grid; grid-template-columns: minmax(0, 440px) minmax(0, 1fr); gap: 22px; align-items: start; + background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 18px; min-width: 0; } +.ringpanel.multi { grid-template-columns: minmax(0, 720px) minmax(0, 1fr); } +@media (max-width: 1180px) { .ringpanel.multi { grid-template-columns: minmax(0, 1fr); } } +@media (max-width: 860px) { .ringpanel { grid-template-columns: minmax(0, 1fr); padding: 14px; } } +.ringviz { min-width: 0; display: grid; gap: 18px 14px; grid-template-columns: repeat(var(--rings, 1), minmax(0, 1fr)); } +@media (max-width: 560px) { .ringviz { grid-template-columns: minmax(0, 1fr); } } +.ringfig { margin: 0; min-width: 0; } +.ringfig figcaption { text-align: center; font-size: 0.8rem; color: var(--muted); margin: 0 0 6px; overflow-wrap: anywhere; } +.ringfig figcaption b { color: var(--fg); font-weight: 650; } +.ringviz svg { display: block; width: 100%; max-width: 440px; height: auto; margin: 0 auto; overflow: visible; } +.rtag { display: inline-block; font: 650 0.68rem var(--mono); color: var(--fg); padding: 0 6px; margin-right: 6px; + border: 1px solid var(--line2); border-radius: 5px; background: var(--panel); vertical-align: 1px; } +.ringhead { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; flex-wrap: wrap; + margin-bottom: 6px; } +.ringhead h2 { margin: 0; font-size: 0.75rem; font-weight: 650; text-transform: uppercase; letter-spacing: 0.08em; + color: var(--muted); } +.ringhead .muted { font-size: 0.75rem; } +svg .cable { fill: none; stroke: var(--line); stroke-width: 8; stroke-linecap: round; } +svg .cable.in { stroke: var(--gc); } +svg .cable.outline { stroke-dasharray: 5 4; } +svg .cable-band { fill: none; stroke: var(--gc); stroke-width: 18; stroke-linecap: round; opacity: .12; } +svg .cable-band.dim { opacity: .07; } +svg .traffic { fill: var(--ink); offset-distance: 50%; animation: cable-traffic 3s linear infinite; pointer-events: none; } +@keyframes cable-traffic { from { offset-distance: 15%; } to { offset-distance: 85%; } } +svg .traffic.rev { animation-direction: reverse; animation-delay: -1.5s; } +@media (prefers-reduced-motion: reduce) { svg .traffic { animation: none; } } +svg .relay { fill: var(--relay); stroke: var(--surface); stroke-width: 1; } +svg .band, svg .node { cursor: pointer; } +svg .lbl { text-anchor: middle; } +svg .lbl text { paint-order: stroke; stroke: var(--surface); stroke-width: 4px; stroke-linejoin: round; } +svg .l1 { font: 650 12px system-ui, sans-serif; fill: var(--gc); } +svg .l2 { font: 9px var(--mono); fill: var(--muted); } +svg .lrate { font: 650 18px var(--mono); fill: var(--ink); } +svg .unit { font: 9px var(--mono); fill: var(--muted); } +svg .node rect { fill: var(--surface); stroke: var(--gc, var(--line)); stroke-width: 1.5; } +svg .node.serving rect { filter: drop-shadow(0 0 5px var(--gc)); } +svg .node .node-dot { fill: var(--gc, var(--muted)); } +svg .node .num { font: 700 12px var(--mono); fill: var(--ink); text-anchor: middle; } +svg .node .host { font: 10px var(--mono); fill: var(--muted); text-anchor: middle; } +svg .node.idle { opacity: .55; } +svg .node.outline rect, svg .node.unknown rect { stroke-dasharray: 3 2; } +svg .node.dim rect, svg .cable.dim { stroke-dasharray: none; } +svg .dim, .allocation .dim { opacity: .6; } +svg .node.down .host, svg .node .downtag { fill: var(--bad); } +svg .node .downtag { font: 700 9px var(--mono); text-anchor: middle; } +svg .node.hot rect, svg .node.sel rect { stroke-width: 3; } +svg .band.hot .l1, svg .band.sel .l1 { text-decoration: underline; } +svg .center { font: 12px var(--mono); fill: var(--muted); text-anchor: middle; } +.allocation { display: flex; flex-wrap: wrap; justify-content: center; gap: 4px; margin: 8px 0; } +.allocation-label { width: 100%; text-align: center; font: 9px var(--mono); letter-spacing: .12em; color: var(--muted); } +.allocation .slot { display: grid; place-items: center; width: 24px; height: 24px; border-radius: 3px; + font: 11px var(--mono); color: var(--bg); background: var(--gc, var(--line)); border: 1px solid var(--gc, var(--line)); } +.allocation .slot.outline { background: transparent; color: var(--muted); border-style: dashed; } +.configuration { text-align: center; font: 11px var(--mono); color: var(--muted); } +.configuration b { color: var(--ink); font-weight: 500; } +.ring-totals { color: var(--muted); font: 11px var(--mono); text-align: center; margin: 8px 0; } +.ring-totals b { color: var(--ink); font-weight: 600; } +svg .ring-totals { text-anchor: middle; } +svg .ring-totals rect { fill: var(--surface); stroke: var(--line); } +svg .ring-total-rate { font: 600 12px var(--mono); fill: var(--ink); } +svg .ring-total-requests { font: 10px var(--mono); fill: var(--muted); } +.ringfig figcaption, .tile .v, .legend .rate, .chart .k, .axis { font-family: var(--mono); } +.ringside { display: grid; gap: 14px; min-width: 0; align-content: start; } +.strip { display: flex; flex-wrap: wrap; gap: 1px; background: var(--line); + border: 1px solid var(--line); border-radius: 10px; overflow: hidden; } +.strip .tile { background: var(--panel2); flex: 1 1 112px; } +.strip .tile .s { white-space: normal; } +.legend { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; } +.legend li { display: grid; grid-template-columns: 12px minmax(0, 1.1fr) minmax(0, 1.3fr) minmax(0, .9fr); gap: 4px 12px; + align-items: center; padding: 9px 12px; border: 1px solid var(--line); border-radius: 9px; + background: var(--panel2); cursor: pointer; transition: border-color 0.15s, background 0.15s; min-width: 0; } +.legend li.hot, .legend li.sel { border-color: var(--gc); background: color-mix(in srgb, var(--gc) 8%, var(--panel2)); } +.legend .sw { width: 12px; height: 12px; border-radius: 4px; background: var(--gc); } +.legend .k-starting .sw, .legend .outline .sw { background: transparent; border: 1px dashed var(--gc); } +.legend .dim { opacity: .45; } +.legend .t1 { font-weight: 650; overflow-wrap: anywhere; } +.legend .t2 { color: var(--muted); font-size: 0.78rem; overflow-wrap: anywhere; } +.legend .col { min-width: 0; } +.legend .right { display: grid; justify-items: end; gap: 3px; min-width: 0; } +.legend .rate { font-variant-numeric: tabular-nums; font-weight: 650; font-size: 0.9rem; } +.legend .empty { display: block; color: var(--muted); cursor: default; grid-template-columns: 1fr; } +@media (max-width: 520px) { + .legend li { grid-template-columns: 12px minmax(0, 1fr) minmax(0, .8fr); } + .legend li .col.mid { grid-column: 2 / 3; } + .legend li .right { grid-column: 3; grid-row: 1 / 3; } +} +.ringnote { margin: 0; font-size: 0.78rem; color: var(--muted); } +.ringnote b { color: var(--fg); font-weight: 600; } +.ringnote .warnword { color: var(--warn); } +.ringnote:empty { display: none; } + +/* -- cards --------------------------------------------------------------------------- */ +.stacks { display: grid; gap: 16px; grid-template-columns: minmax(0, 1fr); align-items: start; } +.card { background: var(--panel); border: 1px solid var(--line); border-left: 4px solid var(--idle); + border-radius: 10px; padding: 12px; display: grid; gap: 8px; min-width: 0; + transition: border-color 0.15s; scroll-margin: 16px; } +.card.st-serving { border-left-color: var(--ok); } +.card.st-not_ready { border-left-color: var(--warn); } +.card.st-stopped { border-left-color: var(--idle); } +.card.st-stopped { opacity: .55; } +.card.outline { border-left-style: dashed; } +.card.st-idle { border-left-color: var(--idle); opacity: 0.75; } +.card.st-offline { border-left-color: var(--bad); } +.card.ringed { border-left-color: var(--gc); } +.card.flare:not(.st-offline) { border-left-color: var(--flare); } +.tag.flare { color: var(--flare); border-color: color-mix(in srgb, var(--flare) 45%, transparent); font-weight: 700; gap: 3px; } +/* The flame marks an endpoint served by Flare: beside its name, in its runtime tag and in the legend. */ +.flame { width: 1em; height: 1em; flex: none; fill: var(--flare); vertical-align: -0.12em; } +svg .flame-mark { fill: var(--flare); } +/* A card folds to its head row; the fold is remembered per card in this browser. */ +button.fold { width: 22px; height: 22px; padding: 0; flex: none; display: inline-grid; place-items: center; + font-size: 0.7rem; color: var(--muted); background: none; border: 1px solid var(--line); border-radius: 6px; cursor: pointer; } +button.fold:hover { color: var(--fg); border-color: var(--accent); } +.card.collapsed { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; } +.collapsed .head { display: contents; } +.launch-facts { min-width: 0; overflow-wrap: anywhere; } +.launch-facts summary { cursor: pointer; } +.card.hot, .card.sel { outline: 1px solid var(--gc, var(--accent)); } +.head { display: flex; justify-content: space-between; gap: 10px; align-items: flex-start; flex-wrap: wrap; } +.head > div { min-width: 0; max-width: 100%; overflow-wrap: anywhere; } +.name { font-size: 1.1rem; font-weight: 650; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.name .run { font-family: var(--mono); } +.sub, .since, .muted { color: var(--muted); } +.sub { font-size: 0.82rem; } +.state { display: grid; justify-items: end; gap: 3px; } +.since { font-size: 0.78rem; } +.pill { display: inline-flex; align-items: center; gap: 6px; font-size: 0.75rem; font-weight: 650; + padding: 2px 9px; border-radius: 999px; max-width: 100%; overflow-wrap: anywhere; color: var(--idle); background: var(--idle-bg); } +.pill::before { content: ""; width: 7px; height: 7px; flex: none; border-radius: 50%; background: currentColor; } +.p-serving { color: var(--ok); background: var(--ok-bg); } +.p-not_ready { color: var(--warn); background: var(--warn-bg); } +.p-offline { color: var(--bad); background: var(--bad-bg); } +.tag { display: inline-flex; align-items: center; font: 600 0.7rem system-ui, sans-serif; padding: 1px 7px; + border-radius: 6px; border: 1px solid var(--line2); color: var(--muted); max-width: 100%; overflow-wrap: anywhere; letter-spacing: 0.02em; } +.tag.arc { color: var(--gc, var(--fg)); border-color: color-mix(in srgb, var(--gc, var(--fg)) 45%, transparent); } +.tag.warn { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 40%, transparent); } +.model { font-family: var(--mono); font-size: 0.92rem; font-weight: 600; overflow-wrap: anywhere; } +.endpoint { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font-size: 0.82rem; margin-top: -6px; } +.endpoint code { background: var(--code); border: 1px solid var(--line); padding: 2px 6px; border-radius: 5px; overflow-wrap: anywhere; } +.endpoint a { color: var(--accent); font-weight: 500; text-decoration: none; } +.endpoint a:hover { text-decoration: underline; } +button.copy { font: 500 0.75rem system-ui, sans-serif; color: var(--accent); background: none; + border: 1px solid var(--line2); border-radius: 5px; padding: 1px 8px; cursor: pointer; } +button.copy:hover { border-color: var(--accent); } +button.copy:disabled { opacity: 0.45; cursor: default; } +.tiles { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 1px; background: var(--line); + border: 1px solid var(--line); border-radius: 9px; overflow: hidden; } +@media (max-width: 460px) { .tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +.tile { background: var(--panel2); padding: 9px 11px; min-width: 0; } +.tile .k { font-size: 0.68rem; text-transform: uppercase; letter-spacing: 0.07em; color: var(--muted); } +.tile .v { font-size: 1.5rem; font-weight: 650; font-variant-numeric: tabular-nums; line-height: 1.2; letter-spacing: -0.01em; } +.tile .v small { font-size: 0.75rem; font-weight: 500; color: var(--muted); margin-left: 3px; letter-spacing: 0; } +.tile .s { font-size: 0.75rem; color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; + overflow: hidden; text-overflow: ellipsis; } +.charts { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; } +.chart .k { display: flex; justify-content: space-between; font-size: 0.72rem; color: var(--muted); gap: 6px; } +.chart svg { display: block; width: 100%; height: 44px; background: var(--code); border: 1px solid var(--line); + border-radius: 6px; margin-top: 3px; } +.chart svg path { stroke-width: 1.6; fill: none; } +.chart .c1 path, .chart .c2 path { stroke: var(--gc, var(--g1)); } +.nochart { height: 44px; display: grid; place-items: center; font-size: 0.75rem; color: var(--muted); + background: var(--code); border: 1px solid var(--line); border-radius: 6px; margin-top: 3px; } +.sparks { display: flex; flex-wrap: wrap; gap: 6px; } +.chip { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--line2); border-radius: 6px; + padding: 3px 8px; font-size: 0.78rem; min-width: 0; max-width: 100%; flex-wrap: wrap; overflow-wrap: anywhere; background: var(--panel2); } +.chip .pos { font: 700 0.72rem var(--mono); color: var(--gc, var(--muted)); } +.chip .dot { width: 7px; height: 7px; } +.chip.up .dot { background: var(--ok); } +.chip.down { border-color: var(--bad); color: var(--bad); } +.chip.down .dot { background: var(--bad); } +.chip .detail { color: var(--muted); font-variant-numeric: tabular-nums; } +dl { margin: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 6px 14px; font-size: 0.8rem; } +dl div { min-width: 0; } +dt { color: var(--muted); font-size: 0.68rem; text-transform: uppercase; letter-spacing: 0.06em; } +dd { margin: 0; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; } +.totals { font-size: 0.8rem; color: var(--muted); border-top: 1px solid var(--line); padding-top: 10px; } +.totals b { color: var(--fg); font-weight: 600; } +.down-note { font-size: 0.85rem; color: var(--muted); margin: 0; } +.logs { border: 1px solid var(--line); border-radius: 9px; background: var(--panel2); min-width: 0; } +.logs summary { cursor: pointer; padding: 8px 12px; font-size: 0.82rem; font-weight: 600; user-select: none; + display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; } +.logs summary .muted { font-weight: 400; font-size: 0.75rem; } +.logs summary .bad { color: var(--bad); font-weight: 500; font-size: 0.75rem; } +.logs[open] summary { border-bottom: 1px solid var(--line); } +.logcmds { display: grid; gap: 8px; padding: 10px 12px; } +.logcmds .endpoint { margin-top: 0; } +section h2 { font-size: 0.75rem; font-weight: 650; text-transform: uppercase; letter-spacing: 0.08em; + color: var(--muted); margin: 0 0 8px; } +.events ul { list-style: none; margin: 0; padding: 0; background: var(--panel); border: 1px solid var(--line); + border-radius: 10px; } +.events li { display: grid; grid-template-columns: 7.5em minmax(0, 1fr); gap: 10px; padding: 8px 14px; + border-top: 1px solid var(--line); font-size: 0.85rem; align-items: baseline; } +.events li:first-child { border-top: 0; } +.events time { color: var(--muted); font-variant-numeric: tabular-nums; font-size: 0.8rem; } +.events .ev { display: flex; gap: 8px; align-items: baseline; min-width: 0; overflow-wrap: anywhere; } +.events .ev .dot { width: 7px; height: 7px; position: relative; top: -1px; } +.events .k-serving .dot { background: var(--ok); } +.events .k-not_ready .dot { background: var(--warn); } +.events .k-offline .dot { background: var(--bad); } +.events .empty { color: var(--muted); display: block; grid-column: 1 / -1; } +footer { color: var(--muted); font-size: 0.78rem; overflow-wrap: anywhere; } +.manage { padding: 16px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); } +.manage label { display: inline-flex; flex-direction: column; margin: 5px; gap: 4px; } +.manage input, .manage select { background: var(--code); color: var(--fg); padding: 7px; border: 1px solid var(--line2); } +.manage pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 420px; overflow: auto; } +.actions { display: flex; flex-wrap: wrap; gap: 6px; } +/* The page follows the system theme until the viewer picks one with the theme button. */ +@media (prefers-color-scheme: light) { + :root:not([data-theme="dark"]) { color-scheme: light; --bg: #eef1f2; --surface: #f8fafa; --ink: #142028; + --muted: #55636c; --line: #cfd7db; --g1: #0b7f8a; --g2: #2f8a4a; + --g3: #6b5bb5; --g4: #3a64b5; --relay: #b5711b; + --ok: #2f8a4a; --warn: #b5711b; --bad: #ad2530; --flare: #d9471a; } +} +:root[data-theme="light"] { color-scheme: light; --bg: #eef1f2; --surface: #f8fafa; --ink: #142028; + --muted: #55636c; --line: #cfd7db; --g1: #0b7f8a; --g2: #2f8a4a; + --g3: #6b5bb5; --g4: #3a64b5; --relay: #b5711b; + --ok: #2f8a4a; --warn: #b5711b; --bad: #ad2530; --flare: #d9471a; } +.theme { display: inline-grid; place-items: center; width: 32px; height: 32px; padding: 0; color: var(--muted); + background: none; border: 1px solid var(--line); border-radius: 50%; cursor: pointer; flex: none; } +.theme:hover { color: var(--fg); } +.theme:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.tiles .s { white-space: normal; overflow-wrap: anywhere; } +.chart { min-width: 0; position: relative; } +.chart button, .graph-controls button { color: var(--fg); background: var(--code); border: 1px solid var(--line2); + border-radius: 5px; padding: 8px; min-height: 44px; cursor: pointer; } +.chart svg { touch-action: pan-y; } +.chart output { display: block; min-height: 2.8em; font-size: .75rem; color: var(--fg); overflow-wrap: anywhere; } +.chart :focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } +#graph-dialog { width: min(1000px, 94vw); max-height: 90vh; overflow: auto; + color: var(--fg); background: var(--panel); border: 1px solid var(--line2); border-radius: 10px; } +#graph-dialog::backdrop { background: #0009; } +#graph-dialog svg { height: 300px; } +#graph-dialog .y-axis { height: 300px; } +#graph-dialog input { width: 100%; min-height: 44px; } +#graph-dialog button { min-height: 44px; } + +/* Numeric slots keep their geometry as samples arrive. */ +.card .tile { height: 64px; padding: 6px 10px; } +.card .tile .v { height: 30px; font-size: 1.3rem; white-space: nowrap; } +.card .tile .k { height: 20px; white-space: nowrap; } +.card .tile .k span { letter-spacing: 0; text-transform: none; } +.chart svg { height: 56px; } +.sparkline { position: relative; display: block; padding: 0; border: 0; background: none; + color: var(--fg); text-align: left; font: inherit; cursor: pointer; } +.sparkline:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } +.sparkline .axis { display: none; } +.sparkline .plot-frame { display: block; } +.sparkline output { position: absolute; top: 100%; left: 0; width: max-content; max-width: 100%; + height: auto; min-height: 0; padding: 4px; background: var(--panel); border: 1px solid var(--line); + font-size: .75rem; z-index: 2; pointer-events: none; visibility: hidden; } +.sparkline:hover output:not(:empty) { visibility: visible; } +.empty-plot { position: absolute; inset: 30px 0 auto; text-align: center; font-size: .72rem; color: var(--muted); } +.chart.empty .axis { visibility: hidden; } +.card .head { align-items: center; justify-content: flex-start; gap: 6px 12px; } +.card .name { font-size: .9rem; } +.card .model { font-size: .82rem; } +.card .state { display: flex; flex-wrap: wrap; align-items: center; min-width: 0; gap: 6px; } +.card .endpoint { margin: 0; min-width: 0; } +.card .thinking, .secondary, .source { font-size: .75rem; } +.card-details { min-width: 0; font-size: .8rem; } +.card-details > summary { cursor: pointer; color: var(--muted); width: fit-content; } +.card-details > .detail-body { display: grid; gap: 10px; padding-top: 10px; } +.card-details p { margin: 0; overflow-wrap: anywhere; } +.recovery-chip { font-size: .7rem; font-weight: 500; } +.card.inactive { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; } +.inactive .head { display: contents; } +.inactive .card-details { margin-left: auto; } +.inactive:has(.card-details[open]) .card-details { flex-basis: 100%; margin-left: 0; } +.start-command { font-size: .75rem; } +@media (max-width: 460px) { + .card .tile { padding: 6px 8px; height: 78px; } + .card .tile .k { height: 32px; white-space: normal; line-height: 15px; } + .card .tile .k span { display: block; } + .card .head { gap: 6px; } + .inactive .card-details { flex-basis: 100%; margin-left: 0; } +} +.graph-controls { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; min-width: 0; } +.graph-controls select, #graph-window { min-height: 44px; background: var(--code); color: var(--fg); } +.graph-controls .seg { display: inline-flex; gap: 2px; padding: 2px; border: 1px solid var(--line); border-radius: 999px; } +.graph-controls .seg button { min-height: 28px; min-width: 0; padding: 0 10px; border: 0; border-radius: 999px; + background: transparent; color: var(--muted); font: 500 .75rem/1 var(--mono); } +.graph-controls .seg button[aria-pressed="true"] { background: var(--line); color: var(--fg); } +.graph-controls .pause { min-height: 28px; min-width: 28px; padding: 0 10px; border-radius: 999px; font: 500 .75rem/1 var(--mono); } +.pause-age { min-width: 14ch; font: .75rem/1 var(--mono); color: var(--muted); font-variant-numeric: tabular-nums; } +.axis { display: flex; justify-content: space-between; height: 20px; font-size: .7rem; color: var(--muted); } +.plot-frame { display: grid; grid-template-columns: 6ch minmax(0, 1fr); gap: 4px; } +.y-axis { height: 80px; margin-top: 3px; flex-direction: column-reverse; align-items: flex-end; } +.x-axis { margin-left: calc(6ch + 4px); } +.state { min-width: 16ch; } +.legend .right { width: 13ch; } +.legend .rate { white-space: nowrap; } +.totals { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 4px 8px; } +.totals > span { height: 3.5em; overflow: auto; font-variant-numeric: tabular-nums; } +.p-installing, .p-starting, .p-loading, .p-compiling, .p-tuning, .p-graphs { color: var(--warn); } +.p-failed, .startup-error { color: var(--bad); } +.lstartup { fill: var(--warn); font-family: var(--mono); text-anchor: middle; } +.lstartup.failed { fill: var(--bad); } +.startup-detail { display: flex; flex-wrap: wrap; gap: 4px 14px; font-size: 11px; color: var(--muted); } +.startup-detail:empty { display: none; } +.startup-error { flex-basis: 100%; overflow-wrap: anywhere; } +.spark-details { position: fixed; z-index: 20; width: 320px; max-width: calc(100vw - 16px); + max-height: calc(100dvh - 16px); overflow: auto; padding: 12px; border: 1px solid var(--line); + border-top: 2px solid var(--gc, var(--line)); border-radius: 8px; background: var(--surface); + color: var(--ink); font-size: 12px; overflow-wrap: anywhere; } +.spark-details h3 { margin: 0 0 8px; font: 600 13px var(--mono); } +.spark-details dl { display: grid; grid-template-columns: 76px minmax(0, 1fr); gap: 4px 8px; margin: 0; } +.spark-details dt { color: var(--muted); text-transform: none; letter-spacing: normal; } +.spark-details dd { margin: 0; font-family: var(--mono); font-weight: 400; white-space: pre-wrap; } +svg .node:focus-visible { outline: none; } +svg .node:focus-visible rect { stroke: var(--g1); stroke-width: 3; } diff --git a/runtime/host/dashboard_assets/ring.js b/runtime/host/dashboard_assets/ring.js new file mode 100644 index 00000000..b2e220fa --- /dev/null +++ b/runtime/host/dashboard_assets/ring.js @@ -0,0 +1,479 @@ +// -- ring view ----------------------------------------------------------------------------- +// The service reports every ring in `rings` (one ring of eight, one or two rings of four, ...); +// a group's `ring` names the ring its arc lies on, and arc positions use that ring's numbering. +const ringsOf = (d) => d.rings || (d.ring ? [d.ring] : []); +const onRing = (ring, members) => members.filter((m) => (m.ring ?? ring.id) === ring.id); +// The ring a group or run is on, as a small tag, when more than one ring is drawn. +const ringTag = (ring, rings) => rings.length > 1 && ring ? `${esc(ring.short || ring.id)}` : ""; + +// Groups drawn on one ring: its discovered serving endpoints, then its container runs without +// an API (a serving run still starting, or a SIRCL collective job). +function ringGroups(ring, members) { + const groups = []; + for (const m of onRing(ring, members)) { + if (!m.arc) continue; + groups.push({ id: m.id, kind: "member", m, ring, positions: m.arc.positions, first: m.arc.first, size: m.arc.size, + color: memberColor(m), outline: !!(m.unmanaged || m.gpu_job), state: m.state, inferred: m.arc.inferred }); + } + for (const r of ring.runs || []) { + const job = r.kind === "job"; + groups.push({ id: "run:" + ring.id + ":" + r.run, kind: job ? "job" : "starting", r, ring, positions: r.positions, + first: r.first, size: r.positions.length, color: job ? JOB_COLOR : gcolor(r.color), outline: job, state: r.state }); + } + return groups; +} + +function ringCaption(ring) { + const f = ring.fabric || {}; + const tip = ring.source === "fabric" + ? `Fabric document ${f.cluster || ""} (${f.shape || "?"}), read from ${(f.read_from || []).join(", ")}${f.id ? "\n" + f.id : ""}` + : "The configured Sparks in their listed cable order"; + const kind = ring.source === "fabric" ? (ring.closed === false ? ` · ${esc(f.shape || "open")}` : "") : " · configured order"; + return `
    ${esc(ring.name)} · ${sparkCount(ring.size)}${kind}
    `; +} + +// Mark cable segments used by a shortest route with an intermediate Spark. +// These are topology-derived routes, not a measurement of traffic. +function relaySegments(ring, groups) { + const segments = new Set(), N = ring.size; + for (const g of groups.filter(g => !g.outline && g.state === "serving")) { + for (const a of g.positions) for (const b of g.positions.filter(b => b > a)) { + const direct = b - a, wrap = N - direct; + if (direct > 1 && (ring.closed === false || direct <= wrap)) + for (let p = a; p < b; p++) segments.add(p); + if (ring.closed !== false && wrap > 1 && wrap <= direct) + for (let p = b; p !== a; p = (p + 1) % N) segments.add(p); + } + } + return segments; +} +function ringOwners(groups) { + const owner = {}; + // Running groups own the visible nodes when stopped records share their positions. + for (const g of [...groups].sort((a, b) => (Number(b.state === "serving") * 2 + Number(groupActive(b))) + - (Number(a.state === "serving") * 2 + Number(groupActive(a))))) + for (const p of g.positions) if (!(p in owner)) owner[p] = g; + return owner; +} +const groupActive = g => !!g && ["serving", "busy", "not_ready", "installing", "starting", "loading", "compiling", "tuning", "graphs"].includes(g.state); +const groupStyle = g => [g?.outline ? "outline" : "", g && !groupActive(g) ? "dim" : ""].filter(Boolean).join(" "); + +// Host availability includes the local controller; allocation records alone do not mean busy. +function ringCounts(rings, members) { + let up = 0, busy = 0, down = 0, size = 0; + for (const ring of rings) { + const owner = ringOwners(ringGroups(ring, members)); + for (let p = 0; p < ring.size; p++) { + const active = groupActive(owner[p]), observed = ring.positions[p]?.up; + size++; + if (active) busy++; + if (active || observed === true) up++; + else if (observed === false) down++; + } + } + return {size, up, busy, idle: up - busy, down, unknown: size - up - down}; +} + +function startupLabel(s) { + const p = s?.startup; + return p ? (p.label || s.state_label || "Starting") + (has(p.done) && has(p.total) ? (p.unit === "%" ? ` ${Math.round(p.done)}%` : ` ${Math.round(p.done)}/${Math.round(p.total)}`) : "") : s?.state_label || ""; +} +function ringStartupLabel(s) { + if (!s?.startup) return ""; + const labels = {loading: "Weights", graphs: "CUDA graphs", installing: "Installing", tuning: "Tuning"}; + return startupLabel({...s, startup: {...s.startup, label: labels[s.startup.phase] || s.startup.label}}); +} +function startupDetails(s) { + if (!s.startup) return ""; + const p = s.startup; + const differing = (p.ranks || []).filter(r => r.phase !== p.phase || r.done !== p.done || r.total !== p.total || r.error); + return `
    ${differing.map(r => `Spark ${esc(r.position)} · ${esc(startupLabel({startup:r}))}`).join("")} + ${p.unobserved?.length ? `${p.unobserved.length === 1 ? "Spark" : "Sparks"} ${esc(span(p.unobserved))} · Unobserved` : ""} + ${p.error ? `${esc(p.error)}` : ""}
    `; +} + +const ringLabelMeasure = document.createElement("canvas").getContext("2d"); +function ringLabels(groups, N, cx, cy) { + // An inactive group whose Sparks all belong to an active one (a stopped install record under a running + // deployment or a listed endpoint) keeps its legend row and card but gets no label on the figure. + const owner = ringOwners(groups); + groups = groups.filter(g => groupActive(g) || g.positions.some(p => owner[p] === g)); + const placed = [], compact = groups.length > 4; + for (const g of groups) { + const full = g.size === N, step = 2 * Math.PI / N; + const angle = -Math.PI / 2 + (g.first + (g.size - 1) / 2) * step; + const radius = groups.length > 2 ? 78 : 66; + let x = full ? cx : cx + radius * Math.cos(angle); + const baseY = N === 2 ? 233 : full ? cy : cy + radius * Math.sin(angle); + const name = g.m ? (g.m.gpu_job ? "GPU in use" : g.m.model_short || g.m.model || g.m.name) : g.r.label; + const size = groups.length > 1 ? 10 : 12, label = clip(name, groups.length > 2 ? 16 : groups.length > 1 ? 22 : 28); + ringLabelMeasure.font = `650 ${size}px system-ui, sans-serif`; + const width = Math.max(ringLabelMeasure.measureText(label).width, g.size === 1 ? 64 : 86); + // Keep the whole label inside the polygon's inner edge so it never sits on a cable or relay marker. + if (!full && N > 2) { + const inner = 140 * Math.cos(Math.PI / N) - 18, room = Math.max(0, inner - width / 2); + x = Math.min(cx + room, Math.max(cx - room, x)); + } + let y = baseY; + // Try small vertical nudges, retaining the group's sector and inner radius. + for (let n = 0; n <= 20; n++) { + const candidate = baseY + (n % 2 ? -1 : 1) * Math.ceil(n / 2) * 6; + const direction = Math.atan2(candidate - cy, x - cx) + Math.PI / 2; + const offset = (direction - (g.first - .5) * step + 4 * Math.PI) % (2 * Math.PI); + if (!full && N > 2 && (offset > g.size * step || Math.hypot(x - cx, candidate - cy) > 110)) continue; + if (N > 2 && Array.from({length: N}, (_, p) => -Math.PI / 2 + p * step).some(a => + Math.abs(x - cx - 140 * Math.cos(a)) < width / 2 + 22 && Math.abs(candidate - cy - 140 * Math.sin(a)) < (compact ? 34 : 37))) continue; + if (placed.some(p => Math.abs(x - p.x) < (width + p.width) / 2 + 1 && Math.abs(candidate - p.y) < (compact ? 42 : 50))) continue; + y = candidate; + break; + } + placed.push({g, x, y, width, label, size}); + } + return placed; +} +// Sum the card snapshots once per serving group, never once per Spark/rank. +function servingTotals(members) { + const serving = [...new Map(members.map(m => [m.id, m])).values()].filter(m => m.state === "serving"); + const sum = key => serving.reduce((total, m) => total + (m.live?.[key] || 0), 0); + return {serving, tps: sum("output_tps"), tps5: sum("output_tps_5m"), running: sum("running"), waiting: sum("waiting")}; +} +// Mean output rate per running request across the serving groups; null when nothing runs. +function perRequest(tps, running) { + return running >= 1 ? tps / running : null; +} +function ringTotalsLayout(ring, members, labels) { + const t = servingTotals(onRing(ring, members)); + const each = perRequest(t.tps, t.running); + const output = `${rate(t.tps)} tok/s`, requests = `${int(t.running)} running · ${int(t.waiting)} queued${each === null ? "" : ` · ${rate(each)} each`}`; + const mono = getComputedStyle(document.documentElement).getPropertyValue("--mono"); + ringLabelMeasure.font = `600 12px ${mono}`; + const outputWidth = ringLabelMeasure.measureText(output).width; + ringLabelMeasure.font = `10px ${mono}`; + const width = Math.max(outputWidth, ringLabelMeasure.measureText(requests).width) + 16, height = 44; + // The inscribed circle keeps the block clear of every cable and node. Label + // boxes use the same centres as ringLabels, including its collision nudges. + const room = 140 * Math.cos(Math.PI / ring.size) - 18; + const center = ring.size > 2 && Math.hypot(width / 2, height / 2) < room && !labels.some(p => { + const g = p.g, compact = labels.length > 4; + ringLabelMeasure.font = `9px ${mono}`; + const subtitle = `${g.m?.layout?.tp ? 'TP' + g.m.layout.tp : 'Unmanaged'} · Sparks ${span(g.positions)}`; + const detailWidth = Math.max(ringLabelMeasure.measureText(subtitle).width, + ringLabelMeasure.measureText(ringStartupLabel(g.m)).width); + ringLabelMeasure.font = `650 ${compact ? 14 : 18}px ${mono}`; + const rateWidth = ringLabelMeasure.measureText(`${g.state === 'serving' ? rate(g.m?.live?.output_tps) : '–'} tok/s`).width; + const labelWidth = Math.max(p.width, detailWidth, rateWidth); + return Math.abs(p.x - 200) < (width + labelWidth) / 2 + 6 && Math.abs(p.y - 190) < height / 2 + 30; + }); + return {output, requests, width, height, center}; +} +function ringSvg(ring, members, now, labels, totals) { + const N = ring.size, cx = 200, cy = 190, R = 140; + const ang = p => -Math.PI / 2 + p * 2 * Math.PI / N; + const pt = p => N === 2 ? [100 + p * 200, 130] : [cx + R * Math.cos(ang(p)), cy + R * Math.sin(ang(p))]; + const groups = ringGroups(ring, members), owner = ringOwners(groups), relays = relaySegments(ring, groups); + let s = ``; + for (let p = 0; p < N; p++) { + if (N < 2 || (N !== 2 && p === N - 1 && ring.closed === false)) continue; + const q = (p + 1) % N, g = owner[p], same = g && owner[q] === g; + const [x1, y1] = pt(p), [x2, y2] = pt(q), offset = N === 2 ? (p ? 5 : -5) : 0; + const d = `M${x1},${y1 + offset} L${x2},${y2 + offset}`; + if (same) s += ``; + s += ``; + if (same && g.state === "serving") { + // One dot each way: a pair's two cables carry one direction each; a ring cable carries both. + const dots = N === 2 ? [p ? "traffic rev" : "traffic"] : ["traffic", "traffic rev"]; + for (const [i, cls] of dots.entries()) s += `Serving cable · activity indicator`; + } + if (relays.has(p)) { + const x = (x1 + x2) / 2, y = (y1 + y2) / 2; + s += `Relayed route through a Spark · from cable topology`; + } + } + for (const position of labels) { + const {g, x, size} = position, compact = groups.length > 4, y = position.y - (compact ? 11 : 13); + const tp = g.m?.gpu_job ? "" : isFlare(g.m) ? "Flare" : g.outline ? (g.m?.layout?.tp ? "TP" + g.m.layout.tp : "Unmanaged") : "TP" + (g.m?.layout?.tp || g.size); + ringLabelMeasure.font = `650 ${size}px system-ui, sans-serif`; + const flame = isFlare(g.m) ? `` : ""; + const phase = ringStartupLabel(g.m); + const phaseSize = 9; + const label = `${flame}${esc(position.label)}` + + `${tp ? esc(tp) + " · " : ""}${g.size === 1 ? "Spark" : "Sparks"} ${esc(span(g.positions))}` + + (phase ? `${esc(phase)}` + : `${g.state === "serving" ? rate(g.m?.live?.output_tps) : "–"} tok/s`) + ``; + s += `${esc(groupTitle(g))}${label}`; + } + if (totals.center) s += ` + + ${esc(totals.output)} + ${esc(totals.requests)}`; + for (let p = 0; p < N; p++) { + const sp = ring.positions[p] || {}, g = owner[p], [x, y] = pt(p); + const dx = N === 2 ? (p ? 1 : -1) : Math.cos(ang(p)), dy = N === 2 ? 0 : Math.sin(ang(p)); + const side = Math.abs(dy) < .25; + const hx = x + dx * (side ? 26 : 34), hy = y + dy * 26; + const cls = ["node", g ? (groupActive(g) ? "busy" : "inactive") + " k-" + g.kind : "idle", g?.state === "serving" ? "serving" : "", groupStyle(g), sp.up === false ? "down" : "", has(sp.up) ? "" : "unknown"].filter(Boolean).join(" "); + s += `` + + `` + + `` + + `${p}` + + `${esc(clip(sp.short || sp.name, side ? 5 : 10))}` + + (sp.up === false ? `DOWN` : "") + ``; + } + return s + ""; +} +function allocationHtml(ring, members, totals) { + const groups = ringGroups(ring, members), owner = ringOwners(groups); + const slots = Array.from({length: ring.size}, (_, p) => { + const g = owner[p]; + return `${p}`; + }).join(""); + const serving = groups.filter(g => g.state === "serving" && !g.outline), sizes = [...new Set(serving.map(g => g.size))]; + const count = sizes.length === 1 ? `${serving.length} × TP${sizes[0]}` : serving.map(g => `TP${g.size}`).join(" + "); + return `
    SPARK ALLOCATION${slots}
    ` + + (totals.center ? "" : `
    ${esc(totals.output)} · ${esc(totals.requests)}
    `) + + `
    ${esc(count || "No managed group serving")} · ${ring.size === 2 ? "A pair" : "A ring of " + ring.size}
    `; +} + +function groupTitle(g) { + const where = `${g.ring ? g.ring.name + " " : ""}${positionText(g.positions)}`; + if (g.kind === "member") { + const m = g.m, a = m.arc || {}; + return `${m.name} — ${where} · ${m.gpu_job ? "GPU in use · " + gpuSummary(m) : m.model || "no model"}\n` + + `${a.inferred ? "inferred from " : "from "}${a.source_label || "?"}${a.detail ? " (" + a.detail + ")" : ""}`; + } + return `${g.r.label} — ${where} · ${g.kind === "job" ? "collective job without an API" : "containers up, API not answering yet"}` + + "\n" + (g.r.containers || []).join(", "); +} + +// Totals across every ring; with more than one ring each serving size names its ring. +function stripHtml(rings, members) { + const {serving, tps, tps5, running, waiting} = servingTotals(members); + const {size, up, busy, idle, down, unknown} = ringCounts(rings, members); + let kv = null, kvName = ""; + for (const m of serving) if (m.live && has(m.live.kv) && (kv === null || m.live.kv > kv)) { kv = m.live.kv; kvName = m.name; } + const short = Object.fromEntries(rings.map((r) => [r.id, r.short || r.id])); + const sizes = serving.map((m) => (m.unmanaged || m.external ? m.layout.label : "TP" + ((m.arc && m.arc.size) || "?")) + (rings.length > 1 && short[m.ring] ? " " + short[m.ring] : "")).join(" · "); + const tile = (k, v, unit, sub) => `
    ${k}
    ${v}${unit ? `${unit}` : ""}
    ${sub}
    `; + return tile("Serving", serving.length, serving.length === 1 ? "group" : "groups", esc(sizes || "nothing serving")) + + tile("Output", rate(tps), "tok/s", "5 min avg " + rate(tps5)) + + tile("Requests", int(running), "running", int(waiting) + " waiting" + (perRequest(tps, running) === null ? "" : " · " + rate(perRequest(tps, running)) + " tok/s each")) + + tile("Sparks up", up, "/ " + size, `${busy} busy · ${idle} idle${down ? ` · ${down} down` : ""}${unknown ? ` · ${unknown} unobserved` : ""}`) + + tile("KV cache", pct(kv), "", kv === null ? "no serving group" : "highest · " + esc(kvName)); +} + +function legendHtml(rings, members) { + const groups = rings.flatMap((ring) => ringGroups(ring, members)); + if (!groups.length) return `
  • No model deployment is recorded for this fabric. sudo sparkring install records one; sudo sparkring dashboard export updates this page's site file.
  • `; + return groups.map((g) => { + const name = (p) => ((g.ring.positions[p] || {}).short) || p; + const ends = g.positions.length > 1 ? ` · ${name(g.positions[0])} → ${name(g.positions[g.positions.length - 1])}` : ` · ${name(g.positions[0])}`; + const where = ringTag(g.ring, rings); + let t1, t2, model, src, right; + if (g.kind === "member") { + const m = g.m, a = m.arc || {}, tr = m.transport && m.transport.label; + t1 = `${isFlare(m) ? FLAME : ""}${esc(m.name)}`; + t2 = `${where}${positionText(g.positions)}${esc(ends)}`; + model = `${esc(m.gpu_job ? "GPU in use" : m.model_short || m.model || "—")}`; + src = m.gpu_job ? esc(gpuSummary(m)) : m.external ? `${esc(m.layout.label)} · ${esc(m.host)}:${esc(m.port)}` + : `${m.unmanaged ? esc(m.layout.label) : 'TP' + a.size}${tr ? " · " + esc(tr) : ""}${a.inferred ? ' · positions guessed' : ""}`; + right = `${esc(m.startup ? startupLabel(m) : m.state_label || "")}` + + (m.state === "serving" ? `${rate((m.live || {}).output_tps)} tok/s` : ""); + } else { + t1 = `${esc(g.r.label)}`; + t2 = `${where}${positionText(g.positions)}${esc(ends)}`; + model = g.kind === "job" ? "SIRCL collective job" : "serving run"; + src = g.kind === "job" ? "no API · from container names" : "containers up · API not answering yet"; + right = `${g.kind === "job" ? "GPU in use" : "Starting"}`; + } + return `
  • ` + + `
    ${t1}
    ${t2}
    ` + + `
    ${model}
    ${src}
    ` + + `
    ${right}
  • `; + }).join(""); +} + +// Only problems are shown here: a fabric document or site file that cannot be used, a paused +// collector and this Spark's host-agent findings. +function ringNote(rings, topology) { + const bits = []; + if (topology && topology.detail) bits.push(`Records: ${esc(topology.detail)}`); + const c = data.collector || {}; + if (c.quiet) bits.push('Paused: sparkring dashboard quiet is on; no request is sent'); + const n = data.node || {}; + if (n.state && !["network-configured", "existing-network-verified"].includes(n.state)) + bits.push(`${esc(n.hostname || "This Spark")}: ${esc(n.state)}${n.error ? " · " + esc(n.error) : ""}${n.next_action ? " · next: " + esc(n.next_action) : ""}`); + for (const w of n.warnings || []) bits.push(esc(w)); + return bits.join(" · "); +} + +function renderRings(rings, members, now) { + const panel = $("ringpanel"); + if (!rings.length) { setHidden(panel, true); return; } + setHidden(panel, false); + panel.classList.toggle("multi", rings.length > 1); + const viz = $("ringviz"); + const columns = String(Math.min(rings.length, 2)); + if (viz.style.getPropertyValue("--rings") !== columns) viz.style.setProperty("--rings", columns); + const svg = rings.map(r => { + const labels = ringLabels(ringGroups(r, members), r.size, 200, 190), totals = ringTotalsLayout(r, members, labels); + return `
    ${ringCaption(r)}${ringSvg(r, members, now, labels, totals)}${allocationHtml(r, members, totals)}
    `; + }).join(""); + patch(viz, svg); + patch($("strip"), stripHtml(rings, members)); + patch($("legend"), legendHtml(rings, members)); + patch($("ringnote"), ringNote(rings, data.topology)); + const disc = rings[0].discovery || {}, total = rings.reduce((a, r) => a + (r.size || 0), 0); + const name = rings.length === 1 ? rings[0].name : "SparkRing"; + text($("ring-name"), name); + document.title = name; + text($("ringtitle"), rings.length === 1 ? `${name} · ${rings[0].closed === false ? "line" : "ring"} of ${rings[0].size}` : "Groups on the rings"); + patch($("ringmeta"), (rings.length > 1 ? `${rings.length} rings · ${sparkCount(total)}` : `${esc(rings[0].name)} · ${sparkCount(rings[0].size)}`) + + (disc.at ? ` · checked ${dur(now - disc.at)} ago` : "")); +} + +// One card reads the same status snapshot as the ring; interaction never fetches. +let sparkAnchor = null, sparkPinned = false, sparkLeave = null; +function sparkDetails(ring, position, member) { + const sp = ring.positions.find(p => p.position === position) || {}; + const startup = member?.spark_startup || member?.startup; + const rank = startup?.ranks?.find(r => r.position === position); + const worker = member?.nodes?.find(n => n.node === sp.name); + const container = member?.containers?.find(c => c.position === position); + const name = member?.sparks?.find(p => p.position === position)?.container || container?.name; + const cached = sp.containers?.find(c => c.name === name); + const rows = []; + const known = v => has(v) && v !== "" && String(v).toLowerCase() !== "unknown"; + const add = (label, value) => { if (known(value)) rows.push(`
    ${esc(label)}
    ${esc(value)}
    `); }; + add("Address", sp.address); + add("Position", position); + add("Group", member?.name); + add("Model", member?.model); + add("Rank", rank?.rank ?? worker?.rank ?? container?.node_rank); + const tp = member?.layout?.tp ?? member?.settings?.tensor_parallel_size; + const dcp = member?.layout?.dcp ?? member?.settings?.decode_context_parallel_size; + add("Parallel", [known(tp) ? `TP${Math.round(tp)}` : "", known(dcp) ? `DCP${Math.round(dcp)}` : ""].filter(Boolean).join(" / ")); + add("State", rank?.phase === "failed" ? startupLabel({startup: rank}) : member?.state === "serving" ? "Serving" + : rank ? startupLabel({startup: rank}) : null); + add("Container", (rank ? [rank.container_state, rank.health] : [cached?.state, cached?.health]).filter(known).join(" · ")); + if (rank?.phase === "failed") add("Error", rank.error?.trim().split(/\r?\n/).pop()); + const gpu = sp.gpu || {}; + if (Number.isFinite(gpu.memory_used_bytes) && Number.isFinite(gpu.memory_total_bytes)) + add("GPU memory", `${Math.round(gpu.memory_used_bytes / 1e9)} / ${Math.round(gpu.memory_total_bytes / 1e9)} GB`); + if (Number.isFinite(gpu.temperature_c)) add("GPU temp", `${Math.round(gpu.temperature_c)} °C`); + for (const id of ["0", "1"]) { + const port = sp.ports?.[id]; + if (!port) continue; + const peer = port.peer, bits = []; + if (has(port.cable)) bits.push(`Cable ${port.cable}${has(peer?.position) ? ` → Spark ${peer.position} port ${peer.port}` : ""}`); + else if (port.cable === null) bits.push("Uncabled"); + for (const nic of Object.values(port.functions || {})) { + const link = sp.links?.find(l => l.netdev === nic.netdev); + const state = [typeof link?.carrier === "boolean" ? `carrier ${link.carrier ? "up" : "down"}` : "", + known(link?.operstate) ? link.operstate : ""].filter(Boolean).join(" · "); + if (state) bits.push(`${nic.netdev}: ${state}`); + } + add(`Port ${id}`, bits.join("\n")); + } + // Cache age is independent of the viewer's faster API and startup samples. + const updated = [rank?.at || (rank && startup?.at), member?.live?.read_at].filter(Number.isFinite); + const at = updated.length ? Math.max(...updated) : data?.generated_at; + if (Number.isFinite(at)) add("Updated", new Date(at * 1000).toLocaleString()); + if (Number.isFinite(sp.observed_at)) add("Node cache", new Date(sp.observed_at * 1000).toLocaleString()); + return `

    ${esc(known(sp.name) ? sp.name : `Spark ${position}`)}

    ${rows.join("")}
    `; +} +function closeSpark() { + clearTimeout(sparkLeave); + sparkAnchor?.removeAttribute("aria-describedby"); + sparkAnchor = null; sparkPinned = false; + setHidden($("spark-details"), true); +} +function positionSpark() { + if (!sparkAnchor?.isConnected) { closeSpark(); return; } + const card = $("spark-details"), box = sparkAnchor.getBoundingClientRect(); + const viewport = window.visualViewport; + const left = viewport?.offsetLeft || 0, top = viewport?.offsetTop || 0; + const width = viewport?.width || innerWidth, height = viewport?.height || innerHeight; + const above = Math.max(0, Math.min(height - 16, box.top - top - 16)); + const below = Math.max(0, Math.min(height - 16, top + height - box.bottom - 16)); + card.style.maxWidth = `${width - 16}px`; + // Keep the trigger exposed so a second tap can close the card, even in landscape. + card.style.maxHeight = `${Math.max(above, below, 80)}px`; + const size = card.getBoundingClientRect(); + card.style.left = `${Math.max(left + 8, Math.min(box.right + 10, left + width - size.width - 8))}px`; + const y = box.bottom + 8 + size.height <= top + height - 8 ? box.bottom + 8 : box.top - size.height - 8; + card.style.top = `${Math.max(top + 8, Math.min(y, top + height - size.height - 8))}px`; +} +function refreshSpark() { + if (!sparkAnchor) return; + if (!sparkAnchor.isConnected) { closeSpark(); return; } + const ring = ringsOf(data).find(r => String(r.id) === sparkAnchor.closest("[data-ring]").dataset.ring); + if (!ring) { closeSpark(); return; } + const members = (data.groups || []).flatMap(g => g.members || []); + const member = members.find(m => m.id === sparkAnchor.dataset.member); + const card = $("spark-details"); + card.style.setProperty("--gc", member ? memberColor(member) : "var(--line)"); + patch(card, sparkDetails(ring, Number(sparkAnchor.dataset.position), member)); + attr(sparkAnchor, "aria-describedby", "spark-details"); + setHidden(card, false); positionSpark(); +} +function openSpark(node, pin = false) { + clearTimeout(sparkLeave); + if (sparkAnchor !== node) { sparkAnchor?.removeAttribute("aria-describedby"); sparkPinned = false; } + sparkAnchor = node; sparkPinned ||= pin; refreshSpark(); +} +function leaveSpark() { + clearTimeout(sparkLeave); + sparkLeave = setTimeout(() => { + if (!sparkPinned && document.activeElement !== sparkAnchor && !$("spark-details").matches(":hover")) closeSpark(); + }, 150); +} + +function initRingEvents() { + $("ringviz").addEventListener("pointerover", e => { + const node = e.target.closest(".node"); + if (node && e.pointerType !== "touch" && !node.contains(e.relatedTarget)) openSpark(node); + }); + $("ringviz").addEventListener("pointerout", e => { + const node = e.target.closest(".node"); + if (node && !node.contains(e.relatedTarget)) leaveSpark(); + }); + $("ringviz").addEventListener("focusin", e => { const node = e.target.closest(".node"); if (node) openSpark(node); }); + $("ringviz").addEventListener("focusout", leaveSpark); + $("spark-details").addEventListener("pointerenter", () => clearTimeout(sparkLeave)); + $("spark-details").addEventListener("pointerleave", leaveSpark); + $("ringviz").addEventListener("click", e => { + const node = e.target.closest(".node"); + if (node) { if (sparkAnchor === node && sparkPinned) closeSpark(); else openSpark(node, true); } + }); + $("ringviz").addEventListener("keydown", e => { + const node = e.target.closest(".node"); + if (node && ["Enter", " "].includes(e.key)) { e.preventDefault(); node.dispatchEvent(new MouseEvent("click", {bubbles: true})); } + }); + document.addEventListener("keydown", e => { if (e.key === "Escape") closeSpark(); }); + document.addEventListener("pointerdown", e => { + if (!e.target.closest("#spark-details, #ringviz .node")) closeSpark(); + }); + window.addEventListener("resize", () => { if (sparkAnchor) positionSpark(); }); + window.addEventListener("scroll", () => { if (sparkAnchor) positionSpark(); }, true); + window.visualViewport?.addEventListener("resize", () => { if (sparkAnchor) positionSpark(); }); +} + +function applyHighlight() { + for (const el of document.querySelectorAll("[data-member]")) { + const id = el.dataset.member; + el.classList.toggle("hot", !!id && id === hoverId); + el.classList.toggle("sel", !!id && id === selectedId); + } +} + +function selectGroup(id) { + selectedId = id && id !== selectedId ? id : null; + applyHighlight(); + if (!selectedId) return; + const card = [...document.querySelectorAll("article.card")].find((c) => c.dataset.member === selectedId); + if (!card) return; + const top = card.getBoundingClientRect().top; + if (top < 0 || top > innerHeight * 0.55) { + card.scrollIntoView({ behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth", block: "start" }); + } +} diff --git a/runtime/host/dashboard_server.py b/runtime/host/dashboard_server.py index 9134aa48..4e0b9843 100644 --- a/runtime/host/dashboard_server.py +++ b/runtime/host/dashboard_server.py @@ -28,13 +28,24 @@ from runtime.host.dashboard_sources import FABRIC_PATH, SITE_PATH, Source, _ip PAGE = Path(__file__).with_name("dashboard.html") +ASSETS_DIR = Path(__file__).with_name("dashboard_assets") +ASSET_PLACEHOLDERS = ( + ("/* DASHBOARD_CSS */", ASSETS_DIR / "dashboard.css"), + ("// VIEWER_RATES", Path(__file__).with_name("dashboard_rates.js")), + ("// DASHBOARD_RING_JS", ASSETS_DIR / "ring.js"), + ("// DASHBOARD_CHARTS_JS", ASSETS_DIR / "charts.js"), + ("// DASHBOARD_CARDS_JS", ASSETS_DIR / "cards.js"), + ("// DASHBOARD_APP_JS", ASSETS_DIR / "app.js"), +) DEFAULT_PORT = 8090 def page_bytes(path: Path = PAGE) -> tuple[bytes, str]: """The page and its Content-Security-Policy: its inline script and style admitted by hash only.""" text = Path(path).read_text(encoding="utf-8") - text = text.replace("// VIEWER_RATES", Path(__file__).with_name("dashboard_rates.js").read_text(encoding="utf-8")) + for marker, asset in ASSET_PLACEHOLDERS: + if marker in text: + text = text.replace(marker, asset.read_text(encoding="utf-8"), 1) policies = [] for tag, directive in (("script", "script-src"), ("style", "style-src")): match = re.search(rf"<{tag}>(.*?)", text, flags=re.S) diff --git a/runtime/host/test_dashboard_actions.py b/runtime/host/test_dashboard_actions.py index 38c24de0..66b4ed00 100644 --- a/runtime/host/test_dashboard_actions.py +++ b/runtime/host/test_dashboard_actions.py @@ -2,7 +2,6 @@ import http.client import json import os -from pathlib import Path import threading from types import SimpleNamespace @@ -109,7 +108,7 @@ def refuse(thread): assert len(api1.requests) == len(api2.requests) assert sorted(r.full_url for r in api1.requests) == sorted(r.full_url for r in api2.requests) assert calls == [] - script = Path(dashboard.PAGE).read_text(encoding="utf-8") + script = dashboard.page_bytes()[0].decode("utf-8") actions = script.split("let manageTicket", 1)[1].split("// Hovering", 1)[0] assert all(word not in actions for word in ("setInterval", "setTimeout", "WebSocket")) diff --git a/runtime/host/test_dashboard_modular.py b/runtime/host/test_dashboard_modular.py new file mode 100644 index 00000000..309f229e --- /dev/null +++ b/runtime/host/test_dashboard_modular.py @@ -0,0 +1,70 @@ +"""Regression tests for dashboard modularization, CPU-list decoupling, and asset assembly.""" +from __future__ import annotations + +import ast +import base64 +import hashlib +from pathlib import Path +import re + +from runtime.host import dashboard, dashboard_server, host_load +from scripts import build_deb + +HOST_DIR = Path(__file__).resolve().parent + + +def test_host_load_cpu_list_round_trip(): + assert host_load.parse_cpu_list("0-4,10-14") == [0, 1, 2, 3, 4, 10, 11, 12, 13, 14] + assert host_load.parse_cpu_list(" 7, 1-2, , 2 ") == [1, 2, 7] + assert host_load.format_cpu_list([14, 13, 12, 11, 10, 4, 3, 2, 1, 0]) == "0-4,10-14" + assert host_load.format_cpu_list([5]) == "5" + assert host_load.format_cpu_list([]) == "" + + +def test_dashboard_modules_have_no_sparkring_sircl_imports(): + for path in sorted(HOST_DIR.glob("dashboard*.py")): + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + assert "sparkring_sircl" not in alias.name, f"{path.name} imports {alias.name}" + assert not alias.name.startswith("spark_transport.sircl"), f"{path.name} imports {alias.name}" + elif isinstance(node, ast.ImportFrom) and node.module: + assert "sparkring_sircl" not in node.module, f"{path.name} imports from {node.module}" + assert not node.module.startswith("spark_transport.sircl"), f"{path.name} imports from {node.module}" + + +def test_page_bytes_assembles_all_assets_with_matching_csp_hashes(): + raw_shell = Path(dashboard.PAGE).read_text(encoding="utf-8") + for marker, asset in dashboard_server.ASSET_PLACEHOLDERS: + assert marker in raw_shell, f"missing marker {marker} in dashboard.html" + assert asset.is_file(), f"missing asset {asset}" + body, csp = dashboard.page_bytes() + text = body.decode("utf-8") + for marker, _ in dashboard_server.ASSET_PLACEHOLDERS: + assert marker not in text, f"unreplaced marker {marker} in assembled page" + for tag, directive in (("script", "script-src"), ("style", "style-src")): + match = re.search(rf"<{tag}>(.*?)", text, flags=re.S) + assert match is not None + expected = base64.b64encode(hashlib.sha256(match.group(1).encode()).digest()).decode() + assert f"{directive} 'sha256-{expected}'" in csp + + +def test_build_deb_runtime_manifest_includes_dashboard_modules_and_assets(): + expected_paths = [ + "runtime/host/dashboard.py", + "runtime/host/dashboard_client.py", + "runtime/host/dashboard_parsers.py", + "runtime/host/dashboard_sources.py", + "runtime/host/dashboard_collector.py", + "runtime/host/dashboard_quiet.py", + "runtime/host/dashboard_server.py", + "runtime/host/dashboard.html", + "runtime/host/dashboard_assets/dashboard.css", + "runtime/host/dashboard_assets/ring.js", + "runtime/host/dashboard_assets/charts.js", + "runtime/host/dashboard_assets/cards.js", + "runtime/host/dashboard_assets/app.js", + ] + for relative in expected_paths: + assert build_deb.is_runtime_manifest_path(relative), f"build_deb excludes {relative}"