diff --git a/docs/DASHBOARD.md b/docs/DASHBOARD.md index c7869e1ff..2f573598b 100644 --- a/docs/DASHBOARD.md +++ b/docs/DASHBOARD.md @@ -253,6 +253,13 @@ launcher folder in the store) fold in the order they were written, so a host clo stepped back (NTP) folds as before. A host clock that is off by more than the gap between two hosts' records still orders those records by that clock, and records of two hosts with the same `time_unix` fold in the order they are read (a known limit). +The spare-node events of a resident `ssh:` island (`island_node_lost`, +`island_waiting_spare`, `island_node_replaced`, `island_replacement_limit`) fold the +same way and share both limits: a host whose clock is behind by more than the gap +between two hosts' records can show a replaced island still waiting for a spare node, +and two hosts' events with the same `time_unix` fold in the order they are read. The +island's record in the run store (`fleet/trainers//state.json`) wins over the +events, so a page that reads the store shows the record's state either way. For tools that read the file itself: ``` @@ -262,6 +269,17 @@ python -m yeto.dashboard.fleet_store merge --store s3:///runs/ \ writes one `fleet.jsonl`, in time order, each record once. +A resident `ssh:` trainer island with spare nodes shows its wait for a spare node, +its lost node and why, and its replacements on its card, its tip and an extra +`Nodes` column of Islands now (a page without such an island has no new column). +It is out of the syncer roster while a spare takes a lost node's place (the roster +in the warning colour). Past `fleet.waiting_absent_after_s` (plan, default 1 h) it +reads `waiting for a spare node · counts as absent`. A wait past +`--spare-max-wait-s` (the record's, default 24 h), or one no record or event +reported for 1 h 12 min (the hourly wait report, two health periods and 10 min), is +not believed: the island reads lost, as one without spare nodes. Node checks stop on +purpose while the island recovers, so a check reads stale only while it runs. + ## Alert rules and thresholds | Rule | Default threshold | Level | diff --git a/tests/test_dashboard_island_health_relaunch.py b/tests/test_dashboard_island_health_relaunch.py new file mode 100644 index 000000000..d285fc472 --- /dev/null +++ b/tests/test_dashboard_island_health_relaunch.py @@ -0,0 +1,71 @@ +"""A resident ssh: island relaunched on the same nodes (own-cluster 4.5 review): its node checks kept over +the relaunch (``reset: true``, the old job's times) must not leave a healthy running island reading +"health unread (stale)" for good. The first check of the new job writes the record again +(``FleetController._health_key`` counts ``reset``), so the record's checks are the new job's.""" + +from __future__ import annotations + +import json + +from test_dashboard_island_spares import cards, reducer, smoke +from test_node_health_wiring import HealthCluster, _island, _tick, _wait +from test_rl_ssh_resident import NAMES, _controller +from test_rl_ssh_resident import _cards # noqa: F401 - autouse + +from yeto.dashboard import fleet_islands +from yeto.launch import island_lifecycle as lifecycle +from yeto.launch.fleet import FleetController +from yeto.rl.engine.object_store import DirectoryObjectStore + + +def test_a_relaunch_on_the_same_nodes_reads_healthy_once_it_runs(tmp_path): + cluster = HealthCluster(NAMES) + ops, clock, _ = _island(tmp_path, cluster) + wall = [2_000_000_000.0] + for w in ops.islands["isl"].health.values(): + w.clock = lambda: wall[0] + objects = DirectoryObjectStore(str(tmp_path / "store")) + store = lifecycle.IslandStateStore(objects, controller={"host": "t"}, clock=lambda: wall[0]) + recorder = lifecycle.FleetRecorder(store, {"isl": lifecycle.IslandRef(island=1, source="ssh")}) + ctl = _controller(ops, recorder=recorder) + rec = ctl.learners["isl"] + ctl._record(rec, reason="launched") + for _ in range(2): # two ok checks + wall[0] += 61 + assert _tick(ops, clock) == "RUNNING" + ctl._health_events(rec) + # rank 2's trainer exits 1 (not a health loss): the island fails, its checks stop + cluster.exit("b300-2", 0, 1) + assert _wait(lambda: ops.islands["isl"].job.procs[2].poll() is not None) + wall[0] += 61 + assert _tick(ops, clock) == "FAILED" + ctl._record(rec, lifecycle.RECOVERING, reason="rank 2 exited 1") + wall[0] += 240 # backoff, preflight and the container start on the same nodes + for w in ops.islands["isl"].health.values(): + w.clock = lambda: wall[0] + assert ops.relaunch(None, "isl") == 1 + ctl._record(rec, lifecycle.RUNNING, reason="relaunched") # the record keeps the old job's checks (reset) + kept = json.loads(objects.read(lifecycle.state_key(1)))["health"]["nodes"] + assert all(n.get("reset") for n in kept.values()) + for _ in range(60): # it runs: ok checks every minute, an hour long + wall[0] += 61 + clock.t += 61 + assert str(ops.job_status("isl", 1)) == "RUNNING" + ctl._health_events(rec) + doc = json.loads(objects.read(lifecycle.state_key(1))) + assert doc["state"] == "running" + assert not any(n.get("reset") for n in doc["health"]["nodes"].values()) # the new job's checks + assert all(n["verdict"] == "ok" for n in doc["health"]["nodes"].values()) + r = reducer() + assert r.load_fleet_state(fleet_islands.read_fleet_state(objects)) + c = cards(r)["1"] + assert c["island_now"]["state"] == "running" and "node_health" not in c + out = smoke(tmp_path / "page", r) + assert not any("stale" in t for t in out["texts"]) and "stale" not in out["nodes"] + + +def test_the_health_key_counts_a_kept_check(): + ok = {"verdict": "ok", "reasons": [], "at": 1.0} + key = FleetController._health_key + assert key({"nodes": {"a": ok}}) != key({"nodes": {"a": {**ok, "reset": True}}}) + assert key({"nodes": {"a": ok}}) == key({"nodes": {"a": {**ok, "at": 99.0}}}) # times alone: no rewrite diff --git a/tests/test_dashboard_island_spares.py b/tests/test_dashboard_island_spares.py new file mode 100644 index 000000000..a736f71fe --- /dev/null +++ b/tests/test_dashboard_island_spares.py @@ -0,0 +1,650 @@ +"""A resident ssh: trainer island with spare nodes on the dashboard (own-cluster 4.5): its nodes' +health reasons, its ``waiting_spare`` state, its replacements (count, last time) and the spare-node +events (``island_node_lost`` / ``island_waiting_spare`` / ``island_node_replaced`` / +``island_replacement_limit``) in the event stream. The island's record (``spares`` / ``health`` in +``fleet/trainers//state.json``) wins over its fleet.jsonl events; an island without spare nodes or +health checks (every customer run) carries no new field at all.""" + +from __future__ import annotations + +import json +import shutil +import subprocess +from pathlib import Path + +import pytest +from test_dashboard_diloco import SMOKE +from test_dashboard_fleet_islands import T0, fleet_reducer, plan_doc + +from yeto.dashboard import fleet_islands +from yeto.dashboard.export import export_html +from yeto.dashboard.reducer import Reducer +from yeto.dashboard.sources import load_all +from yeto.launch import island_spares as isp +from yeto.rl.engine.object_store import DirectoryObjectStore + +LEGEND = 'legend: mk("topoLg").innerHTML' +# the topology smoke, also printing the event stream, trainer 1's tip (a hover on its card) and the dashed boxes +# (each colour reads as its CSS variable's name: --warn, --bad, ...) +EV_SMOKE = "globalThis.getComputedStyle = () => ({ getPropertyValue: (n) => n });\n" + SMOKE.replace(LEGEND, LEGEND + ''', events: mk("evs").innerHTML, + tip: (function () { const h = Object.values(els).find((n) => n.listeners && n.listeners.mousemove); + if (!h) return null; h.listeners.mousemove[0]({ target: { closest: () => ({ getAttribute: () => "trn:1" }) }, + clientX: 0, clientY: 0 }); return mk("topoTip").innerHTML; })(), + dashed: svg.filter((n) => n.style && n.style.strokeDasharray === "5 4").length, + roster: (svg.find((n) => /^roster /.test(String(n.textContent || ""))) || { style: {} }).style.fill || null''') +assert EV_SMOKE != SMOKE +FX = Path(__file__).parent / "fixtures" / "dashboard" +NEW_KEYS = ("spares", "node_health") +WAIT = "fabric group rack-b has no free healthy spare node (gpu-e: lease held by run other)" +LOST = "rank 1 (gpu-d) node health bad in 2 checks in a row: GPU 3 XID 79" + + +def ev(kind: str, at: float, k: int = 1, **fields) -> dict: + return {"event": kind, "time_unix": at, "island": f"fleet-qa-l{k}-modal", "island_id": k, **fields} + + +def lost(at: float) -> dict: + return ev(isp.NODE_LOST, at, node="gpu-d", rank=1, incarnation=0, reason=LOST) + + +def waiting(at: float, elapsed: float = 0, **kw) -> dict: + return ev(isp.WAITING_SPARE, at, lost=["gpu-d"], reason=WAIT, group="rack-b", next_check_s=60, + elapsed_s=elapsed, **kw) + + +def replaced(at: float) -> dict: + return ev(isp.NODE_REPLACED, at, rank=1, lost="gpu-d", spare="gpu-e", incarnation=1, reason=LOST, + resume_step=6, group="rack-b") + + +def reducer(*extra: dict) -> Reducer: + r = fleet_reducer() + for rec in extra: + r.feed(rec) + return r + + +def cards(r: Reducer, now: float | None = None) -> dict: + return {c["id"]: c for c in r.overview(now=r.max_ts if now is None else now)["islands"]} + + +def spares_doc(**kw) -> dict: + return {"nodes": ["gpu-c", "gpu-d"], "spare_nodes": ["gpu-e"], "lost": [], "waiting_spare": False, + "wait_reason": None, "waiting_since": None, "replacements": 0, "replacements_window": 0, + "max_replacements": 3, "last_replaced_at": None, **kw} + + +def node(verdict: str, at: float, reasons=(), bad=0) -> dict: + return {"verdict": verdict, "ok": verdict == "ok", "reasons": list(reasons), "bad_in_row": bad, "at": at, + "every_s": 60.0, "multi": True} + + +def store_state(tmp_path: Path, life: str, **fields) -> dict: + """The fleet state of a run store whose island 1 record is ``life`` with ``fields``.""" + for k, doc in {0: {"state": "running"}, 1: {"state": life, "relaunches": 1, "incarnation": 1, **fields}}.items(): + p = tmp_path / "store" / f"fleet/trainers/{k}/state.json" + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(json.dumps({"since": T0, "handle": {"cluster": f"fleet-qa-l{k}-modal"}, **doc})) + return fleet_islands.read_fleet_state(DirectoryObjectStore(str(tmp_path / "store"))) + + +def smoke(tmp: Path, r: Reducer, width: int = 1200) -> dict: + exe = shutil.which("node") + if exe is None: + pytest.skip("node not installed") + tmp.mkdir(parents=True, exist_ok=True) + page = export_html(r, tmp / "p.html", generated_at=r.max_ts) + (tmp / "smoke.js").write_text(EV_SMOKE) + res = subprocess.run([exe, str(tmp / "smoke.js"), str(page), str(width)], capture_output=True, text=True, + timeout=60, check=False) + assert res.returncode == 0, res.stderr + return json.loads(res.stdout) + + +# -- the reducer --------------------------------------------------------------------------------- +def test_spare_and_health_events_are_no_lifecycle_state_nor_a_sign_of_life(): + end = reducer().max_ts + r = reducer(ev("node_health", end + 4000, node="gpu-d", rank=1, verdict="lost", reasons=["GPU 3 XID 79"]), + lost(end + 4001), waiting(end + 4002)) + assert r.islands["1"]["last_event_ts"] == reducer().islands["1"]["last_event_ts"] # not a sign of life + assert r.islands["1"]["fleet_state"] == reducer().islands["1"]["fleet_state"] # not a lifecycle state + plain = cards(reducer(), now=end + 4002)["1"]["status"] + assert plain in ("stale", "lost") and cards(r, now=end + 4002)["1"]["status"] == plain + marks = ("node_health", isp.NODE_LOST, isp.WAITING_SPARE) + assert all(e["stream"] == "fleet" for e in r.events if e["type"] in marks) + + +def test_the_events_mark_the_card_without_a_record(): + r = reducer(lost(T0 + 400), waiting(T0 + 460, elapsed=30)) + sp = cards(r)["1"]["spares"] + assert sp["waiting"] and sp["since"] == T0 + 430 and sp["reason"] == WAIT and sp["source"] == "events" + assert sp["lost"] == ["gpu-d"] and sp["replacements"] == 0 + r.feed(waiting(T0 + 520, elapsed=90)) # a later report keeps the wait's start + assert cards(r)["1"]["spares"]["since"] == T0 + 430 + r.feed(waiting(T0 + 560)) # a report without its elapsed time (it would start the wait at T0 + 560) + assert cards(r)["1"]["spares"]["since"] == T0 + 430 # the earliest start stays + r.feed(replaced(T0 + 600)) + sp = cards(r)["1"]["spares"] + assert not sp["waiting"] and sp["since"] is None and sp["replacements"] == 1 and sp["last_at"] == T0 + 600 + assert sp["last"]["lost"] == "gpu-d" and sp["last"]["spare"] == "gpu-e" and sp["lost"] == [] + assert "spares" not in cards(r)["0"] # the other island: no field + + +def limit(at: float) -> dict: + return ev(isp.REPLACEMENT_LIMIT, at, replaced=[], lost=["gpu-d"], reason="3 node replacement(s)") + + +@pytest.mark.parametrize("final", [limit(T0 + 700), waiting(T0 + 700, elapsed=86400, given_up=True)]) +def test_a_limit_or_a_given_up_wait_ends_the_wait(final): + sp = cards(reducer(lost(T0 + 400), waiting(T0 + 401), final))["1"]["spares"] + assert not sp["waiting"] and sp["stopped"] + + +# -- replay order: by time across sources, in write order within one source ---------------------------- +def _spares_of(rows) -> dict: + """The events-only ``spares`` mark of island 1 after feeding ``rows`` ([(source, record)]).""" + r = reducer() + for source, rec in rows: + assert r.feed(rec, source=source) + return cards(r)["1"]["spares"] + + +HOST_A = [("host-a", lost(T0 + 400)), ("host-a", waiting(T0 + 401, elapsed=1))] # the lost host's launcher +HOST_B = [("host-b", replaced(T0 + 900))] # the new host's launcher: a spare took gpu-d's place + + +@pytest.mark.parametrize("rows", [HOST_A + HOST_B, HOST_B + HOST_A, [HOST_A[0], HOST_B[0], HOST_A[1]]], + ids=["in-order", "new-host-first", "interleaved"]) +def test_a_lost_host_s_records_read_late_replay_in_place(rows): + sp = _spares_of(rows) + assert sp == _spares_of(HOST_A + HOST_B) + assert not sp["waiting"] and sp["since"] is None and sp["lost"] == [] and sp["replacements"] == 1 + assert sp["last"]["spare"] == "gpu-e" and sp["last_at"] == T0 + 900 + + +def test_one_source_keeps_its_write_order_over_an_older_time(): + """A launcher whose clock stepped back: its replacement line (written after the wait) has an + older time; within its own source the write order decides: the island is not waiting.""" + sp = _spares_of([("host-a", lost(T0 + 400)), ("host-a", waiting(T0 + 500)), ("host-a", replaced(T0 + 450))]) + assert not sp["waiting"] and sp["replacements"] == 1 and sp["last_at"] == T0 + 450 # the record's own time + # another source's later line still goes after it by time + sp = _spares_of([("host-a", lost(T0 + 400)), ("host-a", waiting(T0 + 500)), ("host-a", replaced(T0 + 450)), + ("host-b", waiting(T0 + 480))]) + assert sp["waiting"] is False # host-a's replacement replays at 500 (after its wait), host-b's wait at 480 + + +def test_an_untimed_line_keeps_the_time_of_the_line_before_it(): + untimed = {k: v for k, v in replaced(0).items() if k != "time_unix"} + sp = _spares_of([("host-a", lost(T0 + 400)), ("host-a", untimed), ("host-b", waiting(T0 + 300))]) + assert not sp["waiting"] and sp["replacements"] == 1 and sp["last_at"] is None # host-b's wait is older + + +def test_a_spare_event_sets_no_shape_field_nor_state(): + base = reducer().islands["1"] + r = reducer(dict(lost(T0 + 10), island="other-name", gpu="H100", cloud="nowhere"), + dict(replaced(T0 + 5), gpu="H100")) # the second arrives older: a replay, still no lifecycle + isl = r.islands["1"] + for key in ("name", "gpu", "cloud", "fleet_state", "ready_ts", "lost_ts", "stop_ts", "open_ts", "closed_s"): + assert isl[key] == base[key], key + assert r.fleet_spares_log["1"] and "1" in r.fleet_spares_src_t + + +def test_a_health_event_is_no_spare_record(): + r = reducer(ev("node_health", T0 + 10, node="gpu-d", verdict="lost", reasons=["GPU 3 XID 79"])) + assert "spares" not in r.islands["1"] and "1" not in r.fleet_spares_log + assert any(e["type"] == "node_health" for e in r.events) + + +def test_the_record_wins_over_the_events(tmp_path): + r = reducer(lost(T0 + 400), waiting(T0 + 401), replaced(T0 + 450)) + st = store_state(tmp_path, "recovering", spares=spares_doc(lost=["gpu-d"], waiting_spare=True, + wait_reason=WAIT, waiting_since=T0 + 500)) + assert r.load_fleet_state(st) + c = cards(r)["1"] + sp = c["spares"] + assert sp["source"] == "record" and sp["waiting"] and sp["since"] == T0 + 500 and sp["replacements"] == 0 + assert sp["last"] is None # no replacement on the record: no names from the events either + assert c["status"] == "starting" and c["island_now"]["reason"] == "waiting for a spare node" + assert c["island_now"]["detail"] == WAIT + + +def test_the_record_s_replacements_take_the_names_of_the_last_event(tmp_path): + r = reducer(lost(T0 + 400), replaced(T0 + 450)) + st = store_state(tmp_path, "running", spares=spares_doc(nodes=["gpu-c", "gpu-e"], spare_nodes=["gpu-d"], + replacements=1, replacements_window=1, + last_replaced_at=T0 + 449)) + assert r.load_fleet_state(st) + sp = cards(r)["1"]["spares"] + assert (sp["replacements"], sp["window"], sp["max"], sp["last_at"]) == (1, 1, 3, T0 + 449) + assert sp["last"]["spare"] == "gpu-e" + + +def test_island_state_of_an_island_that_lost_a_node(): + rec = {"life_state": "recovering", "relaunches": 1, "incarnation": 1, + "spares": fleet_islands.spares_record(spares_doc(lost=["gpu-d"]))} + assert fleet_islands.island_state(rec) == {"state": "starting", "reason": "replacing lost node gpu-d", + "detail": "new launch recovering · incarnation 1"} + rec["spares"]["waiting_spare"], rec["spares"]["wait_reason"] = True, WAIT + assert fleet_islands.island_state(rec)["reason"] == "waiting for a spare node" + rec["life_state"] = "running" # replaced and running: the spares say nothing of its state + assert fleet_islands.island_state(rec) == {"state": "running", "reason": None, "detail": None} + + +def test_the_unhealthy_nodes_of_the_record(tmp_path): + r = reducer() + now = r.max_ts + health = {"verdict": "lost", "nodes": {"gpu-c": node("ok", now - 900), + "gpu-d": node("lost", now - 900, ["GPU 3 XID 79"], 2)}} + # the record is not written again while no verdict changes: a check as old as the record is current + assert r.load_fleet_state(store_state(tmp_path, "recovering", health=health, updated=now - 890)) + assert cards(r)["1"]["node_health"] == [{"node": "gpu-d", "verdict": "lost", "reasons": ["GPU 3 XID 79"], + "bad_in_row": 2}] + assert "spares" not in cards(r)["1"] # health checks without spare nodes + + +def test_a_check_older_than_its_record_reads_stale(tmp_path): + r = reducer() + now = r.max_ts + health = {"verdict": "ok", "nodes": {"gpu-c": node("ok", now - 10), "gpu-d": node("ok", now - 400)}} + assert r.load_fleet_state(store_state(tmp_path, "running", health=health, updated=now - 10)) + (bad,) = cards(r)["1"]["node_health"] # gpu-d's checks stopped 390 s before the record: 3 periods are 180 s + assert bad["node"] == "gpu-d" and bad["verdict"] == "read_failed" and bad["stale"] is True + assert fleet_islands.stale_health(health["nodes"]["gpu-d"], now - 300) is health["nodes"]["gpu-d"] # 100 s + + +@pytest.mark.parametrize("life", ["done", "failed"]) +def test_an_ended_island_shows_no_health(tmp_path, life): + now = reducer().max_ts + health = {"verdict": "lost", "nodes": {"gpu-d": node("lost", now - 10, ["GPU 3 XID 79"], 2)}} + r = reducer() + assert r.load_fleet_state(store_state(tmp_path, life, health=health, updated=now)) + assert "node_health" not in cards(r)["1"] + + +def test_the_record_fields_read_defensively(): + assert fleet_islands.spares_record(None) is None and fleet_islands.health_record("x") is None + sp = fleet_islands.spares_record({"waiting_spare": "yes", "replacements": True, "lost": ["a", 3, None]}) + assert sp["waiting_spare"] is False and sp["replacements"] == 0 and sp["lost"] == ["a"] + many = {"verdict": "lost", "reasons": [f"r{i}" for i in range(9)]} + h = fleet_islands.health_record({"nodes": {"a": many, "b": 1}}) + assert list(h["nodes"]) == ["a"] and len(h["nodes"]["a"]["reasons"]) == fleet_islands.HEALTH_REASONS_MAX + + +# -- no new field without spare nodes (every customer run) --------------------------------------------- +def test_no_new_field_without_spare_nodes(tmp_path): + r = reducer() + assert r.load_fleet_state(store_state(tmp_path, "running")) + view = json.dumps(r.page_view(now=r.max_ts), default=str) + assert not any(f'"{k}"' in view for k in NEW_KEYS) + st = store_state(tmp_path / "b", "running") + assert not any(k in (row["record"] or {}) for row in st["trainers"].values() for k in ("spares", "health")) + + +@pytest.mark.parametrize("fixture", sorted(p.name for p in FX.iterdir() if p.is_dir())) +def test_customer_fixtures_carry_no_new_field(fixture): + r = Reducer(run="cust") + load_all(r, [str(p) for p in sorted((FX / fixture).iterdir())]) + view = json.dumps(r.page_view(now=r.max_ts), default=str) + for key in NEW_KEYS + tuple(isp.__dict__[n] for n in ("NODE_LOST", "NODE_REPLACED", "WAITING_SPARE")): + assert f'"{key}"' not in view + + +# -- the page ------------------------------------------------------------------------------------------ +def _with_record(tmp_path, life, *extra, **fields): + r = reducer(*extra) + assert r.load_fleet_state(store_state(tmp_path / "s", life, **fields)) + return r + + +def test_a_waiting_island_s_card_badge_phase_and_why(tmp_path): + end = reducer().max_ts + r = _with_record(tmp_path, "recovering", lost(end - 100), waiting(end - 95), + spares=spares_doc(lost=["gpu-d"], waiting_spare=True, wait_reason=WAIT, waiting_since=end - 95)) + out = smoke(tmp_path, r) + assert out["dashed"] == 0 # warned, not drawn as a lost trainer + assert "waiting spare" not in out["texts"] # the phase line says it: no badge saying it again + assert "waiting for a spare node · 1m35s" in out["texts"] # how long, not the record's incarnation + assert any(t.startswith("gpu-e: lease held by run other · no free spare") for t in out["texts"]) # what to act on first + # Islands now: the mark in place of the status (no "waiting for a spare node" twice), the reason in the last cell + assert 'waiting spare 1m35s' in out["nodes"] + assert "waiting for a spare node" not in out["nodes"] + short = "gpu-e: lease held by run other · no free spare in rack-b" + assert f'
{short}
' in out["nodes"] + assert 'NodesShard · incarnation' in out["nodes"] # its own column + assert "waiting for a spare1m35s · " + WAIT in out["tip"] # the whole reason on a touch page + assert 'title="wait"' in out["events"] and "island_waiting_spare" in out["events"] + + +def test_a_wait_known_from_its_events_only(tmp_path): + end = reducer().max_ts + r = reducer(lost(end + 10), waiting(end + 20, elapsed=40)) + out = smoke(tmp_path, r) + assert "waiting for a spare node · 40s" in out["texts"] + assert "lost" not in out["texts"] and out["dashed"] == 0 # the wait, not a lost trainer + view = r.page_view(now=r.max_ts)["topology"]["diloco"] + assert view["roster"] == 1 # out of the syncer's roster while it waits + + +def test_a_silent_trainer_waiting_for_a_spare_is_not_drawn_lost(tmp_path): + end = reducer().max_ts # its tape silent for an hour: lost, unless it waits for a spare node + gone = smoke(tmp_path / "a", reducer(lost(end + 3590), ev("island_lost", end + 3600, reason=LOST))) + assert "lost" in gone["texts"] and gone["dashed"] >= 1 + out = smoke(tmp_path / "b", reducer(lost(end + 3590), ev("island_lost", end + 3595, reason=LOST), + waiting(end + 3600, elapsed=10))) + assert any(t.startswith("waiting for a spare node") for t in out["texts"]) + assert "lost" not in out["texts"] and out["dashed"] == 0 + + +@pytest.mark.parametrize("life", ["done", "failed"]) +def test_an_island_that_ended_is_no_longer_waiting(tmp_path, life): + end = reducer().max_ts + r = _with_record(tmp_path, life, lost(end - 100), waiting(end - 95), + spares=spares_doc(lost=["gpu-d"], waiting_spare=True, wait_reason=WAIT, waiting_since=end - 95)) + out = smoke(tmp_path, r) + assert "waiting spare" not in out["texts"] and not any("waiting for a spare" in t for t in out["texts"]) + assert "waiting spare" not in out["nodes"] + + +HELPERS = r""" +const fs = require("fs"), src = fs.readFileSync(process.argv[2], "utf8"); +const a = src.indexOf("// a resident ssh: island with spare nodes (tr.spares"), b = src.indexOf("function col(k){"); +var D = JSON.parse(process.argv[3]), C = {warn: "W", bad: "B", ink2: "M"}; +function fin(x) { return typeof x === "number" && isFinite(x); } +function dur(s) { return Math.round(s) + "s"; } +function spNow() { return 1000; } +function row(k, v) { return k + "=" + v + ";"; } +function col(k) { return k; } +function rich() {} +eval(src.slice(a, b)); +const tr = JSON.parse(process.argv[4]); +console.log(JSON.stringify({badge: spareBadge(tr), waiting: waitingSpare(tr), note: spareNote(tr, 1000)})); +""" + + +def helpers(tmp_path, d: dict, tr: dict) -> dict: + exe = shutil.which("node") + if exe is None: + pytest.skip("node not installed") + tmp_path.mkdir(parents=True, exist_ok=True) + (tmp_path / "h.js").write_text(HELPERS) + src = Path(__file__).parents[1] / "yeto/dashboard/static/topology_diloco.js" + res = subprocess.run([exe, str(tmp_path / "h.js"), str(src), json.dumps(d), json.dumps(tr)], capture_output=True, + text=True, timeout=60, check=False) + assert res.returncode == 0, res.stderr + return json.loads(res.stdout) + + +@pytest.mark.parametrize("d, now", [({"done": True}, None), ({"done": False}, {"state": "stopped"}), + ({"done": False}, {"state": "failed"})]) +def test_a_finished_run_or_island_has_no_spare_badge(tmp_path, d, now): + tr = {"island_now": now, "spares": {"waiting": True, "since": 900, "reason": WAIT, "replacements": 0}, + "node_health": [{"node": "gpu-d", "verdict": "lost", "reasons": ["GPU 3 XID 79"]}]} + out = helpers(tmp_path, d, tr) + assert out["badge"] is None and out["waiting"] is False and out["note"] is None + live = helpers(tmp_path / "b", {"done": False}, {**tr, "island_now": {"state": "starting"}}) + assert live["badge"] == ["node ✕", "B"] and live["waiting"] is True # the wait is no badge: its phase line + + +def test_a_lost_node_s_health_reason_and_badge(tmp_path): + now = reducer().max_ts + health = {"verdict": "lost", + "nodes": {"gpu-c": node("ok", now - 5), "gpu-d": node("lost", now - 5, ["GPU 3 XID 79"], 2)}} + r = _with_record(tmp_path, "recovering", + ev("node_health", now - 4, node="gpu-d", rank=1, verdict="lost", reasons=["GPU 3 XID 79"]), + lost(now - 3), spares=spares_doc(lost=["gpu-d"]), health=health, updated=now - 3) + out = smoke(tmp_path, r) + assert "node ✕" in out["texts"] and "gpu-d: GPU 3 XID 79" in out["texts"] + assert any(t.startswith("replacing lost node gpu-d") for t in out["texts"]) + assert 'node ✕' in out["nodes"] + assert '
gpu-d: GPU 3 XID 79
' in out["nodes"] + assert "node gpu-d
lost · GPU 3 XID 79" in out["tip"] + assert "node_health" in out["events"] and "reasons=GPU 3 XID 79" in out["events"] + assert r.page_view(now=r.max_ts)["topology"]["diloco"]["roster"] == 1 # stopped while a spare takes its place + + +def test_the_reason_styles_are_on_the_page(tmp_path): + page = export_html(reducer(), tmp_path / "p.html").read_text() + assert ".ns.bd{color:var(--bad)}" in page # a lost node's reason in red, not in the .ns grey + # the Nodes column: cut by the column's width (no fixed character count), the whole on hover + assert "table.nt th.spn,table.nt td.spn{text-align:left;width:14%;max-width:0}" in page + assert "table.nt td.spn .ns{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}" in page + assert "28ch" not in page + + +def test_one_bad_check_is_a_warning_without_badge(tmp_path): + now = reducer().max_ts + health = {"verdict": "bad_once", "nodes": {"gpu-c": node("bad_once", now - 5, ["GPU 0 uncorrectable ECC +1"], 1)}} + out = smoke(tmp_path, _with_record(tmp_path, "running", health=health, updated=now - 5)) + assert "gpu-c: GPU 0 uncorrectable ECC +1 · 1 bad check" in out["texts"] and "node ✕" not in out["texts"] + assert '
3 node replacement(s)
' in out["nodes"] + + +def test_the_reason_a_trainer_left_is_kept(tmp_path): + end = reducer().max_ts + r = _with_record(tmp_path, "failed", lost(end - 100), waiting(end - 95), limit(end - 50), + exit="3 node replacement(s) within 24 h: the island stops") + c = cards(r)["1"] + assert c["left"]["reason"] and c["spares"]["stopped"] + out = smoke(tmp_path, r) + assert '
' + c["left"]["reason"] + "
" in out["nodes"] # its last cell, as on main + + +@pytest.mark.parametrize("why, short", [ + ("fabric group rack-b has no free healthy spare node (gpu-e: quarantined (XID 79 (GPU 3)); gpu-f: held)", + "gpu-e: quarantined (XID 79 (GPU 3)); gpu-f: held · no free spare in rack-b"), + ("the inventory has no free healthy spare node (gpu-e: unhealthy); placement: no group (of 2) has room", + "gpu-e: unhealthy · no free spare · placement: no group (of 2) has room"), + ("fabric group rack-b has no free healthy spare node", "no free spare in rack-b"), + ("spare refused: no rendezvous address", "spare refused: no rendezvous address"), +]) +def test_why_no_spare_in_short(tmp_path, why, short): + end = reducer().max_ts + r = _with_record(tmp_path, "recovering", lost(end - 100), + spares=spares_doc(lost=["gpu-d"], waiting_spare=True, wait_reason=why, waiting_since=end - 95)) + out = smoke(tmp_path, r, width=2000) + assert '">' + short + "
" in out["nodes"] + + +def test_the_event_stream_shows_the_spare_node_events(tmp_path): + end = reducer().max_ts # the newest events: the stream shows the latest 15 + out = smoke(tmp_path, reducer(lost(end + 10), waiting(end + 20), replaced(end + 30), + limit(end + 40), + waiting(end + 50, elapsed=86400, given_up=True)))["events"] + assert 'title="lost"' in out and "island_node_lost" in out and "node=gpu-d" in out + assert 'title="wait"' in out and "elapsed_s=0" in out and "next_check_s=60" in out + assert 'title="swap"' in out and "lost=gpu-d spare=gpu-e resume_step=6" in out + assert 'title="max"' in out and 'title="stop"' in out and "given_up=true" in out + + +def test_a_long_field_is_cut_with_an_ellipsis_the_whole_on_hover(tmp_path): + end = reducer().max_ts + why = WAIT[:-1] + "; gpu-f: quarantined (XID 79 (GPU 3)))" # 120 characters + out = smoke(tmp_path, reducer(lost(end + 10), ev(isp.WAITING_SPARE, end + 20, lost=["gpu-d"], reason=why)))["events"] + assert "reason=" + why[:79] + "…" in out and "reason=" + why + " " not in out.split("title=")[0] + assert 'title="lost=gpu-d reason=' + why + '"' in out + assert "title=\"node=gpu-d" not in out # a line with no cut field has no hover of its own + + +def test_a_card_without_spare_nodes_draws_nothing_new(tmp_path): + out = smoke(tmp_path, reducer()) + for word in ("waiting spare", "node ✕", "replaced", "no free spare"): + assert word not in json.dumps(out) + + +# -- review fixes: health over a relaunch / a wait, replaced nodes, give-ups, long waits, the roster --------- +def test_a_waiting_island_keeps_its_lost_node_s_reason_and_no_stale_check(tmp_path): + """Its checks stop on purpose while it recovers (the record is written by the hourly wait report): + the lost node still reads lost with its reason, a healthy node is not shown, nothing reads stale.""" + end = reducer().max_ts + health = {"verdict": "lost", "nodes": {"gpu-c": node("ok", end - 3700), + "gpu-d": node("lost", end - 3700, ["GPU 3 XID 79"], 2)}} + r = _with_record(tmp_path, "recovering", lost(end - 3700), waiting(end - 3690), + spares=spares_doc(lost=["gpu-d"], waiting_spare=True, wait_reason=WAIT, waiting_since=end - 3690), + health=health, updated=end - 10) + assert cards(r)["1"]["node_health"] == [{"node": "gpu-d", "verdict": "lost", "reasons": ["GPU 3 XID 79"], + "bad_in_row": 2}] + out = smoke(tmp_path / "p", r) + assert "node gpu-d
lost · GPU 3 XID 79" in out["tip"] and "stale" not in out["tip"] + + +def test_a_node_a_spare_replaced_is_no_node_of_the_island(tmp_path): + end = reducer().max_ts + health = {"verdict": "lost", "nodes": {"gpu-c": node("ok", end - 30), + "gpu-d": node("lost", end - 30, ["GPU 3 XID 79"], 2)}} + r = _with_record(tmp_path, "running", lost(end - 100), replaced(end - 20), + spares=spares_doc(nodes=["gpu-c", "gpu-e"], spare_nodes=["gpu-d"], replacements=1, + replacements_window=1, last_replaced_at=end - 20), + health=health, updated=end - 5) + assert "node_health" not in cards(r)["1"] + out = smoke(tmp_path / "p", r) + assert "node ✕" not in out["texts"] and "node gpu-d" not in (out["tip"] or "") + + +def test_a_later_wait_or_replacement_ends_a_give_up(): + sp = _spares_of([("a", lost(T0 + 400)), ("a", limit(T0 + 500)), + ("b", lost(T0 + 9000)), ("b", waiting(T0 + 9001))]) + assert sp["stopped"] is None and sp["waiting"] # waiting again: not given up + sp = _spares_of([("a", lost(T0 + 400)), ("a", limit(T0 + 500)), ("b", lost(T0 + 9000)), ("b", replaced(T0 + 9100))]) + assert sp["stopped"] is None and sp["replacements"] == 1 + + +def test_a_running_record_shows_no_give_up(tmp_path): + end = reducer().max_ts + r = _with_record(tmp_path, "running", lost(end - 9000), limit(end - 8000), + spares=spares_doc(replacements=1, replacements_window=1, last_replaced_at=end - 100)) + assert cards(r)["1"]["spares"]["stopped"] is None + out = smoke(tmp_path / "p", r) + assert "3 node replacement(s)" not in out["nodes"] and "3 node replacement(s)" not in out["texts"] + events_only = cards(reducer(lost(end + 10), limit(end + 20)))["1"]["spares"] + assert events_only["stopped"] == "3 node replacement(s)" # no record: the events' give-up stays + # a running record without spares of its own: the events' give-up is over too + r = _with_record(tmp_path / "b", "running", lost(end - 9000), limit(end - 8000)) + sp = cards(r)["1"]["spares"] + assert sp["source"] == "events" and sp["stopped"] is None + + +HOUR = 3600.0 + + +def _long_wait(tmp_path, waited: float, *, report_age: float = 60.0, plan_absent: float | None = None, + max_wait: float | None = None): + """Island 1 waiting ``waited`` seconds for a spare node at the page's time, its record written + ``report_age`` seconds before it; its tape silent for an hour.""" + end = reducer().max_ts + now = end + HOUR + r = reducer(lost(now - 10), ev("island_lost", now - 5, reason=LOST), waiting(now, elapsed=waited)) + if plan_absent is not None: + assert r.load_fleet_plan({**plan_doc(), "roster": {"waiting_absent_after_s": plan_absent}}, "test") + doc = spares_doc(lost=["gpu-d"], waiting_spare=True, wait_reason=WAIT, waiting_since=now - waited, + **({"max_wait_s": max_wait} if max_wait is not None else {})) + assert r.load_fleet_state(store_state(tmp_path / "s", "recovering", spares=doc, updated=now - report_age)) + assert r.max_ts == now + return r + + +def test_a_wait_past_waiting_absent_after_s_counts_as_absent(tmp_path): + r = _long_wait(tmp_path, 2 * HOUR) + sp = cards(r)["1"]["spares"] + assert sp["waiting"] and sp["wait_state"] == {"state": "absent"} + out = smoke(tmp_path / "p", r) + assert "waiting for a spare node · counts as absent" in out["texts"] and out["dashed"] == 0 + assert "counts as absent" in out["nodes"] and "counts as absent for the fleet" in out["tip"] + assert out["roster"] == "--warn" # out of the roster as a warning, not a loss + # the plan's fleet.waiting_absent_after_s (3 h): two hours is an ordinary wait + r = _long_wait(tmp_path / "b", 2 * HOUR, plan_absent=3 * HOUR) + assert "wait_state" not in cards(r)["1"]["spares"] + assert "counts as absent" not in json.dumps(smoke(tmp_path / "q", r)) + + +@pytest.mark.parametrize("max_wait", [None, 6 * HOUR]) +def test_a_wait_past_spare_max_wait_s_reads_lost(tmp_path, max_wait): + waited = 30 * HOUR if max_wait is None else 7 * HOUR # past the default 24 h, or the record's own limit + r = _long_wait(tmp_path, waited, max_wait=max_wait) + c = cards(r)["1"] + assert not c["spares"]["waiting"] and c["spares"]["wait_state"]["state"] == "expired" + assert c["island_now"]["state"] == "lost" and c["status"] in ("lost", "stale") + out = smoke(tmp_path / "p", r) + assert out["dashed"] >= 1 and "lost" in out["texts"] # drawn as a lost trainer again + assert not any(t.startswith("waiting for a spare node ·") for t in out["texts"]) # no wait phase + assert any("past --spare-max-wait-s" in t for t in out["texts"]) and "past --spare-max-wait-s" in out["nodes"] + assert out["roster"] == "--bad" # a loss, not a wait + + +def test_a_wait_no_record_reports_any_more_reads_lost(tmp_path): + r = _long_wait(tmp_path, 2 * HOUR, report_age=2 * HOUR) # the launcher stopped writing it two hours ago + c = cards(r)["1"] + assert not c["spares"]["waiting"] and c["spares"]["wait_state"]["state"] == "frozen" + assert c["island_now"]["state"] == "unknown" # nobody says what it is + out = smoke(tmp_path / "p", r) + assert out["dashed"] >= 1 and "lost" in out["texts"] and "no report for 2.0 h" in out["nodes"] + # an hourly report one hour and ten minutes old is still a wait + ok = _long_wait(tmp_path / "b", 30 * 60, report_age=70 * 60) + assert cards(ok)["1"]["spares"]["waiting"] and "wait_state" not in cards(ok)["1"]["spares"] + + +def test_an_events_only_wait_no_event_reports_any_more_reads_lost(tmp_path): + end = reducer().max_ts + r = reducer(lost(end + 10), waiting(end + 20), ev("island_ready", end + 3 * HOUR, k=0)) + sp = cards(r)["1"]["spares"] + assert sp["source"] == "events" and not sp["waiting"] and sp["wait_state"]["state"] == "frozen" + + +def test_a_fresh_failure_waiting_for_a_spare_is_out_of_the_roster(tmp_path): + """Right after the failure its tape is still live: the wait alone (no lost-node event yet) takes + it out of the roster, and the layout line counts it the same way.""" + end = reducer().max_ts + base = reducer().page_view(now=end)["topology"]["diloco"] + assert base["roster"] == 2 and "roster_spare" not in base + r = reducer(waiting(end + 5)) + view = r.page_view(now=r.max_ts)["topology"]["diloco"] + assert cards(r)["1"]["spares"]["lost"] == [] and view["roster"] == 1 and view["roster_spare"] == 1 + out = smoke(tmp_path, r) + assert "1/2 trainer(s) live (1 replacing a lost node)" in out["note"] + assert out["roster"] == "--warn" + + +def test_the_wait_reads_the_same_time_on_card_tip_and_table(tmp_path): + end = reducer().max_ts + r = _with_record(tmp_path, "recovering", lost(end - 100), waiting(end - 95), + spares=spares_doc(lost=["gpu-d"], waiting_spare=True, wait_reason=WAIT, waiting_since=end - 95)) + out = smoke(tmp_path, r) + assert "waiting for a spare node · 1m35s" in out["texts"] # card + assert "waiting for a spare1m35s · " in out["tip"] # its tip + assert "waiting spare 1m35s" in out["nodes"] # Islands now diff --git a/tests/test_fleet_log_store.py b/tests/test_fleet_log_store.py index 54d3bbaeb..efa9645f5 100644 --- a/tests/test_fleet_log_store.py +++ b/tests/test_fleet_log_store.py @@ -258,7 +258,8 @@ def test_the_moved_host_s_island_is_running_with_the_lost_host_s_history(tmp_pat only_store = Reducer() assert fleet_store.store_readers(StoreTapes(objects, label="store")).pump(only_store) == len(a) + len(b) assert _lifecycle(only_store.islands["1"]) == RUNNING_AGAIN - assert {r["event"] for r in only_store.fleet_records} == {"island_ready", "island_lost"} + # every fleet.jsonl record once, the spare-node events too (a line of the fleet records, no lifecycle state) + assert sorted(r["event"] for r in only_store.fleet_records) == sorted(r["event"] for r in a + b) def test_a_folder_stamp_two_hours_off_does_not_change_the_state(tmp_path): diff --git a/tests/test_ssh_island_spares.py b/tests/test_ssh_island_spares.py index 5a846e029..d6fe8c201 100644 --- a/tests/test_ssh_island_spares.py +++ b/tests/test_ssh_island_spares.py @@ -378,6 +378,7 @@ def test_a_spare_takes_the_lost_nodes_place_in_the_same_layout(tmp_path, rank): view = ops.spares_view("isl") assert view["nodes"] == new and view["lost"] == [] and view["replacements"] == 1 assert view["waiting_spare"] is False and view["spare_nodes"] == [NAMES[rank]] + assert view["max_wait_s"] == isp.MAX_WAIT_S # --spare-max-wait-s: the page reads a longer wait as lost assert str(ops.job_status("isl", 1)) == "RUNNING" # the new incarnation's ledger row names its own nodes (a cleanup stops it there) rows = {r.id: r for r in ResourceLedger(tmp_path / "ledger.jsonl").open_resources()} diff --git a/yeto/dashboard/fleet_islands.py b/yeto/dashboard/fleet_islands.py index 81568fe25..391a7a913 100644 --- a/yeto/dashboard/fleet_islands.py +++ b/yeto/dashboard/fleet_islands.py @@ -132,6 +132,9 @@ def load_plan(doc: Any) -> dict | None: if isinstance(syncer, dict) else None)} if doc.get("launch") == "per_island": # its trainers are billed from their launch records (PlanFile) out["launch"] = "per_island" + absent = _f((doc.get("roster") or {}).get("waiting_absent_after_s")) if isinstance(doc.get("roster"), dict) else None + if absent is not None and absent > 0: # fleet.waiting_absent_after_s, when the plan sets it + out["waiting_absent_after_s"] = absent return out @@ -308,7 +311,11 @@ def _trainer_records(objects: Any, learners: Any = None) -> dict[int, dict]: dec = life.get("decision") if isinstance(life.get("decision"), dict) else ( launch.get("decision") if isinstance(launch.get("decision"), dict) else None) ended = launch.get("ended") if isinstance(launch.get("ended"), dict) else {} - out[k] = {"launch_state": _str(launch.get("state")), "life_state": _str(life.get("state")), + # a resident ssh: island with spare nodes and node health checks: only when its record has them + extra = {key: doc for key, doc in (("spares", spares_record(life.get("spares"), life.get("updated"))), + ("health", health_record(life.get("health"), life.get("updated")))) + if doc is not None} + out[k] = {**extra, "launch_state": _str(launch.get("state")), "life_state": _str(life.get("state")), "reason": _str(life.get("reason")), "since": _f(life.get("since")), "exit": _str(life.get("exit")), "decision": {x: _str(dec.get(x)) for x in ("action", "cause", "detail", "state")} if dec else None, "stop": {"at": _f(stop.get("at")), "by": _str(stop.get("by")), "reason": _str(stop.get("reason"))} @@ -327,6 +334,95 @@ def _trainer_records(objects: Any, learners: Any = None) -> dict[int, dict]: return out +def _names(v: Any) -> list[str]: + return [str(x) for x in v if isinstance(x, str) and x] if isinstance(v, (list, tuple)) else [] + + +def spares_record(doc: Any, updated: Any = None) -> dict | None: + """The ``spares`` of a trainer island's record (``SshIslandOps.spares_view``: a resident + ``ssh:`` island with spare nodes), the fields the page shows; None: no such field. + ``updated``: when the record was last written (a wait it no longer reports: :data:`WAIT_FROZEN_S`).""" + if not isinstance(doc, dict): + return None + waiting = doc.get("waiting_spare") is True + return {"nodes": _names(doc.get("nodes")), "spare_nodes": _names(doc.get("spare_nodes")), + "lost": _names(doc.get("lost")), "waiting_spare": waiting, + "wait_reason": _str(doc.get("wait_reason")) if waiting else None, + "waiting_since": _f(doc.get("waiting_since")) if waiting else None, + "replacements": _int(doc.get("replacements")) or 0, + "replacements_window": _int(doc.get("replacements_window")), + "max_replacements": _int(doc.get("max_replacements")), + "last_replaced_at": _f(doc.get("last_replaced_at")), + "max_wait_s": _f(doc.get("max_wait_s")), "updated": _f(updated)} + + +# a wait for a spare node (yeto.launch.island_spares; no import: the dashboard stands alone) +SPARE_MAX_WAIT_S = 24 * 3600.0 # --spare-max-wait-s: the island gives up after this long +SPARE_WAIT_REPORT_S = 3600.0 # island_spares.WAIT_REPORT_S: a waiting island's record is written this often +WAITING_ABSENT_AFTER_S = 3600.0 # yeto.rl.fleet.DEFAULT_WAITING_ABSENT_AFTER_S (fleet.waiting_absent_after_s) +# a waiting island whose record (or wait report) is older than this: its launcher no longer reports +# it (one hourly report missed, plus two health periods and 10 min of slack) +WAIT_FROZEN_S = SPARE_WAIT_REPORT_S + 2 * 60.0 + 600.0 + + +def spare_wait_state(waiting_since: float | None, updated: float | None, now: float, *, + absent_after_s: float | None = None, max_wait_s: float | None = None) -> dict | None: + """How a wait for a spare node reads at ``now``: None (an ordinary wait), ``{"state": "absent"}`` + past ``fleet.waiting_absent_after_s`` (the fleet counts the island absent; still waiting), or + ``{"state": "expired" | "frozen", "why"}``: past ``--spare-max-wait-s`` (the island should have + given up) or its record not written for :data:`WAIT_FROZEN_S` (no launcher reports the wait): + the wait is not believed and the island reads lost or unknown.""" + limit = SPARE_MAX_WAIT_S if max_wait_s is None else float(max_wait_s) + if waiting_since is not None and now - waiting_since > limit: + return {"state": "expired", "why": f"waiting for a spare node past --spare-max-wait-s ({limit / 3600:g} h): " + "the island should have given up; its launcher may be gone"} + if updated is not None and now - updated > WAIT_FROZEN_S: + return {"state": "frozen", "why": f"waiting for a spare node, but no report for {(now - updated) / 3600:.1f} h" + ": its launcher may be gone"} + absent = WAITING_ABSENT_AFTER_S if absent_after_s is None else float(absent_after_s) + if waiting_since is not None and now - waiting_since > absent: + return {"state": "absent"} + return None + + +HEALTH_REASONS_MAX = 3 # reasons of one node the page carries (its record keeps a few more) + + +def health_record(doc: Any, updated: Any = None) -> dict | None: + """The ``health`` of a trainer island's record (``SshIslandOps.island_health``: the newest + check of each node, ``yeto.hw.node_health``): ``{"verdict", "updated", "nodes": {name: + {verdict, reasons, bad_in_row, at, every_s}}}``; None: no such field. ``updated``: when the + record was last written (a check much older than it stopped: :func:`stale_health`).""" + if not isinstance(doc, dict) or not isinstance(doc.get("nodes"), dict): + return None + nodes = {} + for name, node in doc["nodes"].items(): + if not isinstance(node, dict) or not isinstance(name, str): + continue + nodes[name] = {"verdict": _str(node.get("verdict")), + "reasons": _names(node.get("reasons"))[:HEALTH_REASONS_MAX], + "bad_in_row": _int(node.get("bad_in_row")), "at": _f(node.get("at")), + "every_s": _f(node.get("every_s"))} + return {"verdict": _str(doc.get("verdict")), "updated": _f(updated), "nodes": nodes} + + +HEALTH_STALE_PERIODS = 3 # yeto.hw.node_health.STALE_PERIODS (no import: the dashboard stands alone) +HEALTH_EVERY_S = 60.0 # yeto.hw.node_health.HEALTH_EVERY_S + + +def stale_health(node: dict, updated: float | None) -> dict: + """A node's check as ``yeto.hw.node_health.fresh`` reads it, against the record's own write + time (the record is not written again while no verdict changes, so its ``updated`` and the + check's ``at`` move together while checks run): a check older than + :data:`HEALTH_STALE_PERIODS` periods before the record's write reads as ``read_failed`` + (``stale``: the check stopped, e.g. a hung node runtime).""" + at, every = node.get("at"), node.get("every_s") or HEALTH_EVERY_S + if at is None or updated is None or updated - at <= HEALTH_STALE_PERIODS * every: + return node + return {**node, "verdict": "read_failed", "stale": True, + "reasons": [f"health check stale: the last one {updated - at:.0f}s before the record"]} + + def _phase(life: str | None) -> str: """A launch's lifecycle state in words (``yeto.rl.island_launches``).""" return {"ordering": "ordering machines (failing over across zones while none is free)", @@ -373,6 +469,15 @@ def island_state(rec: dict | None, desired: dict | None = None) -> dict | None: # the launch after a move: ordering its new machines (sky fails over across zones and regions) return {"state": "moving", "reason": f"moving to {rec.get('gpu') or (desired or {}).get('gpu')}", "detail": f"new launch {_phase(life)} · incarnation {rec.get('incarnation')}"} + spares = rec.get("spares") or {} + if booting and (spares.get("waiting_spare") or spares.get("lost")): + # a resident ssh: island that lost a node: waiting for a spare node, or starting on one + lost = ", ".join(spares.get("lost") or ()) + if spares.get("waiting_spare"): + return {"state": "starting", "reason": "waiting for a spare node", + "detail": spares.get("wait_reason") or (f"lost {lost}" if lost else None)} + return {"state": "starting", "reason": f"replacing lost node {lost}", + "detail": f"new launch {_phase(life)} · incarnation {rec.get('incarnation')}"} if booting: relaunch = why_now if why_now.startswith("relaunch") else None return {"state": "starting", "reason": relaunch or ("relaunching" if (rec.get("relaunches") or 0) > 0 diff --git a/yeto/dashboard/reducer.py b/yeto/dashboard/reducer.py index 17f2b7d02..69ac52b08 100644 --- a/yeto/dashboard/reducer.py +++ b/yeto/dashboard/reducer.py @@ -61,6 +61,13 @@ SPOT_EVENTS = frozenset({"spot_reclaim", "spot_replace_advice", "spot_replace_launch", "spot_budget_cap"}) SPOT_MAX = 500 FLEET_VIEW_MAX = 500 # fleet records / cost ticks the fleet view shows (the last ones) +# a resident ssh: island's spare nodes (yeto.launch.island_spares) and its nodes' health checks +# (yeto.hw.node_health): fleet.jsonl events that mark its card, never a lifecycle state nor a +# sign of life of its trainer +SPARE_EVENTS = frozenset({"island_node_lost", "island_waiting_spare", "island_node_replaced", + "island_replacement_limit"}) +NODE_HEALTH_EVENTS = frozenset({"node_health", "node_health_read_failed", "node_health_degraded"}) +FLEET_EVENTS = FLEET_EVENTS | SPARE_EVENTS | NODE_HEALTH_EVENTS NO_DATA = None # Overlay-chart metrics (v7 tabs): series key -> (label, extractor field paths). @@ -354,6 +361,11 @@ def __init__(self, *, run: str | None = None, prices: dict | None = None, self.fleet_lifecycle: dict[str, list[tuple[float, int, str, float]]] = {} self.fleet_source_ts: dict[tuple[str, str], float] = {} # (island, source) -> its newest record time self.fleet_shape_ts: dict[str, dict[str, float]] = {} # island -> shape field -> its record's time + # island -> its spare-node records [(time, seq, event, record, ts)] in replay order: by + # time_unix across sources, in write order within one source (another host's store copy + # that arrives late is replayed in place); island -> source -> its latest replay time + self.fleet_spares_log: dict[str, list[tuple[float, int, str, dict, float | None]]] = {} + self.fleet_spares_src_t: dict[str, dict[str, float]] = {} self.events: deque = deque(maxlen=MAX_EVENTS) self.event_seq = 0 self.max_ts: float | None = None @@ -1455,6 +1467,14 @@ def _feed_fleet(self, r: dict, iid: str | None, ts: float | None) -> None: if iid is None: return isl = self.island(iid) + # spare-node and node health events: a mark on the card (and a line of the event stream), + # never a shape field nor a lifecycle state of the island: they return before both (and + # before the lifecycle insort) + if event in SPARE_EVENTS: + self._feed_spares(isl, event, r, ts) + return + if event in NODE_HEALTH_EVENTS: + return # the record carries the health per node; the event is a line of the stream only # The island's timed lifecycle records in fold order (eff, seq, event, ts). A source's # time never goes back (eff): a clock stepped back in one file folds in write order, as on # main. A record before the newest of another source (a lost host's store copy read late) @@ -1514,6 +1534,128 @@ def _fold_fleet_lifecycle(isl: dict, event: str, ts: float | None) -> None: isl["closed_s"] += max(0.0, ts - isl["open_ts"]) isl["open_ts"] = None + def _feed_spares(self, isl: dict, event: str, r: dict, ts: float | None) -> None: + """Fold a spare-node event in replay order: by its ``time_unix`` across sources, in + write order within one source (a record of a source never goes before an earlier line + of that source, even with an older time; an untimed one keeps the time of the line + before it). A record that sorts before one folded already (a lost host's store copy + read after the new host's records) replays the island's ``spares`` mark from its + records; in-order records fold as they come.""" + iid, source = str(isl["id"]), self._source + log = self.fleet_spares_log.setdefault(iid, []) + src_t = self.fleet_spares_src_t.setdefault(iid, {}) + prev = src_t.get(source) + if ts is None: + t = prev if prev is not None else (log[-1][0] if log else float("-inf")) + else: + t = ts if prev is None else max(ts, prev) + src_t[source] = t + row = (t, self.event_seq, event, r, ts) + if log and row[:2] < log[-1][:2]: + bisect.insort(log, row) + isl.pop("spares", None) + for _t, _seq, ev, rec, at in log: + self._fold_spares(isl, ev, rec, at) + return + log.append(row) + self._fold_spares(isl, event, r, ts) + + @staticmethod + def _fold_spares(isl: dict, event: str, r: dict, ts: float | None) -> None: + """A spare-node event of a resident ssh: island (``yeto.launch.island_spares``) into its + ``spares`` mark: what the card shows when the island's record has none.""" + sp = isl.get("spares") + if sp is None: + sp = isl["spares"] = {"waiting": False, "since": None, "reason": None, "replacements": 0, + "last_at": None, "last": None, "lost": [], "stopped": None, "last_ts": None} + if ts is not None: # the newest spare-node event (a wait no event reports any more reads frozen) + sp["last_ts"] = ts if sp["last_ts"] is None else max(sp["last_ts"], ts) + why = str(r["reason"])[:300] if r.get("reason") else None + if event == "island_node_lost": + if r.get("node") and r["node"] not in sp["lost"]: + sp["lost"].append(str(r["node"])) + elif event == "island_waiting_spare": + if r.get("given_up"): + sp.update(waiting=False, since=None, stopped=why) + else: + waited = finite(r.get("elapsed_s")) + start = ts - waited if ts is not None and waited is not None else ts + # a new wait: an earlier give-up is over; a later report keeps the wait's first start + sp.update(waiting=True, reason=why or sp["reason"], stopped=None, + since=sp["since"] if sp["waiting"] and sp["since"] is not None else start) + elif event == "island_node_replaced": + sp["replacements"] += 1 + sp["last_at"] = ts + sp["last"] = {"lost": r.get("lost"), "spare": r.get("spare"), "rank": r.get("rank"), + "resume_step": r.get("resume_step"), "reason": why} + sp["lost"] = [n for n in sp["lost"] if n != r.get("lost")] + sp.update(waiting=False, since=None, reason=None, stopped=None) # a spare took its place: not given up + elif event == "island_replacement_limit": + sp.update(waiting=False, since=None, stopped=why) + + def _spares_card(self, isl: dict, inow: dict | None, now: float) -> dict: + """A trainer island's spare nodes and its unhealthy nodes, for its card: its record's + (``spares`` / ``health`` in ``fleet/trainers//state.json``) over its fleet.jsonl + events. Empty (no key at all) for an island without spare nodes or health checks. + + A wait for a spare node carries ``wait_state`` (:func:`fleet_islands.spare_wait_state`) + past ``fleet.waiting_absent_after_s`` (absent), past ``--spare-max-wait-s`` (expired) or + when no record or event reported it for an hour (frozen); expired and frozen are no + wait (``waiting`` false): the island reads lost or unknown. A give-up (``stopped``) is + not shown once the island's record runs again.""" + trainers = (self.fleet_state or {}).get("trainers") or {} + k = int(isl["id"]) if str(isl["id"]).isdigit() else None + rec = ((trainers.get(k) if k is not None else None) or {}).get("record") or {} + mine, ev = rec.get("spares"), isl.get("spares") + running = bool(inow) and inow.get("state") == "running" + out: dict[str, Any] = {} + updated = max_wait = None + if mine: + out["spares"] = {"waiting": bool(mine.get("waiting_spare")), "since": mine.get("waiting_since"), + "reason": mine.get("wait_reason"), "replacements": mine.get("replacements") or 0, + "window": mine.get("replacements_window"), "max": mine.get("max_replacements"), + "last_at": mine.get("last_replaced_at"), "lost": list(mine.get("lost") or ()), + "spare_nodes": list(mine.get("spare_nodes") or ()), + # the names of the last replacement are on its event only + "last": (ev or {}).get("last") if mine.get("replacements") else None, + "stopped": None if running else (ev or {}).get("stopped"), "source": "record"} + updated, max_wait = mine.get("updated"), mine.get("max_wait_s") + elif ev: + out["spares"] = {**{key: ev[key] for key in ("waiting", "since", "reason", "replacements", "last_at", + "last", "stopped")}, + "window": None, "max": None, "lost": list(ev["lost"]), "spare_nodes": None, + "source": "events"} + if running: + out["spares"]["stopped"] = None + updated, max_wait = ev.get("last_ts"), None + sp = out.get("spares") + if sp and sp["waiting"]: + ws = fleet_islands.spare_wait_state( + sp["since"], updated, now, max_wait_s=max_wait, + absent_after_s=(self.fleet_plan or {}).get("waiting_absent_after_s")) + if ws is not None: + sp["wait_state"] = ws + if ws["state"] != "absent": # not believed: no wait masks the island's loss + sp["waiting"] = False + health = rec.get("health") + # an island that ended: its last checks say nothing of it now + if health and (inow is None or inow.get("state") in ("running", "starting", "moving")): + # the island's nodes now (a node a spare replaced is none of them any more) + nodes = set((mine or {}).get("nodes") or ()) or None + bad = [] + for name, node in sorted((health.get("nodes") or {}).items()): + if nodes is not None and name not in nodes: + continue + if running: # checks run only while the island runs (stopped on purpose while it recovers) + node = fleet_islands.stale_health(node, health.get("updated")) + if node.get("verdict") in (None, "ok"): + continue + bad.append({"node": name, "verdict": node["verdict"], "reasons": list(node.get("reasons") or ()), + "bad_in_row": node.get("bad_in_row"), **({"stale": True} if node.get("stale") else {})}) + if bad: + out["node_health"] = bad + return out + def _feed_pool(self, r: dict, iid: str | None, ts: float | None) -> None: self.async_.fold_pool(r) @@ -1663,6 +1805,14 @@ def _island_card(self, isl: dict, now: float) -> dict: # a trainer island of a fleet launched island by island: its records in the run store say # what it is (yeto.rl.trainer_worker), over what its tape last said inow = self._trainer_island_now(isl) if role != "sampler" else None + # spare nodes and unhealthy nodes of a resident ssh: island (no key without them) + spare_card = self._spares_card(isl, inow, now) if role != "sampler" else {} + ws = (spare_card.get("spares") or {}).get("wait_state") or {} + if inow and ws.get("state") in ("expired", "frozen") and inow["state"] == "starting": + # a wait past the longest wait (lost) or nobody reports any more (unknown) is not a start: the + # island reads what its tape says + inow = {**inow, "state": "lost" if ws["state"] == "expired" else "unknown", "reason": ws["why"], + "detail": inow.get("reason")} rec_stopped = bool(inow) and inow["state"] in ("stopped", "done", "down") if inow and inow["state"] in ("moving", "starting"): left = None # the leave on its tape is the superseded launch's: its next launch is starting @@ -1785,6 +1935,8 @@ def _island_card(self, isl: dict, now: float) -> dict: # round metrics the island's backend does not report: shown as "not reported by " "unreported": unreported_metrics(isl.get("backend")), "backend_label": backend_label(isl.get("backend")), + # spare nodes and unhealthy nodes of a resident ssh: island (no key without them) + **spare_card, } def infer_hardware(self) -> None: diff --git a/yeto/dashboard/static/app.js b/yeto/dashboard/static/app.js index 30337b9ed..73015aae0 100644 --- a/yeto/dashboard/static/app.js +++ b/yeto/dashboard/static/app.js @@ -459,9 +459,18 @@ function evText(e){var r=e.record||{},keys=["phase","rollout_id","policy_version arrived before it, -inf before any) and its arrival index; ties keep the arrival order, newest arrival first */ function evOrder(evs){var t=-Infinity;return evs.map(function(e,i){if(fin(e.ts))t=e.ts;return [e,fin(e.ts)?e.ts:t,i]}) .sort(function(a,b){return a[1]!==b[1]?(b[1]>a[1]?1:-1):b[2]-a[2]}).map(function(x){return x[0]})} +// a resident ssh: island's spare nodes (yeto.launch.island_spares) and node health checks (yeto.hw.node_health) +var EV_SPARE={island_node_lost:["bd","lost"],island_waiting_spare:["wn","wait"],island_node_replaced:["ok","swap"],island_replacement_limit:["bd","max"], + node_health:["bd","node"],node_health_read_failed:["wn","node"],node_health_degraded:["mu","node"]}; +var EV_SPARE_KEYS=["node","lost","spare","resume_step","verdict","reasons","reason","elapsed_s","next_check_s","given_up"]; +Object.keys(EV_SPARE).forEach(function(t){EV_KEEP[t]=1}); +// [level, its fields (a value over 80 characters cut with an ellipsis), the whole fields (the line's hover)] +function evSpare(e){var r=e.record||{},l=EV_SPARE[e.type];if(e.type==="island_waiting_spare"&&r.given_up)l=["bd","stop"]; + var kv=EV_SPARE_KEYS.filter(function(k){return r[k]!=null&&!(Array.isArray(r[k])&&!r[k].length)}).map(function(k){return [k,Array.isArray(r[k])?r[k].join(", "):String(r[k])]}); + return [l,kv.map(function(x){return x[0]+"="+(x[1].length>80?x[1].slice(0,79)+"…":x[1])}).join(" "),kv.map(function(x){return x[0]+"="+x[1]}).join(" ")]} function events(){ var ec=YetoTbl.cap("event-stream",evOrder(EVENTS.filter(function(e){return keepEv(e.type)})),{def:15,unit:"events"}),list=ec.rows; - $("evs").innerHTML=ec.bar+list.map(function(e){var l=evLevel(e.type,e.record||{});return '
'+(fleetOn()&&!fin(e.ts)?'—':clock(e.ts))+''+l[1]+''+esc(e.type.replace(/^rl_/,""))+''+(e.island!=null?" "+esc(cardOf(e.island)?lbl(e.island):"island "+e.island):"")+' '+esc(evText(e))+'
'}).join("")||'
none
'; + $("evs").innerHTML=ec.bar+list.map(function(e){var sp=EV_SPARE[e.type]?evSpare(e):null,l=sp?sp[0]:evLevel(e.type,e.record||{});return '
'+(fleetOn()&&!fin(e.ts)?'—':clock(e.ts))+''+l[1]+''+esc(e.type.replace(/^rl_/,""))+''+(e.island!=null?" "+esc(cardOf(e.island)?lbl(e.island):"island "+e.island):"")+' '+esc(sp?sp[1]:evText(e))+'
'}).join("")||'
none
'; } function cmds(){ var run=O.run||"",cm=O.commands||{}; diff --git a/yeto/dashboard/static/index.html b/yeto/dashboard/static/index.html index 09f92e6e5..30cf2a840 100644 --- a/yeto/dashboard/static/index.html +++ b/yeto/dashboard/static/index.html @@ -169,6 +169,9 @@ .nn{display:flex;align-items:center;gap:6px;white-space:nowrap}.ns{font-size:11px;color:var(--ink2);margin-top:1px} .dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex:none}.dot.g{background:var(--good)}.dot.y{background:var(--warn)}.dot.r{background:var(--bad)}.dot.m{background:var(--ink2)} .sq{width:8px;height:8px;border-radius:2px;display:inline-block;flex:none} +/* a resident ssh: island's spare / health reason (Islands now Nodes column): one line cut to the column's + width, the whole on hover; a lost node in red */ +table.nt th.spn,table.nt td.spn{text-align:left;width:14%;max-width:0}table.nt td.spn .ns{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ns.bd{color:var(--bad)} td.bar,th.bar{text-align:left!important;min-width:200px}.bl{font-size:11px;margin-bottom:3px} .bt{position:relative;height:5px;background:#3a3a40;border-radius:3px}.bf{height:5px;background:#facc15;border-radius:3px}.bf.over{background:var(--bad)}.bf.idle{background:var(--ink2)}.nt tr.off td{color:var(--ink2)}.nt tr.off .sq{opacity:.45} .bm{position:absolute;top:-2px;width:2px;height:9px;background:var(--ink)} diff --git a/yeto/dashboard/static/sft.js b/yeto/dashboard/static/sft.js index e3595d7d3..cc48b72f0 100644 --- a/yeto/dashboard/static/sft.js +++ b/yeto/dashboard/static/sft.js @@ -519,6 +519,33 @@ var NA_KPI={"MFU":"not on the tapes","Projected finish":"no total round count"," function naKpi(x){var t=String(x[0]),v=String(x[1]),y=x.slice(); y[1]=v==="n/a"?(NA_KPI[t]||(/step p50$/.test(t)?"no steps yet":"not on the tapes yet")):v.replace(/\bn\/a\b/g,"—"); y[2]=String(x[2]==null?"":x[2]).replace(/\bn\/a\b/g,"—");return y} +// a resident ssh: island's spare nodes and unhealthy nodes (the card's spares / node_health). Durations as the +// topology cards write them (1m36s), the reasons in the topology's words (YetoTopoD) +function hms(s){return typeof YetoTopo!=="undefined"&&YetoTopo.util?YetoTopo.util.dur(s):dur(s)} +function spEnded(c){return /^(done|stopped|left)$/.test(c.status)||!!(c.island_now&&/^(stopped|done|down|removed|failed|abandoned)$/.test(c.island_now.state))} +var TD=function(){return typeof YetoTopoD!=="undefined"&&YetoTopoD.whyNoSpare?YetoTopoD:null}; +// the time spare waits are measured against: the topology's (its cards and tips use it too), else the page's +function spNow(){var t=TD()&&TD().spNow?TD().spNow():null;return t==null?NOW:t} +function spWait(c){return (c.spares||{}).wait_state||null} +// the Island column's mark ([text, class, dot]) in place of its status, as the straggler's +function spareMark(c){var sp=c.spares;if(spEnded(c))return null; + if(sp&&sp.waiting)return ["waiting spare"+(fin(sp.since)?" "+hms(Math.max(0,spNow()-sp.since)):"")+((spWait(c)||{}).state==="absent"?" · counts as absent":""),"wn","y"]; + return (c.node_health||[]).some(function(h){return h.verdict==="lost"})?["node ✕","bd","r"]:null} +// the trainer row's Nodes cell: the reason only ([text, hover, class]) or null +function spareCell(c){var sp=c.spares,bad=spEnded(c)?[]:c.node_health||[],td=TD(),out=[],tip=[],cls="",ws=spWait(c); + if(sp&&sp.stopped)return [sp.stopped,sp.stopped,"bd"]; + if(ws&&ws.state!=="absent"&&!spEnded(c))return [ws.why,ws.why,"bd"]; // a wait not believed: lost or unknown + if(sp&&sp.waiting&&!spEnded(c))return [td?td.whyNoSpare(sp.reason):sp.reason||"no free spare node",sp.reason||"no free spare node","wt"]; + if(bad.length){var h=bad[0],why=function(x){return td?td.healthWhy(x):x.reasons.join("; ")||x.verdict}; + out.push(h.node+": "+why(h)+(bad.length>1?" +"+(bad.length-1):"")); + tip=bad.map(function(x){return x.node+": "+(x.verdict==="lost"?"lost · ":"")+why(x)});cls=bad.some(function(x){return x.verdict==="lost"})?"bd":"wt"} + if(sp&&sp.replacements>0){var l=sp.last||{};out.push("replaced "+sp.replacements+"×"+(fin(sp.last_at)?" · "+hms(Math.max(0,spNow()-sp.last_at))+" ago":"")); + tip.push((l.lost&&l.spare?l.lost+" → "+l.spare+(l.resume_step!=null?", resumed at step "+l.resume_step:"")+"; ":"")+(fin(sp.window)&&fin(sp.max)?sp.window+" of at most "+sp.max+" replacements in 24 h":sp.replacements+" replacement(s)"))} + return out.length?[out.join(" · "),tip.join("\n"),cls]:null} +// the Nodes column (only on a page with a resident ssh: island that has spare nodes or health checks): one +// line cut to the column's width with an ellipsis, the whole on hover +function spareTd(c){var t=spareCell(c); + return ''+(t?'
'+esc(t[0])+'
':"")+''} function rlm(V){ var O=V.overview||{},A=V.async||{},S=A.samplers||{},TR=A.trainers||{},X=V.islands||{},cs=rlCards(V); var t1=END,t0=END-RANGE_H*3600,tp=t0-RANGE_H*3600; @@ -572,20 +599,24 @@ function rlm(V){ // a run with a syncer: local step / outer version, last PUSH / BCAST; no HBM column when nothing sampled it var dl=typeof YetoTopoD!=="undefined"?YetoTopoD.table(V):null,noHbm=!!dl&&!cs.some(function(c){return fin(hbm(c))}); var head='Island'+(dl?'Local step / outer sweep':"Round / policy")+'Rewardtrain-rollout KLlogprob |diff|grad_normStep / round timeTokens/s'+(noHbm?"":'HBM peak')+''+(dl?"Last PUSH / BCAST applied":"Last release / load")+'Shard · incarnation'; + var spc=cs.some(function(c){return c.role!=="sampler"&&(c.spares||c.node_health)}),nc=(noHbm?9:10)+(spc?1:0); + if(spc)head=head.replace("Shard · incarnation",'NodesShard · incarnation'); var flNa=rlMulti(V); var rowOf=function(c){var ex=X[c.id]||{},s=S[c.id],rr=RR(c),r=rr[rr.length-1]||{},liv=rlLive(c.status),h=hbm(c),lim=ex.hbm_total_gib,mx=Math.max(64,fin(lim)?lim*1.15:0),pc=fin(h)?Math.min(100,100*h/mx):0; - var row='
'+rlDot(c.status)+''+esc(c.label)+'
'+esc([c.name,c.gpu?c.gpu+" × "+c.cards:null,c.backend_label].filter(Boolean).join(" · ")||"n/a")+' · '+esc(c.status+(c.waiting_reason?": "+c.waiting_reason:"")+(c.left?" ("+(c.left.reason||"")+")":"")+(c.starting&&c.startup_stage?": "+c.startup_stage.label+(fin(c.startup_stage.age_s)?" "+dur(c.startup_stage.age_s):"")+(fin(c.startup_s)?" · start "+dur(c.startup_s):""):"")+((c.launches||[]).length>1?" · launch "+(c.launches.length)+" ("+(c.launches.length-1)+" superseded)":""))+'
'; + // a resident ssh: island waiting for a spare node or with a lost node: its mark in place of its status + var sm=c.role!=="sampler"?spareMark(c):null,wr=sm&&c.waiting_reason==="waiting for a spare node"?null:c.waiting_reason; + var row='
'+(sm?'':rlDot(c.status))+''+esc(c.label)+'
'+esc([c.name,c.gpu?c.gpu+" × "+c.cards:null,c.backend_label].filter(Boolean).join(" · ")||"n/a")+' · '+(sm?''+esc(sm[0])+'':esc(c.status))+esc((wr?": "+wr:"")+(c.left?" ("+(c.left.reason||"")+")":"")+(c.starting&&c.startup_stage?": "+c.startup_stage.label+(fin(c.startup_stage.age_s)?" "+dur(c.startup_stage.age_s):"")+(fin(c.startup_s)?" · start "+dur(c.startup_s):""):"")+((c.launches||[]).length>1?" · launch "+(c.launches.length)+" ("+(c.launches.length-1)+" superseded)":""))+'
'; var hb='
'+(fin(h)?h.toFixed(1)+" GiB"+(fin(lim)?" of "+lim+" GiB":""):"not sampled")+'
'+(fin(lim)?'
':"")+'
'+(fin(h)?"":'
'+(/unavailable/.test(ex.gpu_mem_note||"")?"telemetry library missing":"enable --rl-resource-sample-interval")+'
')+''; if(noHbm)hb=""; if(c.role==="sampler"&&s){var sr=s.rounds||[],l=s.last_round||sr[sr.length-1]||{},ld=(A.releases||[]).map(function(x){return (x.loads||{})[c.id]?[x.policy_version,x.loads[c.id]]:null}).filter(Boolean).pop(); return row+''+ k(s.n_rounds-(s.empty_rounds||0),0)+(s.empty_rounds?' (+'+k(s.empty_rounds,0)+' empty)':'')+' / '+(s.policy_version==null?"n/a":"v"+s.policy_version)+'
'+ago(l.ts)+' · age p50 '+k(s.lag_p50,1)+'
'+(dl&&!fin(s.reward_mean_last)?'—
not on its tape
':k(s.reward_mean_last,3))+(fin(s.reward_last_ts)?'
round '+esc(s.reward_last_rollout_id)+' · '+ago(s.reward_last_ts)+'
':"")+''+'—'.repeat(3)+''+dur(l.generate_s)+'
generate, p50 '+dur(s.generate_p50_s)+'
'+(fin(l.response_tokens)&&l.generate_s?k(l.response_tokens/l.generate_s):dl?'—
no tokens on its rounds
':"n/a")+''+hb+ - ''+(ld?(ld[1].at_start?"at start":dur(ld[1].load_wall_s))+'
load v'+ld[0]+' · '+ago(ld[1].loaded_at)+' · '+(ld[1].at_start?"loaded when the sampler started":dur(ld[1].latency_s)+' after release')+'
'+(ld[1].at_start?"":loadParts(ld[1])):"none yet")+''+esc(s.shard||c.id)+'
'+esc(s.incarnation||"n/a")+(pl?" · pool "+esc(pl.event.replace("nc_elastic_",""))+(pl.ticket?" "+esc(pl.ticket):""):"")+'
'} + ''+(ld?(ld[1].at_start?"at start":dur(ld[1].load_wall_s))+'
load v'+ld[0]+' · '+ago(ld[1].loaded_at)+' · '+(ld[1].at_start?"loaded when the sampler started":dur(ld[1].latency_s)+' after release')+'
'+(ld[1].at_start?"":loadParts(ld[1])):"none yet")+''+(spc?'':'')+''+esc(s.shard||c.id)+'
'+esc(s.incarnation||"n/a")+(pl?" · pool "+esc(pl.event.replace("nc_elastic_",""))+(pl.ticket?" "+esc(pl.ticket):""):"")+'
'} var mr=(A.releases||[]).filter(function(x){return String(x.trainer)===String(c.id)}).pop(),kl=lastW(rr,"kl_tr")||lastW(rr,"kl")||{},cw=curWait(V,c),un=c.unreported||{}; var gn=lastW(rr,"grad_norm")||{},dstep=dl&&dl.step(c); return row+''+(dstep!=null?esc(dstep):(r.round==null?"n/a":r.round)+' / '+(c.policy_version==null?'—':(fin(c.released_version)&&c.released_version!==c.policy_version?"local v":"v")+c.policy_version))+'
'+(dstep==null&&fin(c.released_version)&&c.released_version!==c.policy_version?"released v"+c.released_version+" · ":"")+ago(r.ts)+'
'+k((lastW(rr,"reward")||{}).reward,3)+''+(fin(kl.kl_tr)?k(kl.kl_tr,4)+(fin(kl.kl)?'
PPO '+k(kl.kl,4)+'
':un.ppo_kl?'
PPO '+esc(un.ppo_kl)+'
':""):fin(kl.kl)?(un.train_rollout_kl?'—':'n/a')+'
PPO '+k(kl.kl,4)+'
':un.train_rollout_kl?'—
'+esc(un.train_rollout_kl)+'
':"n/a")+''+k((lastW(rr,"logprob_diff")||{}).logprob_diff,4)+''+k(gn.grad_norm,3)+(gn.grad_norm===0&&gn.reward_std===0?'
all rewards equal
':"")+''+ - ''+dur(r.step_s)+(fin(r.round_s)||!flNa?'
round '+dur(r.round_s)+'
':'')+(cw&&cw.s>=60?'
current round'+(cw.round!=null?" "+cw.round:"")+' waiting for data '+dur(cw.s)+'
':"")+''+k(r.tok_s)+''+hb+''+(dl&&dl.trainers[c.id]?dl.push(c,NOW):mr?dur(mr.upload_s)+'
release v'+mr.policy_version+' · '+ago(mr.released_at)+'
':"none"+(c.status==="left"?"":" by this trainer"))+'trainer '+esc(c.id)+'
'+esc((c.left||{}).reason||"")+'
'}; - var unkRow=function(c){var ex=X[c.id]||{};return '
'+rlDot("unknown")+''+esc(c.label)+'
no trainer or sampler events in this tape; not counted
'+ + ''+dur(r.step_s)+(fin(r.round_s)||!flNa?'
round '+dur(r.round_s)+'
':'')+(cw&&cw.s>=60?'
current round'+(cw.round!=null?" "+cw.round:"")+' waiting for data '+dur(cw.s)+'
':"")+''+k(r.tok_s)+''+hb+''+(dl&&dl.trainers[c.id]?dl.push(c,NOW):mr?dur(mr.upload_s)+'
release v'+mr.policy_version+' · '+ago(mr.released_at)+'
':"none"+(c.status==="left"?"":" by this trainer"))+''+(spc?spareTd(c):'')+'trainer '+esc(c.id)+'
'+esc((c.left||{}).reason||"")+'
'}; + var unkRow=function(c){var ex=X[c.id]||{};return '
'+rlDot("unknown")+''+esc(c.label)+'
no trainer or sampler events in this tape; not counted
'+ esc(c.source_lost?"tape source lost: "+String(c.source_lost.error||"").slice(0,120):"")+''}; var liveC=act.filter(function(c){return rlLive(c.status)||c.status==="stale"}),endC=act.filter(function(c){return liveC.indexOf(c)<0}); // a fleet: a value its tapes do not carry is a dash that says so, never a bare n/a (tags and attributes kept) @@ -593,7 +624,7 @@ function rlm(V){ var never=function(c){return flNa&&!rlLive(c.status)&&c.status!=="stale"&&!RR(c).length&&!SR(c).length}; var neverRow=function(c){var why=c.left&&(c.left.reason||c.left.detail),st=c.status==="left"?"left":c.status; return '
'+rlDot(c.status)+''+esc(c.label)+'
'+esc([c.name,c.gpu?c.gpu+" × "+c.cards:null].filter(Boolean).join(" · "))+'
'+ - ''+esc(st+(why?": "+why:"")+" · ended before its first round")+''}; + ''+esc(st+(why?": "+why:"")+" · ended before its first round")+''}; var rowNa=function(c){if(never(c))return neverRow(c);var h=rowOf(c);return flNa?h.replace(/(<[^>]*>)|\bn\/a\b/g,function(m,tag){return tag||'—'}):h}; $("rNodes").innerHTML=(liveC.length?''+head+liveC.map(rowNa).join("")+'
':'
no active island
')+ (endC.length?'
'+endC.length+' island(s) that ended (left / lost / finished / stopped): '+esc(endC.map(function(c){return c.label+" "+c.status}).join(", "))+''+head+endC.map(rowNa).join("")+'
':"")+ diff --git a/yeto/dashboard/static/topology_diloco.js b/yeto/dashboard/static/topology_diloco.js index cb798a875..1b5e2d211 100644 --- a/yeto/dashboard/static/topology_diloco.js +++ b/yeto/dashboard/static/topology_diloco.js @@ -23,6 +23,9 @@ function esc(s){return U.esc(s)} function lr(x){return fin(x)?(x===0?"0":x.toExponential(0)):null} function kn(v){return !fin(v)?"n/a":v>=1e9?(v/1e9).toFixed(1)+"B":v>=1e6?(v/1e6).toFixed(1)+"M":v>=1e4?(v/1e3).toFixed(1)+"k":v.toFixed(0)} function now(){return T?T.now+(U.clock()-recvAt)/1000:0} +// the time a spare-node wait or a replacement is measured against, the same on the card, its tip and the +// Islands now table: a snapshot's own time offline, the topology's clock live +function spNow(){return T?(T.live?now():T.now):null} function colors(){var cs=typeof getComputedStyle==="function"?getComputedStyle(document.documentElement):null,o={},g=function(n){return cs&&cs.getPropertyValue?String(cs.getPropertyValue(n)||"").trim():""}; ["ink","ink2","line","good","warn","bad","traj","wt","delta","bg"].forEach(function(k){o[k]=g("--"+k)});o.wire=g("--topo-wire");return o} function arch(a){return a?"var(--arch-"+String(a).toLowerCase()+")":"var(--ink2)"} @@ -70,6 +73,7 @@ function islandNow(tr){var n=tr.island_now;if(!n)return null; moving:[(n.reason||"moving").replace(/^moving to /,"moving → ")+(n.detail&&/^new launch ordering/.test(n.detail)?" · ordering":""),"warn"],starting:[(n.reason||"starting")+(fin(n.incarnation)?" · incarnation "+n.incarnation:""),"warn"]}[n.state]||null} function trainerState(tr,tn,isl){ var age=fin(tr.phase_since)?tn-tr.phase_since:null,a=age!=null?" · "+dur(age):"",ph=tr.phase_raw,co=isl&&isl.colocated; + if(waitingSpare(tr))return ["waiting for a spare node"+(absentWait(tr)?" · counts as absent":fin(tr.spares.since)?" · "+dur(Math.max(0,spNow()-tr.spares.since)):""),"warn"]; var inow=islandNow(tr);if(inow)return inow; if(tr.failure)return["failed: "+tr.failure.metric,"bad"]; if(sft()){var q=fin(tr.last_event_ts)?dur(tn-tr.last_event_ts)+" ago":"n/a"; @@ -90,6 +94,59 @@ function rolloutState(tr,tn){ if(ph==="publish")return["loading the new snapshot"+(age!=null?" · "+dur(age):""),"wt"]; if(ph==="onload")return["onloading weights","wt"]; return[r.colocated?"offloaded · GPU is training":"idle · trainer step (serial)","mute"]} +// a resident ssh: island with spare nodes (tr.spares: its record's, else its fleet.jsonl events) and its +// nodes' health checks (tr.node_health: the nodes whose newest check is not ok) +var ENDED_NOW=/^(stopped|done|down|removed|failed|abandoned)$/; +function ended(tr){return D.done||!!(tr.island_now&&ENDED_NOW.test(tr.island_now.state))} +function waitingSpare(tr){return !!(tr.spares&&tr.spares.waiting&&!ended(tr))} +function lostNode(tr){return !ended(tr)&&(tr.node_health||[]).some(function(h){return h.verdict==="lost"})} +// a wait past fleet.waiting_absent_after_s (the fleet counts the island absent; it still waits) +function absentWait(tr){return waitingSpare(tr)&&(tr.spares.wait_state||{}).state==="absent"} +// a wait not believed (past --spare-max-wait-s, or no report for an hour): the island reads lost +function overdueWait(tr){var w=(tr.spares||{}).wait_state;return !ended(tr)&&!!w&&w.state!=="absent"?w:null} +// the badge of a lost node (a wait is the card's phase line, not a badge too) +function spareBadge(tr){return lostNode(tr)?["node ✕",C.bad]:null} +// why no spare node (island_spares.Pick.why_none): the skipped nodes and why first (what to act on: a +// lease, a quarantine), then the group, then the placement; any other reason as it is +function whyNoSpare(r){r=String(r||"");var i=r.indexOf("; placement: "),head=i<0?r:r.slice(0,i),place=i<0?"":r.slice(i+13); + var m=/^(?:fabric group (\S+)|the inventory) has no free healthy spare node(?: \((.*)\))?$/.exec(head); + if(!m)return r||"no free spare node"; + return (m[2]?m[2]+" · ":"")+"no free spare"+(m[1]?" in "+m[1]:"")+(place?" · placement: "+place:"")} +// a node's health in words: its reasons, else what its verdict means +var VERDICT_WORDS={lost:"health bad in 2 checks in a row",bad_once:"health bad in 1 check",read_failed:"health unread"}; +function healthWhy(h){if(h.stale)return "health unread (stale)";if(h.verdict==="read_failed")return "health unread"+(h.reasons.length?" ("+h.reasons[0]+")":""); + return (h.reasons.length?h.reasons.join("; "):VERDICT_WORDS[h.verdict]||"health check not ok")+(h.verdict==="bad_once"&&h.reasons.length?" · 1 bad check":"")} +// the card's spare / health line: [[text, colour key]] parts (a bad node and why first, then the replacements), +// or null; waiting: why no spare is free; stopped: why the island gave up +function spareNote(tr,tn){var sp=tr.spares,bad=ended(tr)?[]:tr.node_health||[],out=[]; + if(sp&&sp.stopped)return [[sp.stopped,"bad"]]; + var od=overdueWait(tr);if(od)return [[od.why,"bad"]]; + if(waitingSpare(tr))return [[whyNoSpare(sp.reason),"warn"]]; + if(bad.length){var h=bad[0];out.push([h.node+": ",""],[healthWhy(h),h.verdict==="lost"?"bad":"warn"]); + if(bad.length>1)out.push([" +"+(bad.length-1)+" node"+(bad.length>2?"s":""),""])} + if(sp&&sp.replacements>0){var l=sp.last||{}; + out.push([(out.length?" · ":"")+"replaced "+sp.replacements+"×"+(l.lost&&l.spare?" · "+l.lost+" → "+l.spare:"")+(fin(sp.last_at)?" · "+dur(Math.max(0,spNow()-sp.last_at))+" ago":""),""])} + return out.length?out:null} +// rich text cut to maxW (an ellipsis on the part where it ends), the whole line on hover +function fitRich(e,parts,maxW){var full=parts.map(function(p){return p[0]}).join(""),key=full+"|"+parts.map(function(p){return p[1]}).join(",")+"|"+maxW; + if(e._rich===key)return;e._rich=key;e._full=null; + var cap=Math.max(8,Math.floor(maxW/6.3)),n=0,out=[]; + for(var i=0;icap)t=t.slice(0,Math.max(1,cap-n-1))+"…";out.push([t,parts[i][1]?"fill:"+col(parts[i][1]):""]);n+=t.length} + rich(e,out); + if(full.length>cap&&typeof document!=="undefined"&&document.createElementNS&&e.namespaceURI){var tt=document.createElementNS(e.namespaceURI,"title");tt.textContent=full;e.appendChild(tt)}} +// the trainer tip's rows of its spare nodes and unhealthy nodes (a 400 px touch page reads them here) +function spareRows(tr){var sp=tr.spares,h="",tn=spNow(),ws=(sp||{}).wait_state; + (tr.node_health||[]).forEach(function(x){h+=row("node "+x.node,(x.verdict==="lost"?"lost · ":"")+healthWhy(x))}); + if(!sp)return h; + if(sp.stopped)h+=row("spare nodes",sp.stopped); + if(sp.waiting||ws)h+=row("waiting for a spare",(fin(sp.since)?dur(Math.max(0,tn-sp.since))+" · ":"")+(sp.reason||"no free spare node")); + if(ws)h+=row("spare wait",ws.state==="absent"?"counts as absent for the fleet (past fleet.waiting_absent_after_s)":ws.why); + if(sp.lost&&sp.lost.length)h+=row("lost node(s)",sp.lost.join(", ")); + if(sp.replacements>0){var l=sp.last||{}; + h+=row("last replacement",(l.lost&&l.spare?l.lost+" → "+l.spare:"")+(l.resume_step!=null?" · resumed at step "+l.resume_step:"")+(fin(sp.last_at)?" · "+dur(Math.max(0,tn-sp.last_at))+" ago":"")); + h+=row("replacements",sp.replacements+(fin(sp.window)&&fin(sp.max)?" · "+sp.window+" of at most "+sp.max+" in 24 h":""))} + if(sp.spare_nodes&&sp.spare_nodes.length)h+=row("other nodes of its pool",sp.spare_nodes.join(", ")); + return h} function col(k){return{good:C.good,warn:C.warn,bad:C.bad,wt:C.wt,mute:C.ink2,delta:C.delta}[k]||C.ink2} function shardOf(f){var sh=D.shards;for(var i=0;i=sh[i].lo&&ftr.versions[f]} @@ -351,12 +408,13 @@ function lane(e,k){var c={delta:C.delta,wt:C.wt,warn:C.warn,bad:C.bad}[k];e.styl function active(kk,iid,sh,td){return T.live&&D.flows.some(function(f){return f.k===kk&&f.i===iid&&(sh==null||f.sh===sh)&&f.t0<=td&&Math.max(f.t1,f.t0+1.3)>=td})} function paint(){ var tn=now(),td=tn-DELAY_S,red=U.reduced(); - D.trainers.forEach(function(tr,k){var o=L.boxes[k],tc=o.tc,st=trainerState(tr,tn,tr.island),c=col(st[1]),dead=!tr.live&&!(tr.status==="done"||tr.status==="stopped"||tr.finalized||D.done)&&!(tr.island_now&&/^(moving|starting)$/.test(tr.island_now.state)); // a finished run: no trainer is lost + D.trainers.forEach(function(tr,k){var o=L.boxes[k],tc=o.tc,st=trainerState(tr,tn,tr.island),c=col(st[1]),dead=!tr.live&&!(tr.status==="done"||tr.status==="stopped"||tr.finalized||D.done)&&!(tr.island_now&&/^(moving|starting)$/.test(tr.island_now.state))&&!waitingSpare(tr); // a finished run: no trainer is lost tc.step.textContent=(fin(tr.step)?"step "+tr.step:fleet()?"not trained yet":"step —")+(sft()&&fin(tr.steps_total)?" / "+tr.steps_total:"");tc.outer.textContent=fin(tr.outer)?(L.W<640?"sweep ":"outer sweep ")+tr.outer:""; // complete sweeps it applied (hover: the card's tip) fitText(tc.ph,st[0],tc.phw);tc.ph.style.fill=st[1]==="good"?C.ink:c;tc.dot.setAttribute("fill",c); tc.badge.textContent=tr.failure?(/hash/.test(tr.failure.metric)?"hash ✕":/lr/.test(tr.failure.metric)?"lr 0":"failed"):tr.lr_zero&&tr.live?"lr 0":dead?"lost":tr.syncer_link&&tr.syncer_link.state==="disconnected"&&!D.done&&!(tr.island_now&&/^(moving|starting)$/.test(tr.island_now.state))?"link ✕":"";tc.badge.style.fill=C.bad; [tc.co?o.merged:tc.box].forEach(function(b){if(b){b.style.stroke=dead||tr.failure?C.bad:"";b.style.strokeDasharray=dead?"5 4":""}}); o.tc.g.setAttribute("opacity",dead?0.6:1); + var sb=spareBadge(tr);if(sb&&!/^(failed|hash ✕|lr 0)$/.test(tc.badge.textContent)){tc.badge.textContent=sb[0];tc.badge.style.fill=sb[1]} // a lost node / no spare node var L0=tc.l,lw=tc.lw; fitText(L0[0],(tr.hash?"snapshot "+tr.hash:"no snapshot yet")+(lr(tr.lr)!=null?" · lr "+lr(tr.lr):""),lw); if(tr.versions){var parts=[["frag [",""]];tr.versions.forEach(function(v,f){var b=behind(tr,f);parts.push([String(v),b?"fill:"+C.warn+";font-weight:700":""]);if(f=0&&td-tr.apply_ts<3;tc.flash.style.stroke=C.wt;tc.flash.setAttribute("opacity",ap?0.9:0); if(o.ro)paintRollout(tr,o,tn,td); if(o.lat){var ln=(D.lanes||{})[tr.id]||{};o.lat.textContent=fin(ln.latest)?"v"+ln.latest:"no release";o.buf.textContent=fin(ln.backlog)?"buffer "+Math.round(ln.backlog):"written "+Math.round(ln.written||0); @@ -405,7 +464,7 @@ function paint(){ if(!fin(sw0)||sw0<=0)sw0=pre.length*6.3+big.length*12.2; // no layout: the small and big fonts' advances if(fi===forms.length-1||14+sw0+16+textW(o.of,5.9)<=o.w-12)break}} o.barf.setAttribute("width",D.P?(o.barW*(((sh.step-1)%D.P+1)/D.P)).toFixed(1):0); - o.roster.textContent=D.done?"run done · roster "+D.M:"roster "+D.roster+"/"+D.M;o.roster.style.fill=D.done?C.ink2:D.roster=D.M?C.warn:C.bad):C.good; var c=st==="done"?C.ink2:st==="waiting for quorum"?(sh.attempt_max>1?C.bad:C.warn):st==="merging"?C.wt:st==="gathering"?C.good:C.ink2; var ended=mine.length&&mine.every(function(r){return r.ended}); fitText(o.st,(st==="done"?"done (final cut)":st==="stale"?"stale: no trainer up":st)+(ended?" · "+mine.length+" unmerged at the end":st==="done"&&!mine.length?"":" · in flight "+mine.length)+(D.behind&&D.syncer_tape!==false?" · syncer tape behind":""),o.lw-14);o.st.style.fill=c===C.good?C.ink:c;o.dot.setAttribute("fill",c); @@ -542,7 +601,7 @@ function tipHtml(key){var a=key.split(":"),tn=now(),tr=null;D.trainers.forEach(f if(a[0]==="trn"&&tr)return '
Trainer '+esc(tr.id)+"
"+row("island status",tr.status)+row("local step",tr.step)+row("outer sweep",fin(tr.outer)?tr.outer+": every fragment merged at least "+tr.outer+" time"+(tr.outer===1?"":"s")+" (complete sweeps applied)":null)+row("policy hash",tr.hash)+ row("fragment versions",tr.versions?"["+tr.versions.join(", ")+"]":null)+row("merged, not applied",tr.pending_n)+row("applied lr",lr(tr.lr))+ row("last PUSH",tr.last_push?"f"+tr.last_push.frag+" t"+tr.last_push.step+" · "+mb(tr.last_push.bytes)+(tr.last_push.wire?" on the wire ("+mb(tr.last_push.payload_bytes)+" f32)":""):null)+ - row("BCAST overwrite / catch-up",tr.bcast_overwrites||tr.bcast_catch_ups?(tr.bcast_overwrites||0)+" / "+(tr.bcast_catch_ups||0):null)+row("last event",fin(tr.last_event_ts)?dur(tn-tr.last_event_ts)+" ago":null)+ + row("BCAST overwrite / catch-up",tr.bcast_overwrites||tr.bcast_catch_ups?(tr.bcast_overwrites||0)+" / "+(tr.bcast_catch_ups||0):null)+row("last event",fin(tr.last_event_ts)?dur(tn-tr.last_event_ts)+" ago":null)+spareRows(tr)+ row("source",tr.full_push?"rl_full_parameter_round · rl_fragment_*":"rl_local_round · rl_policy_snapshot · rl_fragment_*")+'
PULL permits held and live BCAST queueing are not on the tapes yet
'; if(a[0]==="rol"&&tr&&tr.island){var r=tr.island;return '
Island '+esc(tr.id)+" rollout ("+esc(r.placement||"placement n/a")+")
"+row("execution mode",r.exec_mode)+row("engines",r.engines)+row("rollout round",r.round)+ row("serving",r.served?r.served.token:null)+row("groups / traj / tokens",[r.groups,r.traj,r.tokens].join(" / "))+row("rollout seconds",fin(r.rollout_s)?r.rollout_s.toFixed(1):null)+ @@ -607,7 +666,8 @@ function render(view,offline){ var W=host.clientWidth||800; if(!L||L.shape!==shape()||vw(L.W)!==vw(W)||(host.contains&&!host.contains(L.svg)))build(host); var live=D.trainers.filter(function(x){return x.live}).length,rolls=D.trainers.filter(function(x){return x.island}).length; - $("topoNote").textContent="layout: "+D.kind.replace("_"," ")+" ("+D.layout_reason+") · "+(sft()?D.trainers.length+" learner island(s), no rollout":D.kind==="island"?rolls+" island(s): trainer + in-island rollout":(t.samplers||[]).filter(function(s){return s.live}).length+" live sampler(s)"+(D.fleet?" in "+D.fleet.islands.length+" island(s)":""))+" · "+live+"/"+D.M+(sft()?" learner(s)":" trainer(s)")+" live · syncer "+(D.shards.length>1?D.shards.length+" shards":"1 process")+ + if(D.roster_spare)live=D.roster; // an island out of the roster while a spare takes a lost node's place is not live + $("topoNote").textContent="layout: "+D.kind.replace("_"," ")+" ("+D.layout_reason+") · "+(sft()?D.trainers.length+" learner island(s), no rollout":D.kind==="island"?rolls+" island(s): trainer + in-island rollout":(t.samplers||[]).filter(function(s){return s.live}).length+" live sampler(s)"+(D.fleet?" in "+D.fleet.islands.length+" island(s)":""))+" · "+live+"/"+D.M+(sft()?" learner(s)":" trainer(s)")+" live"+(D.roster_spare?" ("+D.roster_spare+" replacing a lost node)":"")+" · syncer "+(D.shards.length>1?D.shards.length+" shards":"1 process")+ (t.live?" · replayed "+DELAY_S+" s behind the newest tape data":" · offline snapshot"); paint();kick(); if(!bound){bound=true;host.addEventListener("mousemove",tip);host.addEventListener("mouseleave",function(){var tp=$("topoTip");if(tp)tp.style.display="none"}); @@ -620,7 +680,7 @@ function render(view,offline){ function ago(t,tn){return fin(t)?dur(tn-t)+" ago":"n/a"} function kpis(view,kp){ var t=view&&view.topology,d=t&&t.diloco;if(!d)return kp;U=YetoTopo.util; - var tn=(view.overview||{}).now||t.now,trs=d.trainers,isl=d.kind==="island",live=trs.filter(function(x){return x.live}).length,rolls=trs.filter(function(x){return x.island}); + var tn=(view.overview||{}).now||t.now,trs=d.trainers,isl=d.kind==="island",live=d.roster_spare?d.roster:trs.filter(function(x){return x.live}).length,rolls=trs.filter(function(x){return x.island}); var eng=rolls.reduce(function(a,x){return a+(x.island.engines||0)},0),pls={};rolls.forEach(function(x){if(x.island.placement)pls[x.island.placement]=1}); var pl=Object.keys(pls),co=rolls.some(function(x){return x.island.colocated}); var pct=function(x){return fin(x)?Math.round(100*x)+"%":"—"},sh=d.shards[0]||{},open=d.rounds.filter(function(r){return !r.ended}).length,pend=trs.filter(function(x){return x.live}).reduce(function(a,x){return a+x.pending_n},0); @@ -649,5 +709,5 @@ function table(view){var d=view&&view.topology&&view.topology.diloco;if(!d)retur return (p?"↑ f"+p.frag+" t"+p.step+" · "+dur(tn-p.ts)+" ago":t.full_push?"↑ "+(t.full_push.count||0)+" PUSH last round, "+(t.full_push.total||0)+" in the run"+(t.full_push.overwritten?" · overwritten "+t.full_push.overwritten:""):"↑ none")+'
'+(b?"↓ f"+b.frag+" v"+b.v+" applied"+(fin(t.apply_s)?" · apply "+t.apply_s.toFixed(2)+"s":""):t.full_push?"↓ applied in the round (no per-fragment record yet)":"↓ no BCAST applied yet")+"
"+ '
frag ['+(t.versions||[]).join(" ")+"]
"}}} -return{render:render,kpis:kpis,table:table}; +return{render:render,kpis:kpis,table:table,whyNoSpare:whyNoSpare,healthWhy:healthWhy,spNow:spNow}; })(); diff --git a/yeto/dashboard/topology_diloco.py b/yeto/dashboard/topology_diloco.py index 4009e4be3..cd9da1f3a 100644 --- a/yeto/dashboard/topology_diloco.py +++ b/yeto/dashboard/topology_diloco.py @@ -380,6 +380,17 @@ def config_summary(configs: dict[int, dict]) -> dict | None: "step0": _int(c.get("global_step")), "ts": c.get("_ts")} +def _replacing(card: dict | None) -> bool: + """A resident ssh: island that lost a node: waiting for a spare node or starting on one.""" + sp = (card or {}).get("spares") or {} + return bool(sp.get("waiting") or sp.get("lost")) + + +def _overdue(card: dict | None) -> bool: + """A wait for a spare node the page does not believe (past the longest wait, or unreported).""" + return ((((card or {}).get("spares") or {}).get("wait_state") or {}).get("state")) in ("expired", "frozen") + + def _quiet_move(inow: dict | None, now: float) -> bool: """Whether a trainer island's record says it is moving or relaunching, for no longer than MOVE_QUIET_S (one stuck in ordering or starting longer than that raises the stuck and @@ -451,6 +462,11 @@ def view(reducer, cards: list[dict], now: float, kind_: str) -> dict: versions, committed, merged_steps, expected = sy["versions"], sy["committed"], sy["merged_steps"], sy["expected"] m_size = len(expected) or len(trainer_ids) live = [i for i in trainer_ids if (states.get(i) or {}).get("alive")] + # a resident ssh: island that lost a node (stopped, waiting for a spare or starting on one) is out of the + # roster: the syncer merges without it until it is back + roster = [i for i in live if not _replacing(by_id.get(i))] + # trainers out of it only while a spare takes a lost node's place (a warning, not a loss) + roster_spare = sum(1 for i in trainer_ids if _replacing(by_id.get(i)) and not _overdue(by_id.get(i))) # rounds in flight: PUSHes of steps the owner shard has not committed yet (a PULL without a # PUSH is not on the tapes) @@ -543,7 +559,7 @@ def view(reducer, cards: list[dict], now: float, kind_: str) -> dict: "quorum": sy["quorum"], "versions": versions, "last_merge_ts": sy["last_merge_ts"], "behind": behind, "syncer_tape": tape_seen, "inferred_versions": inferred, "stuck": stuck, "period_s": sy["period_s"], "merge_gap_s": sy["merge_gap_s"], "quorum_p50_s": sy["quorum_p50_s"], - "roster": len(live), "expected": expected, "shards": shard_rows(p, n, merges, rounds, committed, done), + "roster": len(roster), **({"roster_spare": roster_spare} if roster_spare else {}), "expected": expected, "shards": shard_rows(p, n, merges, rounds, committed, done), "rounds": rounds, "last_merge_ts_any": sy["last_merge_ts_any"], "running": running, "done": done, "traffic": {"push": len(pushes5), "push_bytes": sum(_push_bytes(x) or 0 for x in pushes5), "bcast": len(bcasts5)}, @@ -790,6 +806,8 @@ def _trainer(iid: str, x: _Island, card: dict, st: dict, merges: list[dict], ver "truncated": x.truncated[-1] if x.truncated else None, "island": roll, "nodes": _nodes(x, card, roll, now), + # a resident ssh: island: its spare nodes and its unhealthy nodes (no key without them) + **{k: card[k] for k in ("spares", "node_health") if k in card}, } diff --git a/yeto/launch/fleet.py b/yeto/launch/fleet.py index 35f1be93f..5fd993b66 100644 --- a/yeto/launch/fleet.py +++ b/yeto/launch/fleet.py @@ -639,9 +639,11 @@ def _island_health(self, rec): @staticmethod def _health_key(health): - """What a change of the health record is judged by (verdicts and reasons, not times).""" + """What a change of the health record is judged by (verdicts and reasons, not times; and + whether a node's check is the one kept over a relaunch, ``reset``: the first check of the + new job writes the record again, so its time is the new job's).""" nodes = (health or {}).get("nodes") or {} - return tuple(sorted((name, doc.get("verdict"), tuple(doc.get("reasons") or ())) + return tuple(sorted((name, doc.get("verdict"), tuple(doc.get("reasons") or ()), bool(doc.get("reset"))) for name, doc in nodes.items())) def _health_events(self, rec) -> None: diff --git a/yeto/launch/ssh_resident.py b/yeto/launch/ssh_resident.py index ad9696a3b..74362072b 100644 --- a/yeto/launch/ssh_resident.py +++ b/yeto/launch/ssh_resident.py @@ -1171,7 +1171,7 @@ def spares_view(self, name: str) -> dict[str, Any] | None: "wait_reason": sp.wait_reason, "waiting_since": sp.wait_since if sp.waiting else None, "replacements": len(sp.replacements), "replacements_window": len(sp.recent(self.wall())), "max_replacements": int(sp.max_replacements), - "last_replaced_at": None if last is None else last.get("at")} + "last_replaced_at": None if last is None else last.get("at"), "max_wait_s": float(sp.max_wait_s)} def _node_log_tail(self, rec: _Island, reason: str, lines: int = 20) -> str: """The last lines of the failed rank's local log copy (rank > 0)."""