From 0a07f03e0f0c5714db98ebce3bf3ca9d3ab7f75c Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 15:57:58 +0800 Subject: [PATCH 01/13] fleet: an island none of whose pushes is merged in N merge cycles is reported (island_straggler) The syncer already merges the other islands at each quorum deadline and excuses a silent island (#865); nobody said that the island had stopped contributing. The fleet controller now reads the syncer's merges (its tape on this host, or the copy the syncer launch uploads to the run store, tapes/syncer/) and writes island_straggler once per stretch, in fleet.jsonl and in the island's record, when no push of a running island was merged in N merge cycles (one outer step of every fragment; --rl-island-straggler-cycles, default 3, 0 off). island_straggler_cleared follows once a push of it is merged again. Counting starts at the island's join after a (re)launch. A policy decides what to do: wait by default (nothing is stopped or relaunched), or a replacement its provider offers. Tests: the tracker and its sources (local tape, store chunks across syncer incarnations); the controller's event, record and policy; and an end-to-end CPU test of ssh: trainer islands (the launcher's fleet controller over the resident ssh ops on a fake SSH cluster, the trainer worker on a local store, the real syncer): a third island added, one removed, and one stuck while connected. In each case the other islands' processes never restart, the merged steps run without a gap or a repeat, no push is merged twice and the resource ledger holds each ssh incarnation once. docs/OWN_CLUSTERS.md: "Islands that lag, join or leave". Co-Authored-By: Claude Opus 5.5 --- docs/OWN_CLUSTERS.md | 74 +++++ tests/test_island_straggler.py | 331 ++++++++++++++++++++ tests/test_own_clusters_islands_doc.py | 64 ++++ tests/test_ssh_island_fleet_e2e.py | 399 +++++++++++++++++++++++++ yeto/launch/fleet.py | 64 ++++ yeto/launch/island_straggler.py | 346 +++++++++++++++++++++ yeto/launch/rl_args.py | 3 + yeto/launcher.py | 23 ++ yeto/rl/engine/run_flags.py | 5 + 9 files changed, 1309 insertions(+) create mode 100644 tests/test_island_straggler.py create mode 100644 tests/test_own_clusters_islands_doc.py create mode 100644 tests/test_ssh_island_fleet_e2e.py create mode 100644 yeto/launch/island_straggler.py diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 81b716d6d..fab94e271 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -477,3 +477,77 @@ constraint. it was. `yeto cluster probe` and `yeto cluster check` always print the note. To drop the rule, delete the `fabric_group` lines. + +## Islands that lag, join or leave + +A fleet of `ssh:` trainer islands on your own machines uses the same fleet mechanisms as any +other island fleet ([FLEET_TRAINER_ISLANDS.md](FLEET_TRAINER_ISLANDS.md)). This section +covers what is specific to `ssh:` islands: how a slow or stuck island is reported, and what +happens when one leaves. + +### An island that lags + +An island can fall behind or stop pushing while its process and its connection stay up: a +slow node, a hung collective, a trainer that waits on something. The syncer does not wait +for it. When a round's quorum deadline passes, the syncer merges the pushes that arrived and +records the silent island as absent. Later rounds do not wait for it either. Once the island +delivers again, its late push is carried into a later round with a discount, or refused when +it lags past `--rl-sync-max-base-lag`. The island then catches up to the newest merged +weights and answers rounds again. The other islands keep merging the whole time. + +The island's fleet controller reports such an island. It reads the syncer's merges, and +when none of the island's pushes was merged in `N` merge cycles it writes: + +- `island_straggler` in the launch's `fleet.jsonl`, with `missed_cycles`, `merges`, + `fragments`, `last_merged_step`, `newest_step`, `absent` and `action`; +- the same fields under `straggler` in the island's record (`fleet/trainers//state.json`, + shown by `yeto island status`). + +A merge cycle is one outer step of every fragment, so with 4 fragments and `N = 3` the +island is reported after 12 merges without it. Counting starts when the island joins the +syncer after a launch or relaunch, so the time an island takes to start is not counted. A +push the syncer refused does not count as merged. The report is written once per stretch. +`island_straggler_cleared` follows once a push of the island is merged again, and its record's +`straggler` is set back to `null`. + +`action` is what the controller does about it. The default is `wait`: nothing is stopped or +relaunched, because the syncer already merges without the island. A lost or unhealthy node +is handled by the island's own launch, not by this report. + +Set `N` in `fleet.trainer_argv`, so every island launch gets the same value: + +```json +"trainer_argv": ["...", "--rl-island-straggler-cycles", "3"] +``` + +`3` is the default. `0` turns the report off. The value must be a whole number of 0 or more; +`yeto launch --dry-run` refuses anything else. + +The controller reads the syncer's tape in one of two places: + +- from the syncer's own file, when the syncer runs on the same host as the controller + (`--controller head`); +- otherwise from its copy in the run store, `tapes/syncer//.jsonl`. The + syncer launch uploads it every 30 s (`YETO_RL_TAPE_UPLOAD_S`) when `--rl-checkpoint-store` + is an `s3://` store. With another store, or with the upload off (`YETO_RL_TAPE_UPLOAD_S=0`), + the launch prints `island straggler watch off` and nothing is reported. Training is not + affected either way. + +The report comes at most one upload interval after the merges it counts. + +### Removing an island + +```bash +yeto fleet island remove --config run.json --name north --dry-run +yeto fleet island remove --config run.json --name north +``` + +The trainer worker writes the island's STOP. The island's controller drains it, stops the +trainer on every node (and checks that each container is gone), and records the island +`done`. Its incarnation is closed in the run's resource ledger. The syncer sees the island's +connection drop. The round it was asked for waits one island lease and then merges over the +islands left. The island's nodes are free for another island afterwards. + +In a fleet launched as one launch (`fleet.launch: synced_group`), islands cannot be added +while it trains. One island can be stopped and started again by its learner id, for example +island 1 with `yeto island stop 1 --config run.json` and `yeto island start 1 --config run.json`. diff --git a/tests/test_island_straggler.py b/tests/test_island_straggler.py new file mode 100644 index 000000000..416772f93 --- /dev/null +++ b/tests/test_island_straggler.py @@ -0,0 +1,331 @@ +"""Island stragglers (own-cluster-fleet-stability 9.1): an island none of whose pushes the +syncer merged in N merge cycles is written as ``island_straggler`` by the fleet controller, +once per stretch, and cleared once a push of it is merged again. The tracker reads the +syncer's tape (a local file or its copy in the run store); the controller asks its policy +whether to wait (default) or replace, and the other islands are not touched.""" + +from __future__ import annotations + +import json +import types + +import pytest + +from test_controller import RUNNING, SYNCER, FakeOps, ImmediateThread +from yeto.launch import island_lifecycle as lc +from yeto.launch import island_straggler as st +from yeto.launch.fleet import FleetController +from yeto.rl.engine.object_store import DirectoryObjectStore + + +def _step(step, merged, *, fragments=2, absent=()): + return {"kind": "outer_step", "step": step, "fragment": (step - 1) % fragments, + "weights": [[k, step - 1, 1.0 / len(merged)] for k in merged], + "raw_weights": [[k, step - 1, 1.0] for k in merged], "absent": list(absent)} + + +def _join(k): + return {"kind": "pool_join", "island_id": k, "generation": 0, "catch_up": False, "base_version": 0} + + +RUN2 = {0: (0, 1), 1: (0, 1)} + + +def test_an_island_merged_in_no_round_for_n_cycles_is_a_straggler_once_then_cleared(): + tracker = st.StragglerTracker(cycles=3) + for k in (0, 1): + tracker.feed(_join(k)) + step = 0 + for _ in range(4): # both islands merged: nothing + step += 1 + tracker.feed(_step(step, [0, 1])) + assert tracker.check(RUN2) == [] + signals = [] + for _ in range(6): # island 1 silent: 3 cycles of 2 fragments + step += 1 + tracker.feed(_step(step, [0], absent=[1])) + signals += tracker.check(RUN2) + (signal,) = signals + assert signal.island == 1 and not signal.cleared and signal.missed_cycles == 3 and signal.merges == 6 + assert signal.fragments == 2 and signal.cycles == 3 and signal.absent and signal.newest_step == step + assert signal.last_merged_step == 4 and "3 merge cycle(s)" in signal.reason + for _ in range(4): # still silent: no second event for the same stretch + step += 1 + tracker.feed(_step(step, [0], absent=[1])) + assert tracker.check(RUN2) == [] + step += 1 + tracker.feed(_step(step, [0, 1])) # a push of it is merged again (a late push carried in) + (cleared,) = tracker.check(RUN2) + assert cleared.island == 1 and cleared.cleared and cleared.last_merged_step == step + + +def test_one_cycle_short_is_not_a_straggler_and_a_merged_push_resets_the_count(): + tracker = st.StragglerTracker(cycles=3) + for k in (0, 1): + tracker.feed(_join(k)) + step = 0 + for _ in range(3): + for _ in range(5): # 5 of the 6 merges without it, then one with it + step += 1 + tracker.feed(_step(step, [0])) + step += 1 + tracker.feed(_step(step, [0, 1])) + assert tracker.check(RUN2) == [] + + +def test_counting_starts_at_the_join_of_the_launch_and_a_relaunch_starts_it_again(): + tracker = st.StragglerTracker(cycles=1) + for step in range(1, 9): # island 1 not joined yet (its launch still starts): nothing counts + tracker.feed(_step(step, [0], fragments=1)) + assert tracker.check(RUN2) == [] + tracker.feed(_join(1)) + tracker.feed(_step(9, [0], fragments=1)) + (signal,) = tracker.check(RUN2) + assert signal.island == 1 and signal.merges == 1 + # relaunched while flagged (a new incarnation token): cleared, and counted from its next join + (cleared,) = tracker.check({0: (0, 1), 1: (1, 2)}) + assert cleared.cleared and cleared.reason == "relaunched" + tracker.feed(_step(10, [0], fragments=1)) + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] + tracker.feed(_join(1)) # a re-JOIN of the same incarnation later does not restart it + tracker.feed(_step(11, [0], fragments=1)) + tracker.feed(_join(1)) + assert [s.island for s in tracker.check({0: (0, 1), 1: (1, 2)})] == [1] + + +def test_only_the_running_islands_are_reported_and_zero_cycles_is_off(): + tracker = st.StragglerTracker(cycles=1) + for k in (0, 1): + tracker.feed(_join(k)) + tracker.feed(_step(1, [0], fragments=1)) + assert tracker.check({0: (0, 1)}) == [] # island 1 draining or recovering: not watched + off = st.StragglerTracker(cycles=0) + for k in (0, 1): + off.feed(_join(k)) + for step in range(1, 20): + off.feed(_step(step, [0], fragments=1)) + assert off.check(RUN2) == [] + + +def test_the_flag_is_a_whole_number_of_cycles(): + assert st.straggler_cycles(types.SimpleNamespace()) == 3 + assert st.straggler_cycles(types.SimpleNamespace(rl_island_straggler_cycles=5)) == 5 + assert st.straggler_cycles(types.SimpleNamespace(rl_island_straggler_cycles=0)) == 0 + with pytest.raises(ValueError, match="whole number >= 0"): + st.straggler_cycles(types.SimpleNamespace(rl_island_straggler_cycles=-1)) + + +def test_the_flag_is_checked_with_the_island_pool_options(monkeypatch): + from yeto.cli import build_parser + from yeto.launch import rl_args + + base = ["launch", "--training-mode", "rl", "--model", "m", "--data", "d"] + assert build_parser().parse_args([*base, "--rl-island-straggler-cycles", "4"]).rl_island_straggler_cycles == 4 + assert build_parser().parse_args(base).rl_island_straggler_cycles is None + monkeypatch.setattr(rl_args, "rl_needs_critic", lambda args: False) + args = types.SimpleNamespace(training_mode="rl", rl_sync_island_lease_s=30.0, rl_sync_preset="strict-avg", + experimental_rl_sync=False, syncer_shards=None, rl_island_straggler_cycles=-2) + with pytest.raises(ValueError, match="--rl-island-straggler-cycles must be a whole number"): + rl_args._check_island_pool(args, num_islands=2) + + +# -- the syncer's tape --------------------------------------------------------------------------- + +def test_the_local_tape_is_read_line_by_line_from_its_offset(tmp_path): + tape = tmp_path / "tape.jsonl" + tape.write_text(json.dumps(_join(9)) + "\n") + source = st.FileTape(tape, offset=tape.stat().st_size) # an earlier syncer job's records + assert source.read() == [] + with tape.open("a") as fh: + fh.write(json.dumps(_join(0)) + "\n" + '{"kind": "outer_st') # the syncer mid-write + assert source.read() == [_join(0)] + with tape.open("a") as fh: + fh.write('ep", "step": 1}\nnot json\n') + assert source.read() == [{"kind": "outer_step", "step": 1}] + assert st.FileTape(tmp_path / "missing.jsonl").read() == [] + + +def test_the_store_tape_reads_each_chunk_once_in_the_order_the_syncers_started(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + late, early = "hostb-20261126T120000Z", "hosta-20261126T130000Z" # by name the restart sorts first + objects.write(f"tapes/syncer/{late}/00000000.jsonl", (json.dumps(_join(0)) + "\n").encode()) + objects.write(f"tapes/syncer/{early}/00000000.jsonl", (json.dumps(_step(1, [0])) + "\n").encode()) + objects.write("tapes/syncer-shard1/x/00000000.jsonl", b'{"kind": "outer_step"}\n') # not this tape + objects.write("tapes/l0-host-20261126T120000Z/00000000.jsonl", b'{"event": "rl_local_round"}\n') + clock = [0.0] + source = st.StoreTape(objects, interval_s=30, clock=lambda: clock[0]) + assert source.read() == [_join(0), _step(1, [0])] + objects.write(f"tapes/syncer/{early}/00000001.jsonl", (json.dumps(_step(2, [0])) + "\n").encode()) + assert source.read() == [] # within the poll interval: no request + clock[0] = 31.0 + assert source.read() == [_step(2, [0])] + clock[0] = 62.0 + assert source.read() == [] + + +def test_a_watch_whose_tape_does_not_read_logs_once_and_goes_on(): + lines = [] + + class Broken: + label = "s3://b/runs/r/tapes/syncer/" + + def read(self): + raise OSError("store down") + + watch = st.StragglerWatch(Broken(), cycles=1, log=lines.append) + assert watch.poll(RUN2) == [] and watch.poll(RUN2) == [] + assert len(lines) == 1 and "store down" in lines[0] + + +def test_the_launcher_watches_an_island_pool_only(tmp_path): + lines = [] + pool = types.SimpleNamespace(training_mode="rl", rl_sync_island_lease_s=30.0) + assert st.watch_for(types.SimpleNamespace(training_mode="rl"), objects=object(), log=lines.append) is None + assert st.watch_for(types.SimpleNamespace(**vars(pool), rl_island_straggler_cycles=0), objects=object(), + log=lines.append) is None + assert st.watch_for(pool, log=lines.append) is None and "watch off" in lines[-1] + watch = st.watch_for(pool, local_tape=tmp_path / "tape.jsonl", objects=object(), log=lines.append) + assert isinstance(watch.source, st.FileTape) and watch.tracker.cycles == 3 + watch = st.watch_for(pool, objects=DirectoryObjectStore(tmp_path / "s"), log=lines.append) + assert isinstance(watch.source, st.StoreTape) + + +# -- the fleet controller ------------------------------------------------------------------------ + +class ScriptedTape: + label = "test tape" + + def __init__(self): + self.pending: list[dict] = [] + + def read(self): + out, self.pending = self.pending, [] + return out + + +class Recorder: + def __init__(self): + self.events = [] + + def event(self, kind, name, **fields): + self.events.append((kind, name, fields)) + + def maybe_tick(self): + pass + + def cost_tick(self): + pass + + +def _controller(tmp_path, *, policy=None, cycles=1): + ops = FakeOps() + ops.status_seq.update({SYNCER: [RUNNING], "r-l0": [RUNNING], "r-l1": [RUNNING]}) + store = lc.IslandStateStore(DirectoryObjectStore(tmp_path / "store")) + refs = {f"r-l{k}": lc.IslandRef(k, "ssh") for k in (0, 1)} + tape, log = ScriptedTape(), Recorder() + ctl = FleetController(learners={n: (f"task-{n}", 1) for n in refs}, syncer=(SYNCER, "task-syncer", 1), + sky_ops=ops, poll_interval=30, recover_timeout=600, thread_cls=ImmediateThread, + recorder=lc.FleetRecorder(store, refs), elastic=True, fleet_log=log, + straggler=st.StragglerWatch(tape, cycles=cycles, log=lambda m: None), + straggler_policy=policy) + return ctl, ops, store, tape, log + + +def test_the_controller_writes_the_straggler_once_waits_and_touches_no_other_island(tmp_path): + ctl, ops, store, tape, log = _controller(tmp_path) + tape.pending += [_join(0), _join(1), _step(1, [0, 1], fragments=1), _step(2, [0], fragments=1, absent=[1])] + ctl._poll_stragglers() + (event,) = [e for e in log.events if e[0] == st.EVENT] + assert event[1] == "r-l1" and event[2]["action"] == st.WAIT and event[2]["missed_cycles"] == 1 + record = store.read(1) + assert record["straggler"]["action"] == "wait" and record["straggler"]["last_merged_step"] == 1 + assert "straggler" not in (store.read(0) or {}) + ctl._poll_stragglers() # nothing new: no second event + assert len([e for e in log.events if e[0] == st.EVENT]) == 1 + tape.pending.append(_step(3, [0, 1], fragments=1)) + ctl._poll_stragglers() + assert [e[:2] for e in log.events if e[0] == st.CLEARED_EVENT] == [(st.CLEARED_EVENT, "r-l1")] + assert store.read(1)["straggler"] is None + assert ops.down_calls == [] and ops.relaunch_calls == [] # waiting stops and relaunches nothing + assert all(rec["state"] == "running" for rec in ctl.learners.values()) + + +def test_a_draining_island_is_not_reported(tmp_path): + ctl, _ops, _store, tape, log = _controller(tmp_path) + ctl.learners["r-l1"]["draining"] = True + tape.pending += [_join(0), _join(1), _step(1, [0], fragments=1), _step(2, [0], fragments=1)] + ctl._poll_stragglers() + assert not [e for e in log.events if e[0] == st.EVENT] + + +def test_the_policy_decides_and_a_replace_is_handed_to_it(tmp_path): + asked, replaced = [], [] + + class Policy: + def __call__(self, name, signal): + asked.append((name, signal.island)) + return st.REPLACE + + def replace(self, name, signal): + replaced.append(name) + + ctl, _ops, store, tape, log = _controller(tmp_path, policy=Policy()) + tape.pending += [_join(0), _join(1), _step(1, [0], fragments=1)] + ctl._poll_stragglers() + assert asked == [("r-l1", 1)] and replaced == ["r-l1"] + assert store.read(1)["straggler"]["action"] == "replace" + + +def test_a_policy_that_fails_or_answers_nonsense_waits(tmp_path): + def broken(name, signal): + raise RuntimeError("no spare") + + ctl, _ops, store, tape, _log = _controller(tmp_path, policy=broken) + tape.pending += [_join(0), _join(1), _step(1, [0], fragments=1)] + ctl._poll_stragglers() + assert store.read(1)["straggler"]["action"] == "wait" + ctl, _ops, store, tape, _log = _controller(tmp_path / "b", policy=lambda name, signal: "reboot") + tape.pending += [_join(0), _join(1), _step(1, [0], fragments=1)] + ctl._poll_stragglers() + assert store.read(1)["straggler"]["action"] == "wait" + + +def test_without_a_watch_the_controller_reads_nothing(tmp_path): + ctl, _ops, _store, _tape, log = _controller(tmp_path) + ctl.straggler = None + ctl._poll_stragglers() + assert log.events == [] + + +def test_a_watch_that_reads_no_syncer_record_says_so_once(): + lines, tape = [], ScriptedTape() + watch = st.StragglerWatch(tape, cycles=1, log=lines.append) + for _ in range(st.QUIET_POLLS + 5): + watch.poll(RUN2) + assert len(lines) == 1 and "no syncer record read from test tape" in lines[0] + lines.clear() + read = st.StragglerWatch(tape, cycles=1, log=lines.append) + tape.pending.append(_join(0)) + for _ in range(st.QUIET_POLLS + 5): + read.poll(RUN2) + assert lines == [] # it read the syncer once: a quiet stretch later is the syncer's, not the source's + + +def test_the_launcher_reads_the_store_copy_for_an_island_launch_only(tmp_path, monkeypatch): + from yeto import launcher + + monkeypatch.delenv("YETO_RL_TAPE_UPLOAD_S", raising=False) + states = types.SimpleNamespace(objects=DirectoryObjectStore(tmp_path / "s")) + base = dict(training_mode="rl", rl_sync_island_lease_s=30.0, rl_checkpoint_store="s3://b/runs/r") + island = types.SimpleNamespace(**base, rl_fleet_role="island") + assert isinstance(launcher._island_straggler_watch(island, states, None).source, st.StoreTape) + group = types.SimpleNamespace(**base, rl_fleet_role=None) # one launch: its syncer's tape is not uploaded + assert launcher._island_straggler_watch(group, states, None) is None + local = types.SimpleNamespace(event_tape=str(tmp_path / "tape.jsonl"), _event_offset=5) + watch = launcher._island_straggler_watch(group, states, local) + assert isinstance(watch.source, st.FileTape) and watch.source.offset == 5 + assert launcher._island_straggler_watch(island, None, None) is None # no island records: nothing written + monkeypatch.setenv("YETO_RL_TAPE_UPLOAD_S", "0") + assert launcher._island_straggler_watch(island, states, None) is None + with pytest.raises(SystemExit, match="whole number"): + launcher._island_straggler_watch(types.SimpleNamespace(**base, rl_island_straggler_cycles=-1), states, local) diff --git a/tests/test_own_clusters_islands_doc.py b/tests/test_own_clusters_islands_doc.py new file mode 100644 index 000000000..1101815c5 --- /dev/null +++ b/tests/test_own_clusters_islands_doc.py @@ -0,0 +1,64 @@ +"""docs/OWN_CLUSTERS.md, "Islands that lag, join or leave": every command of the section +parses, the ``yeto fleet island`` ones run in the doc's order on a seeded per-island fleet +(local store), each dry run writes nothing, and the flags and events the section names are +the code's.""" + +from __future__ import annotations + +import re +import shlex +from pathlib import Path + +from test_fleet_island_changes import fleet_store # noqa: F401 - fixture +from yeto.launch import island_straggler as st +from yeto.rl import fleet, fleet_islands + +DOC = Path(__file__).resolve().parents[1] / "docs" / "OWN_CLUSTERS.md" +SECTION = "## Islands that lag, join or leave" + + +def section() -> str: + text = DOC.read_text() + start = text.index(SECTION) + end = text.find("\n## ", start + len(SECTION)) + return text[start:] if end < 0 else text[start:end] + + +def commands() -> list[list[str]]: + out = [] + for block in re.findall(r"```bash\n(.*?)```", section(), flags=re.S): + out += [shlex.split(line) for line in block.replace("\\\n", " ").splitlines() if line.strip()] + inline = re.findall(r"`(yeto island (?:stop|start) [^`]+)`", section()) + return out + [shlex.split(c) for c in inline] + + +def test_the_section_names_the_code_s_flags_and_events(): + text = section() + assert "--rl-island-straggler-cycles" in text and f"`{st.DEFAULT_CYCLES}` is the default" in text + for name in (st.EVENT, st.CLEARED_EVENT, st.WAIT, st.SYNCER_TAPES.rstrip("/")): + assert name in text + for field in st.Straggler.__dataclass_fields__: + if field not in ("island", "cleared", "cycles", "reason"): + assert f"`{field}`" in text, field + + +def test_the_section_commands_run_in_order(fleet_store, capsys): # noqa: F811 + from yeto.cli import build_parser + + cfg, objects, store, run_cli, samplers = fleet_store + argvs = commands() + assert {a[1] for a in argvs} == {"fleet", "island"} + for argv in argvs: + build_parser().parse_args(argv[1:]) + plan = fleet.plan_of(cfg) # the island the section removes + entry = dict(cfg["islands"][1]["samplers"][0], name="sglang-north") + member, pools = fleet_islands.compile_island(cfg, plan, k=2, name="north", gpu="modal:1x2xh100", usd_per_h=8.0, + samplers=[entry]) + store.update(lambda d: fleet_islands.add(d, member, pools), note="add north") + for argv in (a for a in argvs if a[:3] == ["yeto", "fleet", "island"]): + rest = argv[3:] + config = rest.index("--config") + del rest[config:config + 2] + before = store.read()["generation"] + assert run_cli(*rest) == 0, (argv, capsys.readouterr().err) + assert store.read()["generation"] == before + (0 if "--dry-run" in argv else 1) diff --git a/tests/test_ssh_island_fleet_e2e.py b/tests/test_ssh_island_fleet_e2e.py new file mode 100644 index 000000000..b3cd3d2c2 --- /dev/null +++ b/tests/test_ssh_island_fleet_e2e.py @@ -0,0 +1,399 @@ +"""SSH trainer islands that join, leave and lag a training fleet, end to end +(own-cluster-fleet-stability 9.1 and 9.2): the real Rust syncer, the trainer worker +reconciling the desired state on a local store, and for each island launch the launcher's +own fleet controller over the resident ``ssh:`` island ops (``yeto.launch.ssh_resident``) on +a fake SSH cluster. Rank 0 of each island is its trainer: its start on the fake nodes +connects a syncer client under the island's learner id, its kill drops the connection. No +cloud, no Ray, no GPU. + +Two islands (``ssh:2x8xb300@bm``, two nodes each) train. Then, one case each: + +* **add**: ``yeto fleet island add`` (its functions) writes a third island into the desired + state; the worker starts its launch on two more nodes, the island catches up to the newest + outer weights and its pushes are merged from then on. +* **remove**: ``remove`` takes island 1 out; the worker writes its island STOP, its + controller drains it, releases its nodes (the kill on each node), and the rounds merge over + island 0 alone. +* **stuck**: island 1's trainer stops pushing while it stays connected (heartbeats). The + syncer merges island 0 at the quorum deadline and excuses island 1; island 1's controller + writes ``island_straggler`` (action ``wait``) once three merge cycles went by without a push + of it, nothing is stopped or relaunched, and once it pushes again its controller writes + ``island_straggler_cleared``. + +Each case checks that the other islands' processes never restarted (one start per node, no +kill before the end, one launch), that the merged steps run 1..N without a gap or a repeat, +that no push is merged twice, and that the resource ledger holds each SSH incarnation once. +""" + +from __future__ import annotations + +import json +import threading +import time +from collections import Counter + +import pytest + +from test_fleet_island_launches import example_doc +from test_fleet_trainer_worker import FakeLaunches +from test_rl_full_parameter_async import _f32, _initial, _start_async_syncer, _wait, needs_cargo +from test_rl_full_parameter_async import syncer_binary # noqa: F401 - fixture +from test_rl_full_parameter_dynamic_members import LAUNCHED, MAX_LEARNERS, P, POOL, _client, _delta, _outer_steps +from test_rl_ssh_resident import FakeCluster, b300 +from yeto.cost.ledger import ResourceLedger +from yeto.hw import card_tools +from yeto.launch import island_lifecycle as lifecycle +from yeto.launch import island_straggler as st +from yeto.launch.fleet import FleetController +from yeto.launch.learner_ids import allocate_learner_id +from yeto.launch.pool import desired as dz +from yeto.launch.ssh_resident import SshIslandOps +from yeto.launch.ssh_trainer_island import SshTrainerSpec +from yeto.launch.ssh_trainer_ledger import KIND as SSH_TRAINER +from yeto.modal_runner import RoutingOps +from yeto.rl import fleet, fleet_islands, island_launches, trainer_worker +from yeto.rl import up +from yeto.rl.engine.object_store import DirectoryObjectStore + +GPU = "ssh:2x8xb300@bm" +NODES = {k: (b300(2 * k), b300(2 * k + 1)) for k in range(MAX_LEARNERS)} # island k on nodes 2k, 2k+1 +CYCLES = 3 +# the stuck case: a short soft deadline, so a round that waits for the silent island merges +# island 0's push after 2 s (the quorum deadline of an island pool, #865) +STUCK_POOL = tuple({"30": "2"}.get(a, a) for a in POOL) + + +@pytest.fixture(autouse=True) +def _ssh_nodes(monkeypatch, tmp_path): + monkeypatch.setattr(card_tools, "check_cards", lambda family, text, **kw: []) + monkeypatch.setenv("YETO_RESOURCE_LEDGER", str(tmp_path / "ledger.jsonl")) + monkeypatch.setenv("YETO_ISLAND_HMAC_KEY", "ssh-island-fleet-test-key") + + +class TrainerCluster(FakeCluster): + """The fake nodes of every island; rank 0's start and kill are its trainer's.""" + + def __init__(self) -> None: + super().__init__([n.name for nodes in NODES.values() for n in nodes]) + self.rank0 = {nodes[0].name: k for k, nodes in NODES.items()} + self.trainer_starts: list[int] = [] + self.trainer_kills: list[int] = [] + self.guard = threading.Lock() + + def start(self, node, script): + stream = super().start(node, script) + if "setsid bash -c" in script and node.name in self.rank0: + with self.guard: + self.trainer_starts.append(self.rank0[node.name]) + return stream + + def run(self, node, script, *, timeout=300.0): + out = super().run(node, script, timeout=timeout) + if "kill -TERM" in script and node.name in self.rank0: + with self.guard: + self.trainer_kills.append(self.rank0[node.name]) + return out + + def finish(self, k: int) -> None: + """Island k's trainer ended its run: every rank exits 0 (rank 0 last).""" + for node in reversed(NODES[k]): + if self.runs[node.name].get(0, {}).get("state") == "running": + self.exit(node.name, 0, 0) + + +class FastClock: + """The island controller's sky side: fake time, 30 s per poll in 10 ms.""" + + def __init__(self) -> None: + self.t = 0.0 + + def now(self): + return self.t + + def sleep(self, seconds): + time.sleep(0.01) + self.t += seconds + + +class FleetLog: + def __init__(self) -> None: + self.events: list[tuple[str, str, dict]] = [] + + def event(self, kind, name, **fields): + self.events.append((kind, name, fields)) + + def maybe_tick(self): + pass + + def cost_tick(self): + pass + + def kinds(self, kind): + return [e for e in list(self.events) if e[0] == kind] + + +class _SyncThread: + def __init__(self, target, daemon=None): + self.target = target + + def start(self): + self.target() + + def join(self, timeout=None): + pass + + +class SshIslandLaunches(FakeLaunches): + """Each island launch is what ``yeto launch --gpu ssh:...`` runs for one island of a + fleet: the resident ssh: island ops on its inventory nodes and the fleet controller + supervising it (its island STOP, its record, the straggler watch), on a thread.""" + + def __init__(self, tmp_path, cluster: TrainerCluster, objects, tape) -> None: + super().__init__() + self.tmp_path, self.cluster, self.objects, self.tape = tmp_path, cluster, objects, tape + self.controllers: dict[int, FleetController] = {} + self.logs: dict[int, FleetLog] = {} + self.errors: list[BaseException] = [] + + def start(self, prefix: str, argv: list[str]) -> int: + pid = super().start(prefix, argv) + k = int(argv[argv.index("--rl-fleet-learner-id") + 1]) + assert argv[argv.index("--gpu") + 1] == GPU + name = f"{prefix}-trainer" + ops = SshIslandOps(run_id=prefix, journal_dir=self.tmp_path / "runs" / prefix / "ssh-islands", + events_dir=self.tmp_path / "events" / prefix, ops=self.cluster, log=lambda m: None) + spec = SshTrainerSpec(nodes=NODES[k], run_id=prefix, workdir="/opt/yeto", run_script="echo island", env={}) + ops.add(name, spec) + job = ops.start(name) + log = self.logs[k] = FleetLog() + recorder = lifecycle.FleetRecorder(lifecycle.IslandStateStore(self.objects, log=lambda m: None), + {name: lifecycle.IslandRef(k, "ssh")}) + ctl = self.controllers[k] = FleetController( + learners={name: (spec, job)}, syncer=None, sky_ops=RoutingOps(FastClock(), None, ssh_ops=ops), + poll_interval=30.0, recover_timeout=600.0, thread_cls=_SyncThread, recorder=recorder, elastic=True, + deterministic_stop=True, fleet_log=log, + straggler=st.StragglerWatch(st.FileTape(self.tape), cycles=CYCLES, log=lambda m: None)) + + def supervise(): + code = 0 + try: + ctl.run() + except BaseException as error: # noqa: BLE001 - reported by the test + self.errors.append(error) + code = 1 + self.end(prefix, code) + + threading.Thread(target=supervise, daemon=True).start() + return pid + + +def _config(tmp_path): + doc = example_doc(tmp_path, max_islands=MAX_LEARNERS) + for island in doc["islands"]: + island["trainer"].update(gpu=GPU, usd_per_h=0.0) # own machines + path = tmp_path / "run.json" + path.write_text(json.dumps(doc)) + return up.load_config(str(path)) + + +@needs_cargo +@pytest.mark.parametrize("case", ["add", "remove", "stuck"]) +def test_ssh_islands_join_leave_and_lag_without_touching_the_other_islands(syncer_binary, tmp_path, # noqa: F811 + case): + cfg = _config(tmp_path) + plan = fleet.plan_of(cfg) + objects = DirectoryObjectStore(tmp_path / "store") + store = dz.DesiredStore(objects) + members = island_launches.trainer_members(cfg, plan) + store.apply({"members": [*members, *({"kind": "sampler_pool", "name": p.name, "island": i.index, + "pool": {"provider": "modal"}} for i in plan.islands for p in i.pools)]}, + expect=0) + total_steps, change_at = 12, 3 + process, port, profile_hash = _start_async_syncer( + syncer_binary, tmp_path, *(STUCK_POOL if case == "stuck" else POOL), total_steps=total_steps, + log_file=tmp_path / "syncer.log") + tape = tmp_path / "tape.jsonl" + island_launches.write_syncer_record(objects, addr=f"127.0.0.1:{port}", syncer_epoch=0, learners=LAUNCHED, + max_learners=MAX_LEARNERS, run="r") + states = lifecycle.IslandStateStore(objects, log=lambda m: None) + cluster = TrainerCluster() + launches = SshIslandLaunches(tmp_path, cluster, objects, tape) + worker = trainer_worker.TrainerWorker(store, objects, launches, states, log=lambda m: None) + + clients: dict[int, object] = {} + started = Counter() + gone: list[int] = [] + catching: dict[int, dict] = {} + versions = {k: [0] * P for k in range(MAX_LEARNERS)} + seen: dict[int, set] = {k: set() for k in range(MAX_LEARNERS)} + held: dict[int, list] = {} + state = {"changed": False, "stuck": False, "flagged": False, "cleared": False, "joined_at": None} + beat = [0.0] + + def follow_the_nodes(): + with cluster.guard: + starts, kills = list(cluster.trainer_starts), list(cluster.trainer_kills) + for k in starts[sum(started.values()):]: + started[k] += 1 + client = _client(k, port, profile_hash) + client.start() + clients[k] = client + if k >= LAUNCHED: + catching[k] = {} + for k in kills: + if k in clients and k not in gone: # its machines torn down: the connection just drops + clients.pop(k).close() + gone.append(k) + + def drain(k): + client = clients[k] + client.check_health() + if k in catching: # a joiner applies its catch-up before it answers a PULL + caught = catching[k] + for update in client.drain_updates(): + caught.setdefault(update.fragment_id, update.version) + held.setdefault(k, []).extend(client.drain_pulls()) + if len(caught) < P: + return + versions[k] = [caught[fid] for fid in range(P)] + state["joined_at"] = list(versions[k]) # the outer versions its catch-up brought + del catching[k] + for update in client.drain_updates(): + versions[k][update.fragment_id] = max(versions[k][update.fragment_id], update.version) + if case == "stuck" and k == 1 and state["stuck"]: + return # connected (its heartbeats go on), delivering nothing + for permit in held.pop(k, []) + client.drain_pulls(): + key = (permit.global_step, permit.round_attempt) + if key in seen[k]: + continue + seen[k].add(key) + client.push_fragment(permit.fragment_id, permit.global_step, permit.round_attempt, + versions[k][permit.fragment_id], permit.global_step, 1, 7, + _f32(_delta(k, permit.global_step))) + + def change(): + if case == "add": + k = allocate_learner_id(objects, launched=LAUNCHED, max_learners=MAX_LEARNERS, island="north") + entry = dict(cfg["islands"][1]["samplers"][0], name="sglang-north") + member, pools = fleet_islands.compile_island(cfg, plan, k=k, name="north", gpu=GPU, usd_per_h=0.0, + samplers=[entry]) + store.update(lambda d: fleet_islands.add(d, member, pools), note="add north") + elif case == "remove": + store.update(lambda d: fleet_islands.remove(d, "sglang"), note="remove island 1") + else: + state["stuck"] = True + state["changed"] = True + + def poll(): + assert not launches.errors, launches.errors + if time.monotonic() - beat[0] > 1: # every connected island renews its lease + beat[0] = time.monotonic() + for client in list(clients.values()): + client.heartbeat(0) + worker.step() + follow_the_nodes() + for k in list(catching) or list(clients): + drain(k) + if catching: + return False # a joiner catches up before the fleet moves on + if not state["changed"] and len(clients) == LAUNCHED and min(versions[0]) >= change_at: + change() + if case == "stuck" and state["stuck"] and launches.logs[1].kinds(st.EVENT): + state["stuck"], state["flagged"] = False, True # reported: it pushes again + if case == "stuck" and state["flagged"] and launches.logs[1].kinds(st.CLEARED_EVENT): + state["cleared"] = True + done = all(c.finalizing.is_set() for c in clients.values()) + if case == "add": + return done and 2 in clients and state["joined_at"] is not None + if case == "remove": + return done and 1 in gone + return done and state["cleared"] + + finals = {} + try: + worker.step() # islands 0 and 1 start on their nodes + follow_the_nodes() + assert sorted(clients) == [0, 1] + for fid in range(P): + clients[0].send_init(fid, _f32(_initial(fid))) + _wait(poll, f"the fleet never finalized ({case})", timeout=240) + for k, client in clients.items(): + manifest, _fragments = client.wait_for_final_fragments(timeout=30) + finals[k] = manifest + client.acknowledge_finalization(manifest) + assert process.wait(timeout=15) == 0 + for k in list(clients): + cluster.finish(k) # the trainers end their run: every launch ends by its trainer + _wait(lambda: all(launches.ended(m["prefix"]) is not None for m in worker_members(store, case)), + "an island launch did not end", timeout=60) + finally: + for client in clients.values(): + client.close() + if process.poll() is None: + process.terminate() + process.wait(timeout=10) + assert not launches.errors, launches.errors + + # -- the other islands were never touched: one start per node, one launch, no kill before the end + others = {"add": [0, 1], "remove": [0], "stuck": [0, 1]}[case] + for k in others: + assert started[k] == 1 and launches.started(f"r-i{k}") == 1 + assert [sum(1 for c in cluster.calls if c[:2] == ("start", n.name)) for n in NODES[k]] == [1, 1] + kills_before_end = [k for k in cluster.trainer_kills if k in gone] + assert kills_before_end == ([1] if case == "remove" else []) + if case == "add": + assert started[2] == 1 and launches.started("r-i2") == 1 + if case == "remove": + assert all(sum(1 for c in cluster.calls if c[:2] == ("kill", n.name)) >= 1 for n in NODES[1]) + worker.step() + assert worker.load(1)["state"] == trainer_worker.REMOVED + + # -- the merges: steps 1..N without a gap or a repeat, no push merged twice + steps = _outer_steps(tape.read_text()) + assert [r["step"] for r in steps] == list(range(1, total_steps * P + 1)) + merged = [(int(e[0]), pushed) for r in steps for e, pushed in zip(r["raw_weights"], r["pushed_for"])] + assert len(merged) == len(set(merged)), Counter(merged).most_common(3) + for record in steps: + assert abs(sum(float(e[2]) for e in record["weights"]) - 1.0) < 1e-9 + contributors = {int(e[0]) for r in steps for e in r["raw_weights"]} + assert contributors == ({0, 1, 2} if case == "add" else {0, 1}) + if case == "add": # the joiner caught up to the merged weights of the add's time, then merged + first = min(r["step"] for r in steps if 2 in [int(e[0]) for e in r["raw_weights"]]) + assert min(state["joined_at"]) >= change_at and first > max(state["joined_at"]) + if case == "remove": + leave = next(r for r in _records(tape) if r.get("kind") == "pool_leave" and int(r["island_id"]) == 1) + after = [r for r in steps if r.get("time_unix", 0) > leave.get("time_unix", 0)][2 * P:] + assert after and all([int(e[0]) for e in r["raw_weights"]] == [0] for r in after) + + # -- the straggler: written once by island 1's controller, waiting; nobody else reported + if case == "stuck": + (event,) = launches.logs[1].kinds(st.EVENT) + assert event[2]["action"] == st.WAIT and event[2]["missed_cycles"] == CYCLES and event[2]["fragments"] == P + assert event[2]["absent"] is True + assert len(launches.logs[1].kinds(st.CLEARED_EVENT)) == 1 + assert states.read(1)["straggler"] is None # cleared in its record too + absent = [r for r in steps if r["absent"] == [1]] + assert any(r["timed_out"] for r in absent) # merged at the quorum deadline without it + assert launches.controllers[1].learners["r-i1-trainer"]["relaunches"] == 0 + for k, log in launches.logs.items(): + if case != "stuck" or k != 1: + assert not log.kinds(st.EVENT), (k, log.kinds(st.EVENT)) + + # -- the ledger: each ssh incarnation created once, released at most once + rows = [r for r in ResourceLedger(tmp_path / "ledger.jsonl").records() if r["kind"] == SSH_TRAINER] + created = Counter(r["id"] for r in rows if r["op"] == "create") + released = Counter(r["id"] for r in rows if r["op"] == "release") + islands = {"add": 3, "remove": 2, "stuck": 2}[case] + assert sorted(created) == sorted(f"r-i{k}/r-i{k}-trainer-i0" for k in range(islands)) + assert set(created.values()) == {1} and all(n == 1 for n in released.values()) + + +def worker_members(store, case): + members = list(dz.trainers(store.read()).values()) + if case == "remove": + members.append({"prefix": "r-i1"}) + return members + + +def _records(tape): + return [json.loads(line) for line in tape.read_text().splitlines() if line.strip()] diff --git a/yeto/launch/fleet.py b/yeto/launch/fleet.py index 99eb1d0a4..68375d288 100644 --- a/yeto/launch/fleet.py +++ b/yeto/launch/fleet.py @@ -287,6 +287,8 @@ def __init__( incarnations=None, stop_probe=None, deterministic_stop: bool = False, + straggler=None, + straggler_policy=None, ): """`learners` maps cluster name -> (task, job_id); `syncer` is (name, task, job_id) for a cluster syncer, or None with @@ -406,6 +408,13 @@ def __init__( # STOP there ends that island only. None (a single-trainer launch by default): # nothing is written or read. self.recorder = recorder + # yeto.launch.island_straggler.StragglerWatch or None: the syncer's merges, read each + # poll; a running island none of whose pushes was merged in N merge cycles is written + # as island_straggler (fleet.jsonl and its record). ``straggler_policy(name, signal)`` + # says what to do (island_straggler.WAIT, the default, or REPLACE with a ``replace`` + # callable of its own); None: wait (the syncer merges without it meanwhile). + self.straggler = straggler + self.straggler_policy = straggler_policy # name -> {"incarnation", "relaunches", "adopted"} from the island's record of an # earlier launcher of this run (yeto.launch.island_adopt): an adopted island keeps # its incarnation; a relaunched one continues the count. @@ -532,6 +541,7 @@ def _run_fleet(self) -> dict: self._poll_local_syncer() for rec in self.learners.values(): self._poll_recorded(rec) + self._poll_stragglers() self._end_followers() if all(r["state"] in (DONE, ABANDONED) for r in self.learners.values()): break @@ -1049,6 +1059,60 @@ def _check_stall(self) -> None: print(f"[launcher] ERROR: run stalled: {message}", file=sys.stderr) raise RunStalled(message, silent_s=silent, timeout_s=self.stall_timeout) + # -- island stragglers (yeto.launch.island_straggler) ------------------------------------- + def _poll_stragglers(self) -> None: + """The straggler watch's signals for the islands running now (not draining): each one + is written once (``island_straggler`` / ``island_straggler_cleared`` in fleet.jsonl, + ``straggler`` in the island's record) and its policy is asked what to do. Never + raises: a watch that fails is a missing view, not the end of supervision.""" + if self.straggler is None or self.recorder is None: + return + try: + running, names = {}, {} + for rec in self.learners.values(): + ref = self.recorder.ref(rec["name"]) + if ref is None or ref.role == "sampler" or rec["state"] != RUNNING or rec.get("draining"): + continue + running[ref.island] = (rec.get("incarnation"), rec.get("job_id")) + names[ref.island] = rec + for signal in self.straggler.poll(running): + rec = names.get(signal.island) + if rec is not None: + self._island_straggler(rec, signal) + except Exception as error: # noqa: BLE001 - a watch, never the end of supervision + print(f"[launcher] island straggler watch: {type(error).__name__}: {error}"[:400], file=sys.stderr) + + def _island_straggler(self, rec, signal) -> None: + from . import island_straggler as st + + name = rec["name"] + if signal.cleared: + print(f"[launcher] {name}: no longer a straggler ({signal.reason})", file=sys.stderr) + self._fleet(st.CLEARED_EVENT, name, **st.signal_fields(signal, None)) + self._record(rec, straggler=None) + return + action = st.WAIT + if self.straggler_policy is not None: + try: + action = self.straggler_policy(name, signal) or st.WAIT + except Exception as error: # noqa: BLE001 - the default is to wait + print(f"[launcher] {name}: straggler policy failed ({type(error).__name__}: {error}); " + "waiting", file=sys.stderr) + action = st.WAIT + if action not in st.ACTIONS: + print(f"[launcher] {name}: straggler policy answered {action!r}; waiting", file=sys.stderr) + action = st.WAIT + fields = st.signal_fields(signal, action) + print(f"[launcher] WARNING: {name}: island straggler: {signal.reason}; " + + ("waiting (the syncer merges the other islands at each quorum deadline, and catches it up " + "once it delivers again)" if action == st.WAIT else "its provider replaces it"), file=sys.stderr) + self._fleet(st.EVENT, name, **fields) + self._record(rec, straggler=dict(fields, at=self.ops.now())) + if action == st.REPLACE: + replace = getattr(self.straggler_policy, "replace", None) + if callable(replace): + replace(name, signal) + def _all_learners_finalized(self) -> bool: return self.finalized_probe is not None and all( r["state"] == DONE or self._finalized(r) for r in self.learners.values() diff --git a/yeto/launch/island_straggler.py b/yeto/launch/island_straggler.py new file mode 100644 index 000000000..b77aed107 --- /dev/null +++ b/yeto/launch/island_straggler.py @@ -0,0 +1,346 @@ +"""Island stragglers of an island pool: a running island none of whose pushes was merged in +N merge cycles (``island_straggler``). + +The syncer already keeps such an island from holding the others: a pool round whose quorum +deadline passes merges the pushes that arrived, the silent island is recorded absent and +excused from the next rounds, and once it delivers again it is caught up and merged again. +What nobody said so far is that an island has stopped contributing: it heartbeats, its +launch is up, and the fleet controller sees nothing wrong. This module watches the syncer's +merges and tells the controller, which writes the event and decides what to do (wait, the +default, or a replacement the island's provider offers). + +* **What is counted.** The syncer's tape (its ``outer_step`` records; ``pool_join`` for the + start of an island). A merge cycle is one outer step of every fragment: with P fragments + (the distinct ``fragment`` ids merged so far, 1 for a non-fragment pool) an island is a + straggler once ``N x P`` merges in a row went by without a push of it in their weights. + A push the syncer refused, or one still in flight, is not merged and does not count. +* **When counting starts.** At the island's first ``pool_join`` after it was (re)launched: + the time a launch takes to come up and join is not counted. A later re-JOIN of the same + incarnation (a lease that expired) does not restart the count. A merged push of the island + resets it. +* **Who is watched.** The islands the controller holds running (not draining, not + recovering): it passes their learner ids with a token of the incarnation; a new token + is a relaunch and starts the count again. +* **Signals.** One :class:`Straggler` when an island crosses the threshold, and one + ``cleared`` signal when a push of it is merged again (or when it was relaunched while + flagged). Nothing in between: the controller writes one event per stretch. + +Sources (:func:`tape_source`): the syncer's tape file on this host (a head-mode syncer), or +its copy in the run store (``tapes/syncer//.jsonl``, uploaded every 30 s +by ``yeto.rl.engine.tape_upload``). A source that does not read is skipped for that poll; +nothing here ever stops or slows the fleet. +""" + +from __future__ import annotations + +import json +import os +from collections.abc import Callable, Mapping +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any + +EVENT = "island_straggler" +CLEARED_EVENT = "island_straggler_cleared" +DEFAULT_CYCLES = 3 +SYNCER_TAPES = "tapes/syncer/" +STORE_POLL_S = 30.0 # the syncer's uploads are 30 s apart (tape_upload.DEFAULT_INTERVAL_S) +MAX_READ_BYTES = 8 << 20 # one poll reads at most this much of a local tape +QUIET_POLLS = 40 # polls (20 min at 30 s) without a syncer record before that is said, once + +WAIT = "wait" # the syncer merges without it; it is caught up once it delivers again +REPLACE = "replace" # the island's provider replaces it (its own policy decides) +ACTIONS = (WAIT, REPLACE) + + +def straggler_cycles(args: Any) -> int: + """``--rl-island-straggler-cycles`` (N >= 0; 0 turns the watch off), default + :data:`DEFAULT_CYCLES`.""" + value = getattr(args, "rl_island_straggler_cycles", None) + if value is None: + return DEFAULT_CYCLES + if isinstance(value, bool) or int(value) != value or int(value) < 0: + raise ValueError(f"--rl-island-straggler-cycles must be a whole number >= 0 (got {value!r})") + return int(value) + + +@dataclass(frozen=True) +class Straggler: + """One signal about island ``island`` (its learner id).""" + + island: int + cleared: bool # False: it became a straggler; True: a push of it is merged again (or relaunched) + missed_cycles: int # whole merge cycles since its last merged push (or its join) + merges: int # merges since then + fragments: int # P + cycles: int # N, the threshold + newest_step: int | None # the newest merged step the syncer recorded + last_merged_step: int | None # the newest step a push of the island was merged into + absent: bool # the newest merge listed it absent (expected, not answered) + reason: str = "" + + def fields(self) -> dict[str, Any]: + out = asdict(self) + out.pop("island") + out.pop("cleared") + return out + + +@dataclass +class _Island: + joined: bool = False + misses: int = 0 + last_merged_step: int | None = None + absent: bool = False + flagged: bool = False + token: Any = None + + +@dataclass +class StragglerTracker: + """Folds syncer tape records (:meth:`feed`) and answers :meth:`check` (module doc).""" + + cycles: int = DEFAULT_CYCLES + islands: dict[int, _Island] = field(default_factory=dict) + fragments: set[int] = field(default_factory=set) + newest_step: int | None = None + + def _island(self, k: int) -> _Island: + return self.islands.setdefault(int(k), _Island()) + + @property + def per_cycle(self) -> int: + return max(1, len(self.fragments)) + + def feed(self, record: Mapping[str, Any]) -> None: + kind = record.get("kind") + if kind == "pool_join": + island = _int(record.get("island_id")) + if island is not None and not self._island(island).joined: + state = self._island(island) + state.joined, state.misses, state.absent = True, 0, False + return + if kind != "outer_step": + return + step, fragment = _int(record.get("step")), _int(record.get("fragment")) + if fragment is not None: + self.fragments.add(fragment) + if step is not None: + self.newest_step = step if self.newest_step is None else max(self.newest_step, step) + merged = {_int(entry[0]) for entry in _entries(record.get("weights")) + _entries(record.get("raw_weights"))} + absent = {_int(i) for i in record.get("absent") or () if _int(i) is not None} + for k, state in self.islands.items(): + if k in merged: + state.misses, state.absent = 0, False + state.last_merged_step = step if step is not None else state.last_merged_step + state.joined = True # a merged push: it is in the pool whatever the tape showed of its join + elif state.joined: + state.misses += 1 + state.absent = k in absent + for k in merged - set(self.islands) - {None}: + self.islands[k] = _Island(joined=True, last_merged_step=step) + + def check(self, running: Mapping[int, Any]) -> list[Straggler]: + """The signals for the islands held running (learner id -> incarnation token).""" + out: list[Straggler] = [] + threshold = self.cycles * self.per_cycle + for k, token in running.items(): + state = self._island(int(k)) + if state.token != token: + if state.token is not None: # relaunched: its count starts at its next join + if state.flagged: + out.append(self._signal(int(k), state, cleared=True, reason="relaunched")) + state.joined, state.misses, state.absent, state.flagged = False, 0, False, False + state.token = token + if self.cycles <= 0 or not state.joined: + continue + if not state.flagged and state.misses >= threshold: + state.flagged = True + out.append(self._signal(int(k), state, cleared=False, + reason=f"no push merged in {state.misses // self.per_cycle} merge cycle(s) " + f"({state.misses} merges over {self.per_cycle} fragment(s))")) + elif state.flagged and state.misses < threshold: + state.flagged = False + out.append(self._signal(int(k), state, cleared=True, reason="a push of it is merged again")) + for k, state in self.islands.items(): + if k not in running: + state.flagged = False # not running (recovering, draining, ended): no stretch to close + return out + + def _signal(self, k: int, state: _Island, *, cleared: bool, reason: str) -> Straggler: + return Straggler(island=k, cleared=cleared, missed_cycles=state.misses // self.per_cycle, + merges=state.misses, fragments=self.per_cycle, cycles=self.cycles, + newest_step=self.newest_step, last_merged_step=state.last_merged_step, + absent=state.absent, reason=reason) + + +def _int(value: Any) -> int | None: + if isinstance(value, bool): + return None + try: + return int(value) + except (TypeError, ValueError): + return None + + +def _entries(value: Any) -> list: + return [e for e in value or () if isinstance(e, (list, tuple)) and e] + + +# -- the syncer's tape --------------------------------------------------------------------- + +class FileTape: + """The syncer's tape file on this host: the complete lines added since the last read.""" + + def __init__(self, path: str | os.PathLike[str], *, offset: int = 0) -> None: + self.path = Path(os.path.expanduser(str(path))) + self.offset = int(offset) # a reused host's tape: what an earlier syncer job wrote is not read + self.label = str(self.path) + + def read(self) -> list[dict[str, Any]]: + try: + size = self.path.stat().st_size + except FileNotFoundError: + return [] + if size < self.offset: # rewritten from the start: read it again + self.offset = 0 + if size == self.offset: + return [] + with self.path.open("rb") as handle: + handle.seek(self.offset) + data = handle.read(MAX_READ_BYTES) + end = data.rfind(b"\n") + if end < 0: + return [] + self.offset += end + 1 + return _records(data[: end + 1]) + + +class StoreTape: + """The syncer's tape in the run store (``tapes/syncer//.jsonl``): the + chunks not read yet, incarnations in the order they started, each chunk once.""" + + def __init__(self, objects: Any, *, interval_s: float = STORE_POLL_S, + clock: Callable[[], float] | None = None) -> None: + import time + + self.objects = objects + self.interval_s = float(interval_s) + self.clock = clock or time.monotonic + self.cursors: dict[str, str] = {} # incarnation -> its last chunk read + self.label = f"{getattr(objects, 'uri', 'store')}/{SYNCER_TAPES}" + self._next: float | None = None + + def read(self) -> list[dict[str, Any]]: + from yeto.dashboard.store_tapes import _launch_ordered # noqa: PLC0415 + + now = self.clock() + if self._next is not None and now < self._next: + return [] + self._next = now + self.interval_s + keys = [] + for key in self.objects.list(SYNCER_TAPES): + parts = str(key)[len(SYNCER_TAPES):].split("/") + if len(parts) == 2 and parts[1].endswith(".jsonl") and key > self.cursors.get(parts[0], ""): + keys.append(str(key)) + out: list[dict[str, Any]] = [] + for key in _launch_ordered(keys, "tapes/"): + data = self.objects.read(key) + self.cursors[key[len(SYNCER_TAPES):].split("/")[0]] = key + if data: + out += _records(data if isinstance(data, bytes) else str(data).encode()) + return out + + +def _records(data: bytes) -> list[dict[str, Any]]: + out = [] + for line in data.splitlines(): + try: + record = json.loads(line) + except (ValueError, UnicodeDecodeError): + continue + if isinstance(record, dict): + out.append(record) + return out + + +class StragglerWatch: + """A tracker fed from one source: :meth:`poll` reads what the syncer added and returns + the signals for the islands held running. A read that fails is logged once per stretch + of failures and tried again at the next poll.""" + + def __init__(self, source: Any, *, cycles: int = DEFAULT_CYCLES, + log: Callable[[str], None] | None = None) -> None: + import sys + + self.source = source + self.tracker = StragglerTracker(cycles=int(cycles)) + self.log = log or (lambda m: print(m, file=sys.stderr, flush=True)) + self._failing = False + self._empty_polls = 0 # polls with islands running and no syncer record read yet + + def poll(self, running: Mapping[int, Any]) -> list[Straggler]: + try: + records = self.source.read() + except Exception as error: # noqa: BLE001 - a watch, never the end of supervision + if not self._failing: + self.log(f"[launcher] island straggler watch: the syncer tape {self.source.label} does not read " + f"({type(error).__name__}: {error}); tried again next poll"[:400]) + self._failing = True + records = [] + else: + self._failing = False + for record in records: + self.tracker.feed(record) + if records: + self._empty_polls = -1 + elif running and self._empty_polls >= 0: + self._empty_polls += 1 + if self._empty_polls == QUIET_POLLS: + self.log(f"[launcher] island straggler watch: no syncer record read from {self.source.label} in " + f"{QUIET_POLLS} polls; no straggler is reported until the syncer's tape is there") + return self.tracker.check(running) + + +def tape_source(*, local_tape: str | os.PathLike[str] | None = None, local_offset: int = 0, + objects: Any = None) -> Any: + """The syncer tape this controller can read: the local file of a syncer on this host, + else the run store's copy; None when neither is there.""" + if local_tape: + return FileTape(local_tape, offset=local_offset) + if objects is not None: + return StoreTape(objects) + return None + + +def watch_for(args: Any, *, local_tape: str | os.PathLike[str] | None = None, local_offset: int = 0, + objects: Any = None, log: Callable[[str], None] | None = None) -> StragglerWatch | None: + """The launcher's watch of an island pool (``--rl-island-straggler-cycles``, default 3; + 0 turns it off): None without an island pool, with the watch off, or with no syncer tape + to read from here (said once).""" + import sys + + from .syncer import island_pool + + if getattr(args, "training_mode", "sft") != "rl" or not island_pool(args): + return None + cycles = straggler_cycles(args) + if cycles == 0: + return None + source = tape_source(local_tape=local_tape, local_offset=local_offset, objects=objects) + say = log or (lambda m: print(m, file=sys.stderr, flush=True)) + if source is None: + say("[launcher] island straggler watch off: no syncer tape to read here (a syncer on this host, or " + "the run store's tapes/syncer/)") + return None + say(f"[launcher] island straggler watch: an island none of whose pushes is merged in {cycles} merge " + f"cycle(s) is reported ({EVENT}); syncer tape {source.label}") + return StragglerWatch(source, cycles=cycles, log=log) + + +def signal_fields(signal: Straggler, action: str | None) -> dict[str, Any]: + """The event's and the island record's fields of ``signal``.""" + out = signal.fields() + if action is not None: + out["action"] = action + return out diff --git a/yeto/launch/rl_args.py b/yeto/launch/rl_args.py index f1e6c473e..9601b2cff 100644 --- a/yeto/launch/rl_args.py +++ b/yeto/launch/rl_args.py @@ -842,6 +842,9 @@ def _check_island_pool(args, *, num_islands: int) -> None: if int(getattr(args, "syncer_shards", None) or 1) > 1: raise ValueError("membership options need one syncer (no --syncer-shards > 1)") check_stale_lag(args) + from .island_straggler import straggler_cycles + + straggler_cycles(args) # --rl-island-straggler-cycles: a whole number >= 0 max_learners = getattr(args, "rl_sync_max_learners", None) if max_learners is not None: # full-parameter: the islands bind the roster 0..N-1 into their session diff --git a/yeto/launcher.py b/yeto/launcher.py index 7b76ee929..8ef0ebd31 100644 --- a/yeto/launcher.py +++ b/yeto/launcher.py @@ -690,6 +690,28 @@ def reader(): resolve_island_syncer_epoch(args, reader(), **({} if timeout_s is None else {"timeout_s": timeout_s})) +def _island_straggler_watch(args, island_states, local_syncer): + """``yeto.launch.island_straggler``'s watch of an island pool's merges: the syncer's tape + of a syncer on this host, else, for an island launch of a fleet launched island by island, + the copy its syncer launch uploads to an object run store (``tapes/syncer/``); None + without an island fleet's records (nothing is written then).""" + if island_states is None: + return None + from .launch.island_straggler import watch_for + from .launch.storage import is_object_store_uri + from .rl.engine.sample_roles import FLEET_ROLE_ISLAND, fleet_role + from .rl.engine.tape_upload import upload_interval_s + + uploaded = (fleet_role(args) == FLEET_ROLE_ISLAND and upload_interval_s() is not None + and is_object_store_uri(str(getattr(args, "rl_checkpoint_store", None) or ""))) + try: + return watch_for(args, local_tape=getattr(local_syncer, "event_tape", None), + local_offset=int(getattr(local_syncer, "_event_offset", 0) or 0), + objects=getattr(island_states, "objects", None) if uploaded else None) + except ValueError as error: + raise SystemExit(str(error)) from None + + def _island_state_store(args): """The run store's island records (None: no object API for the store, or none).""" from .launch.island_lifecycle import open_state_store @@ -1340,6 +1362,7 @@ def route_container(learner_id: int): "new_machine_retries": _recorded_new_machine_retries(recorder, name)} for name, a in adoption.items()}, deterministic_stop=deterministic_stop(args)[0], + straggler=_island_straggler_watch(args, island_states, local_syncer if head_mode else None), # why an island stopped, from its own tape records (a breaker, a strict check, a # refusal: never relaunched), not from its rank's exit status stop_probe=( diff --git a/yeto/rl/engine/run_flags.py b/yeto/rl/engine/run_flags.py index f24fbb652..d5be7b59e 100644 --- a/yeto/rl/engine/run_flags.py +++ b/yeto/rl/engine/run_flags.py @@ -1039,6 +1039,11 @@ def rl_forward_pairs(*dests: str | tuple[str, str]) -> tuple[tuple[str, str], .. help="with --rl-fleet-role syncer on a cluster: how long the syncer cluster may stay " "unreadable or not UP in a row before the syncer launch fails (and the fleet ends). " "It includes the time the sky API itself does not answer (default 300)"), + cli_flag("--rl-island-straggler-cycles", type=int, default=None, metavar="N", + help="island pool: the fleet controller reports a running island none of whose pushes " + "the syncer merged in N merge cycles (one outer step of every fragment) as " + "island_straggler, and again once it is merged again; the syncer keeps merging the " + "other islands at each quorum deadline. 0 turns the report off (default 3)"), cli_flag("--rl-sync-max-learners", type=int, default=None, metavar="N", help="membership: the syncer admits island ids 0..N-1, so islands may join " "after the launch (default: the launched islands; with the full-parameter " From 656a6ab47b883928e7fbe6a467b17b6ca350b704 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 20:50:18 +0800 Subject: [PATCH 02/13] island straggler: review fixes (history, store reads, clears, dashboard) - count only records of this launch: a watch starts at the current syncer incarnation's tail and ignores records older than its start; a new pool_join (generation or syncer term) restarts an island's count - bounded store reads: list after a cursor, at most 16 GETs per poll, a time budget, partial reads kept on a failed GET - a flagged island that stops running is cleared, naming why - island_straggler_unavailable names why stragglers cannot be watched - dashboard: straggler events in the event stream, a straggler mark on the trainer card and in Islands now Co-Authored-By: Claude Opus 5.5 --- tests/test_dashboard_island_straggler.py | 108 +++++++++ tests/test_island_straggler.py | 224 +++++++++++++++-- yeto/dashboard/reducer.py | 14 +- yeto/dashboard/static/app.js | 7 +- yeto/dashboard/static/sft.js | 4 +- yeto/dashboard/static/topology_diloco.js | 5 +- yeto/dashboard/topology_diloco.py | 1 + yeto/launch/fleet.py | 34 ++- yeto/launch/island_straggler.py | 292 ++++++++++++++++++----- yeto/launcher.py | 15 +- 10 files changed, 614 insertions(+), 90 deletions(-) create mode 100644 tests/test_dashboard_island_straggler.py diff --git a/tests/test_dashboard_island_straggler.py b/tests/test_dashboard_island_straggler.py new file mode 100644 index 000000000..b03b4f722 --- /dev/null +++ b/tests/test_dashboard_island_straggler.py @@ -0,0 +1,108 @@ +"""A trainer island the syncer has merged no push of for N merge cycles (``island_straggler`` +in fleet.jsonl, ``straggler`` in its record) on the dashboard: the event stream shows the +straggler events, the trainer card carries a straggler badge until it is cleared, and the +events leave the island's lifecycle state alone.""" + +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 + +from yeto.dashboard.export import export_html +from yeto.launch import island_straggler as st + +# the topology page's smoke, also printing the event stream +EV_SMOKE = SMOKE.replace('legend: mk("topoLg").innerHTML', 'legend: mk("topoLg").innerHTML, events: mk("evs").innerHTML') +assert EV_SMOKE != SMOKE + + +def _flagged(k: int = 1, at: float = T0 + 50) -> dict: + return {"event": st.EVENT, "time_unix": at, "island": f"fleet-qa-l{k}-modal", "island_id": k, + "action": st.WAIT, "missed_cycles": 3, "merges": 12, "fragments": 4, "newest_step": 40, + "last_merged_step": 28, "absent": True} + + +def _cleared(k: int = 1, at: float = T0 + 60) -> dict: + return {"event": st.CLEARED_EVENT, "time_unix": at, "island": f"fleet-qa-l{k}-modal", "island_id": k, + "missed_cycles": 0, "reason": "a push of it is merged again"} + + +def _reducer(*extra: dict): + r = fleet_reducer() + for rec in extra: + r.feed(rec) + return r + + +def _smoke(tmp: Path, r) -> dict: + node = shutil.which("node") + if node 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([node, str(tmp / "smoke.js"), str(page), "1200"], capture_output=True, text=True, + timeout=60, check=False) + assert res.returncode == 0, res.stderr + return json.loads(res.stdout) + + +def _cards(r) -> dict: + return {c["id"]: c for c in r.overview(now=r.max_ts)["islands"]} + + +def test_a_straggler_event_marks_the_card_and_keeps_its_lifecycle_state(): + plain = _cards(_reducer()) + flagged = _cards(_reducer(_flagged())) + assert flagged["1"]["straggler"] == {"action": "wait", "missed_cycles": 3, "newest_step": 40, + "last_merged_step": 28, "at": T0 + 50} + assert flagged["0"]["straggler"] is None and plain["1"]["straggler"] is None + assert flagged["1"]["status"] == plain["1"]["status"] # not a lifecycle state + assert _cards(_reducer(_flagged(), _cleared()))["1"]["straggler"] is None + + +def test_an_unavailable_watch_is_no_mark(): + rec = {"event": st.UNAVAILABLE_EVENT, "time_unix": T0 + 50, "island": "fleet-qa-l1-modal", "island_id": 1, + "reason": "the run store is not an object store"} + cards = _cards(_reducer(_flagged(), rec)) + assert cards["1"]["straggler"]["missed_cycles"] == 3 # still flagged: unavailable says nothing of it + + +def test_the_trainer_card_draws_a_straggler_badge_until_cleared(tmp_path): + flagged = _smoke(tmp_path / "a", _reducer(_flagged())) + assert "straggler" in flagged["texts"] # the topology's trainer card + assert flagged["nodes"].count("straggler") == 1 # Islands now: trainer 1's row only + for r in (_reducer(), _reducer(_flagged(), _cleared())): + out = _smoke(tmp_path / str(len(r.fleet_records)), r) + assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] + + +def test_the_island_record_s_mark_wins_over_the_events(tmp_path): + """A per-island fleet: the island's record says what the controller holds now.""" + from test_dashboard_trainer_islands import _state + + from yeto.dashboard import fleet_islands + + r = _reducer(_flagged()) + state = _state(tmp_path) + rec = {**state["trainers"][1]["record"], "launch_state": "running", "life_state": "running", + "straggler": None} + state["trainers"][1].update(record=rec, now=fleet_islands.island_state(rec, state["trainers"][1])) + r.load_fleet_state(state) + assert _cards(r)["1"]["island_now"]["straggler"] is None + out = _smoke(tmp_path / "rec", r) + assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] + + +def test_the_event_stream_shows_the_straggler_events(tmp_path): + end = fleet_reducer().max_ts # the newest events: the stream shows the latest 15 + events = _smoke(tmp_path, _reducer(_flagged(at=end + 10), _cleared(at=end + 20)))["events"] + assert "island_straggler" in events and "missed_cycles=3" in events and "action=wait" in events + assert "island_straggler_cleared" in events and "reason=a push of it is merged again" in events + assert 'title="lag"' in events and 'title="back"' in events diff --git a/tests/test_island_straggler.py b/tests/test_island_straggler.py index 416772f93..11e8c5b68 100644 --- a/tests/test_island_straggler.py +++ b/tests/test_island_straggler.py @@ -99,6 +99,10 @@ def test_only_the_running_islands_are_reported_and_zero_cycles_is_off(): tracker.feed(_join(k)) tracker.feed(_step(1, [0], fragments=1)) assert tracker.check({0: (0, 1)}) == [] # island 1 draining or recovering: not watched + (flagged,) = tracker.check(RUN2) # running again (same incarnation): reported + (closed,) = tracker.check({0: (0, 1)}) # then it stops running: its stretch is closed + assert not flagged.cleared and closed.cleared and closed.island == 1 and closed.reason == "not running" + assert tracker.check({0: (0, 1)}) == [] off = st.StragglerTracker(cycles=0) for k in (0, 1): off.feed(_join(k)) @@ -129,6 +133,59 @@ def test_the_flag_is_checked_with_the_island_pool_options(monkeypatch): rl_args._check_island_pool(args, num_islands=2) +def _at(record, t): + return dict(record, time_unix=t) + + +def test_records_from_before_the_watch_started_are_not_counted(): + """A relaunched or moved island's new launch reads the syncer's history: the merges its + earlier launch missed, and its earlier join, are stamped before the watch started.""" + tracker = st.StragglerTracker(cycles=1, since=1000.0) + tracker.feed(_at(_join(1), 900.0)) + for step in range(1, 9): + tracker.feed(_at(_step(step, [0], fragments=1), 900.0 + step)) + assert tracker.check(RUN2) == [] # nothing of it counts: island 1 has not joined since + tracker.feed(_at(_join(1), 1001.0)) + assert tracker.check(RUN2) == [] + tracker.feed(_at(_step(9, [0], fragments=1), 1002.0)) + (signal,) = tracker.check(RUN2) + assert signal.merges == 1 and signal.last_merged_step is None + + +def test_a_join_of_a_new_generation_or_syncer_term_starts_the_count_again(): + tracker = st.StragglerTracker(cycles=2) + tracker.feed(_join(1)) + for step in range(1, 3): + tracker.feed(_step(step, [0], fragments=1)) + (signal,) = tracker.check(RUN2) + assert not signal.cleared + tracker.feed(dict(_join(1), generation=1)) # a relaunch the controller did not see + (cleared,) = tracker.check(RUN2) + assert cleared.cleared and cleared.reason.startswith("rejoined (generation 1") + tracker.feed(_step(3, [0], fragments=1)) + assert tracker.check(RUN2) == [] # counted from 0 at that join: 1 of 2 + tracker.feed(dict(_join(1), generation=1, syncer_epoch=4)) # a restarted syncer's term + tracker.feed(_step(4, [0], fragments=1)) + assert tracker.check(RUN2) == [] + tracker.feed(_step(5, [0], fragments=1)) + assert [s.merges for s in tracker.check(RUN2)] == [2] + + +def test_a_relaunch_ignores_the_earlier_incarnation_s_records_read_late(): + now = [5000.0] + tracker = st.StragglerTracker(cycles=1, clock=lambda: now[0]) + tracker.feed(_at(_join(1), 4000.0)) + tracker.check(RUN2) + now[0] = 6000.0 + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] # relaunched at 6000 + tracker.feed(_at(_join(1), 5500.0)) # its earlier join, in a chunk read late + tracker.feed(_at(_step(1, [0], fragments=1), 5600.0)) + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] + tracker.feed(_at(_join(1), 6100.0)) + tracker.feed(_at(_step(2, [0], fragments=1), 6200.0)) + assert [s.merges for s in tracker.check({0: (0, 1), 1: (1, 2)})] == [1] + + # -- the syncer's tape --------------------------------------------------------------------------- def test_the_local_tape_is_read_line_by_line_from_its_offset(tmp_path): @@ -145,22 +202,121 @@ def test_the_local_tape_is_read_line_by_line_from_its_offset(tmp_path): assert st.FileTape(tmp_path / "missing.jsonl").read() == [] -def test_the_store_tape_reads_each_chunk_once_in_the_order_the_syncers_started(tmp_path): +def _chunk(objects, inc, seq, *records): + objects.write(f"tapes/syncer/{inc}/{seq:08d}.jsonl", "".join(json.dumps(r) + "\n" for r in records).encode()) + + +def test_the_store_tape_starts_at_the_tail_of_the_newest_syncer_and_reads_each_chunk_once(tmp_path): objects = DirectoryObjectStore(tmp_path / "store") - late, early = "hostb-20261126T120000Z", "hosta-20261126T130000Z" # by name the restart sorts first - objects.write(f"tapes/syncer/{late}/00000000.jsonl", (json.dumps(_join(0)) + "\n").encode()) - objects.write(f"tapes/syncer/{early}/00000000.jsonl", (json.dumps(_step(1, [0])) + "\n").encode()) + old, current = "hostb-20261126T120000Z", "hosta-20261126T130000Z" # by name the newer sorts first + _chunk(objects, old, 0, _join(1), _step(1, [0])) + _chunk(objects, current, 0, _join(1), _step(2, [0])) # the history before this watch + _chunk(objects, current, 1, _step(3, [0])) objects.write("tapes/syncer-shard1/x/00000000.jsonl", b'{"kind": "outer_step"}\n') # not this tape objects.write("tapes/l0-host-20261126T120000Z/00000000.jsonl", b'{"event": "rl_local_round"}\n') clock = [0.0] source = st.StoreTape(objects, interval_s=30, clock=lambda: clock[0]) - assert source.read() == [_join(0), _step(1, [0])] - objects.write(f"tapes/syncer/{early}/00000001.jsonl", (json.dumps(_step(2, [0])) + "\n").encode()) - assert source.read() == [] # within the poll interval: no request + assert source.read() == [] and source.polled # the tail: no history + _chunk(objects, current, 2, _step(4, [0])) + assert source.read() == [] and not source.polled # within the poll interval: no request clock[0] = 31.0 - assert source.read() == [_step(2, [0])] + assert source.read() == [_step(4, [0])] clock[0] = 62.0 assert source.read() == [] + restarted = "hosta-20261126T140000Z" # the syncer restarted: its new tape is read from its start + _chunk(objects, current, 3, _step(5, [0])) + _chunk(objects, restarted, 0, _join(0), _step(6, [0])) + got = [] + for _ in range(st.STORE_DISCOVER_POLLS): # found by the next full listing + clock[0] += 31.0 + got += source.read() + assert got == [_step(5, [0]), _join(0), _step(6, [0])] # the old one drained, then the new one + + +def test_a_watch_started_on_a_history_does_not_count_it(tmp_path): + """The relaunch case through the store: an earlier launch's history (island 1 missing + every merge) in the newest syncer incarnation; a new watch reports nothing until island 1 + joins again, then counts from 0.""" + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + _chunk(objects, inc, 0, _at(_join(0), 10.0), _at(_join(1), 10.0), + *(_at(_step(n, [0], fragments=1), 10.0 + n) for n in range(1, 9))) + clock = [0.0] + watch = st.StragglerWatch(st.StoreTape(objects, interval_s=30, clock=lambda: clock[0]), cycles=2, + since=100.0, log=lambda m: None) + assert watch.poll(RUN2) == [] + _chunk(objects, inc, 1, *(_at(_step(n, [0], fragments=1), 101.0 + n) for n in range(9, 12))) + clock[0] = 31.0 + assert watch.poll(RUN2) == [] # island 1 has not joined since the watch started + _chunk(objects, inc, 2, _at(_join(1), 120.0), _at(_step(12, [0], fragments=1), 121.0)) + clock[0] = 62.0 + assert watch.poll(RUN2) == [] # 1 merge since its join + _chunk(objects, inc, 3, _at(_step(13, [0], fragments=1), 122.0)) + clock[0] = 93.0 + (signal,) = watch.poll(RUN2) + assert signal.island == 1 and signal.merges == 2 + + +def test_the_store_tape_reads_at_most_its_chunks_per_poll_and_keeps_what_it_read(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + _chunk(objects, inc, 0, _join(0)) + clock = [0.0] + source = st.StoreTape(objects, interval_s=30, clock=lambda: clock[0], gets_per_poll=4) + assert source.read() == [] + for seq in range(1, 11): + _chunk(objects, inc, seq, _step(seq, [0])) + got = [] + for _ in range(3): + clock[0] += 31.0 + batch = source.read() + assert len(batch) <= 4 + got += batch + assert [r["step"] for r in got] == list(range(1, 11)) + + class Flaky: # the 3rd chunk read of a poll fails once + def __init__(self, inner): + self.inner, self.reads, self.failed = inner, 0, False + + def list(self, prefix, *, start_after=""): + return self.inner.list(prefix, start_after=start_after) + + def read(self, key): + self.reads += 1 + if self.reads == 3 and not self.failed: + self.failed = True + raise OSError("read timed out") + return self.inner.read(key) + + flaky = st.StoreTape(Flaky(objects), interval_s=30, clock=lambda: clock[0]) + assert flaky.read() == [] + for seq in range(11, 16): + _chunk(objects, inc, seq, _step(seq, [0])) + clock[0] += 31.0 + first = flaky.read() + assert [r["step"] for r in first] == [11, 12] and "read timed out" in flaky.error # kept, not lost + clock[0] += 31.0 + second = flaky.read() + assert [r["step"] for r in second] == [13, 14, 15] and flaky.error is None # none twice, none skipped + + +def test_a_store_poll_starts_no_request_past_its_budget(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + _chunk(objects, inc, 0, _join(0)) + ticks = [0.0] + + def clock(): # every call of the poll's clock: 1 s + ticks[0] += 1.0 + return ticks[0] + + source = st.StoreTape(objects, interval_s=0, clock=clock, budget_s=4.0) + assert source.read() == [] + for seq in range(1, 20): + _chunk(objects, inc, seq, _step(seq, [0])) + before = source.requests + batch = source.read() + assert 0 < len(batch) < 16 and source.requests - before <= 4 def test_a_watch_whose_tape_does_not_read_logs_once_and_goes_on(): @@ -181,11 +337,15 @@ def test_the_launcher_watches_an_island_pool_only(tmp_path): lines = [] pool = types.SimpleNamespace(training_mode="rl", rl_sync_island_lease_s=30.0) assert st.watch_for(types.SimpleNamespace(training_mode="rl"), objects=object(), log=lines.append) is None - assert st.watch_for(types.SimpleNamespace(**vars(pool), rl_island_straggler_cycles=0), objects=object(), - log=lines.append) is None - assert st.watch_for(pool, log=lines.append) is None and "watch off" in lines[-1] + off = st.watch_for(types.SimpleNamespace(**vars(pool), rl_island_straggler_cycles=0), objects=object(), + log=lines.append) + assert isinstance(off, st.UnavailableWatch) and off.notices() == ["turned off (--rl-island-straggler-cycles 0)"] + assert off.notices() == [] and off.poll(RUN2) == [] + none = st.watch_for(pool, log=lines.append, no_source="the syncer runs on its own VM") + assert isinstance(none, st.UnavailableWatch) and none.notices() == ["the syncer runs on its own VM"] + assert "watch off: the syncer runs on its own VM" in lines[-1] watch = st.watch_for(pool, local_tape=tmp_path / "tape.jsonl", objects=object(), log=lines.append) - assert isinstance(watch.source, st.FileTape) and watch.tracker.cycles == 3 + assert isinstance(watch.source, st.FileTape) and watch.tracker.cycles == 3 and watch.tracker.since > 0 watch = st.watch_for(pool, objects=DirectoryObjectStore(tmp_path / "s"), log=lines.append) assert isinstance(watch.source, st.StoreTape) @@ -210,6 +370,9 @@ def __init__(self): def event(self, kind, name, **fields): self.events.append((kind, name, fields)) + def kinds(self, kind): + return [e for e in self.events if e[0] == kind] + def maybe_tick(self): pass @@ -302,7 +465,9 @@ def test_a_watch_that_reads_no_syncer_record_says_so_once(): watch = st.StragglerWatch(tape, cycles=1, log=lines.append) for _ in range(st.QUIET_POLLS + 5): watch.poll(RUN2) - assert len(lines) == 1 and "no syncer record read from test tape" in lines[0] + assert len(lines) == 1 and "no syncer record read from test tape in 10 reads" in lines[0] + (notice,) = watch.notices() + assert "no syncer record" in notice and watch.notices() == [] lines.clear() read = st.StragglerWatch(tape, cycles=1, log=lines.append) tape.pending.append(_join(0)) @@ -320,12 +485,41 @@ def test_the_launcher_reads_the_store_copy_for_an_island_launch_only(tmp_path, m island = types.SimpleNamespace(**base, rl_fleet_role="island") assert isinstance(launcher._island_straggler_watch(island, states, None).source, st.StoreTape) group = types.SimpleNamespace(**base, rl_fleet_role=None) # one launch: its syncer's tape is not uploaded - assert launcher._island_straggler_watch(group, states, None) is None + off = launcher._island_straggler_watch(group, states, None) + assert isinstance(off, st.UnavailableWatch) and "a VM of its own" in off.reason local = types.SimpleNamespace(event_tape=str(tmp_path / "tape.jsonl"), _event_offset=5) watch = launcher._island_straggler_watch(group, states, local) assert isinstance(watch.source, st.FileTape) and watch.source.offset == 5 assert launcher._island_straggler_watch(island, None, None) is None # no island records: nothing written + local_store = types.SimpleNamespace(**dict(base, rl_checkpoint_store=str(tmp_path / "d")), rl_fleet_role="island") + assert "not an object store" in launcher._island_straggler_watch(local_store, states, None).reason monkeypatch.setenv("YETO_RL_TAPE_UPLOAD_S", "0") - assert launcher._island_straggler_watch(island, states, None) is None + assert "upload is off" in launcher._island_straggler_watch(island, states, None).reason with pytest.raises(SystemExit, match="whole number"): launcher._island_straggler_watch(types.SimpleNamespace(**base, rl_island_straggler_cycles=-1), states, local) + + +def test_a_flagged_island_that_stops_running_is_cleared_naming_why(tmp_path): + from yeto.launch import fleet as lf + + for setup, why in ((lambda rec: rec.update(draining=True), "stopped or removed (island STOP)"), + (lambda rec: rec.update(state=lf.RECOVERING), "relaunched"), + (lambda rec: rec.update(state=lf.DONE), "not running (done)")): + ctl, _ops, store, tape, log = _controller(tmp_path / why.split()[0]) + tape.pending += [_join(0), _join(1), _step(1, [0], fragments=1)] + ctl._poll_stragglers() + assert store.read(1)["straggler"]["action"] == "wait" + setup(ctl.learners["r-l1"]) + ctl._poll_stragglers() + (cleared,) = log.kinds(st.CLEARED_EVENT) + assert cleared[1] == "r-l1" and cleared[2]["reason"] == why + assert store.read(1)["straggler"] is None + + +def test_the_watch_s_notices_are_written_once_as_unavailable(tmp_path): + ctl, _ops, _store, _tape, log = _controller(tmp_path) + ctl.straggler = st.UnavailableWatch("the run store is not an object store") + ctl._poll_stragglers() + ctl._poll_stragglers() + why = {"reason": "the run store is not an object store"} + assert [e[1:] for e in log.kinds(st.UNAVAILABLE_EVENT)] == [("r-l0", why), ("r-l1", why)] # once per island diff --git a/yeto/dashboard/reducer.py b/yeto/dashboard/reducer.py index 3d5dfe761..e5aa6f32c 100644 --- a/yeto/dashboard/reducer.py +++ b/yeto/dashboard/reducer.py @@ -41,8 +41,11 @@ from . import topology as topology_mod from .sources import COST_EVENTS_FILE, up_state_stops +# a trainer island the syncer has merged no push of for N merge cycles, and its end (or why +# that cannot be watched): fleet.jsonl events that are not lifecycle states +STRAGGLER_EVENTS = frozenset({"island_straggler", "island_straggler_cleared", "island_straggler_unavailable"}) FLEET_EVENTS = frozenset({"island_launch", "island_ready", "island_lost", "island_stop", "island_done", - "cost_tick"}) + "cost_tick"}) | STRAGGLER_EVENTS POLICY_SWEEP_LEDGER_EVENT = "policy_sweep_ledger" # the syncer's own records (``kind``, no ``step``): its config, round opens / timeouts and # the island connections it saw; a ``learner_id`` there is not a sign of life of that island @@ -669,6 +672,7 @@ def _trainer_island_now(self, isl: dict) -> dict | None: "gpu": rec.get("gpu") or row.get("gpu"), "usd_per_h": rec.get("usd_per_h") or row.get("usd_per_h"), "incarnation": rec.get("incarnation"), "relaunches": rec.get("relaunches"), "moves": row.get("moves") or [], "name": row.get("name"), + "straggler": rec.get("straggler"), # the controller's straggler mark, None once cleared "prefix": rec.get("prefix") or row.get("prefix")} def _membership_left(self, isl: dict, now: float | None = None) -> dict | None: @@ -1452,6 +1456,13 @@ def _feed_fleet(self, r: dict, iid: str | None, ts: float | None) -> None: isl[key] = r[key] if r.get("island") is not None: isl["name"] = r["island"] + if event in STRAGGLER_EVENTS: # a mark on the card, not a lifecycle state + if event == "island_straggler": + isl["straggler"] = {**{k: r.get(k) for k in ("action", "missed_cycles", "newest_step", + "last_merged_step")}, "at": ts} + elif event == "island_straggler_cleared": + isl["straggler"] = None + return isl["fleet_state"] = event[len("island_"):] # wall clock accrues over ready -> lost/stop intervals (relaunches re-open one) if event == "island_ready" and ts is not None: @@ -1706,6 +1717,7 @@ def _island_card(self, isl: dict, now: float) -> dict: # a sampler waiting at its backlog cap writes nothing until the trainers read "waiting_backlog": waiting, "waiting_reason": waiting_why or ("backlog full" if waiting else None), "role": role, "left": left, "stale_after_s": _r(warn_s), "island_now": inow, + "straggler": isl.get("straggler"), # a sampler whose pool removed or retired it but that still runs (draining, or its # machine not released): shown running, alerted past alerts.POOL_REMOVED_GRACE_S "pool_removed": ({**pool_removed, "since_s": _r(now - pool_removed["ts"]) diff --git a/yeto/dashboard/static/app.js b/yeto/dashboard/static/app.js index 30337b9ed..730cb7534 100644 --- a/yeto/dashboard/static/app.js +++ b/yeto/dashboard/static/app.js @@ -445,14 +445,17 @@ function cost(){ } var EV_KEEP={rl_engine_selected:1,rl_driver_start:1,rl_driver_phase:1,rl_publication:1,rl_round_trained:1,rl_reconfiguration:1,rl_learner_finalized:1, island_ready:1,island_lost:1,island_stop:1,island_done:1,island_leave:1,operator_stop:1,dashboard_source_lost:1,rl_elastic_recommendation:1, - rl_policy_released:1,rl_sampler_start:1,rl_sampler_join:1,rl_sampler_policy_loaded:1,rl_sampler_backlog_full:1,rl_sampler_admitted:1,rl_sampler_stopped:1}; + rl_policy_released:1,rl_sampler_start:1,rl_sampler_join:1,rl_sampler_policy_loaded:1,rl_sampler_backlog_full:1,rl_sampler_admitted:1,rl_sampler_stopped:1, + island_straggler:1,island_straggler_cleared:1,island_straggler_unavailable:1}; var POOL_BAD=/evicted|node_lost|crash_loop|failed|breaker|timeout|overdue|orphan|refused|manual_release/; function keepEv(t){return EV_KEEP[t]||/^nc_elastic_/.test(t)} var EVENTS=[],EV_CURSOR=0; function evLevel(t,rec){if(t==="operator_stop")return ["mu","stop"]; + if(t==="island_straggler")return ["wn","lag"];if(t==="island_straggler_cleared")return ["ok","back"];if(t==="island_straggler_unavailable")return ["mu","info"]; if(/^nc_elastic_/.test(t))return POOL_BAD.test(t)?["bd","pool"]:["wn","pool"];if(t==="island_leave")return ["wn","left"];if(t==="island_lost"||(t==="rl_reconfiguration"&&rec.result==="RECOVERY_REQUIRED"))return ["bd","failure"]; if(t==="rl_publication"||t==="rl_round_trained")return ["ok","done"];if(t==="rl_reconfiguration"||t==="dashboard_source_lost")return ["wn","change"];return ["mu","info"]} -function evText(e){var r=e.record||{},keys=["phase","rollout_id","policy_version","result","cause","recommendation","marker","reason_name","backlog_groups","buffer_selected","ticket","shard","why","detail"]; +var EV_STRAGGLER_KEYS=["action","missed_cycles","newest_step","last_merged_step","reason"]; +function evText(e){var r=e.record||{},keys=/^island_straggler/.test(e.type)?EV_STRAGGLER_KEYS:["phase","rollout_id","policy_version","result","cause","recommendation","marker","reason_name","backlog_groups","buffer_selected","ticket","shard","why","detail"]; return keys.filter(function(k){return r[k]!=null}).map(function(k){return k+"="+String(r[k]).slice(0,80)}).join(" ")} /* newest first by event time; the tapes are read one after another, so arrival (seq) order is not time order. One total-order key per event: its time (an event without one takes the time of the last timed event that diff --git a/yeto/dashboard/static/sft.js b/yeto/dashboard/static/sft.js index e3595d7d3..c7805de16 100644 --- a/yeto/dashboard/static/sft.js +++ b/yeto/dashboard/static/sft.js @@ -574,7 +574,9 @@ function rlm(V){ 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 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)":""))+'
'; + 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 trainer island the syncer has merged no push of for N merge cycles (its record's mark, else its fleet event) + ((c.island_now&&"straggler" in c.island_now?c.island_now.straggler:c.straggler)&&liv?" · straggler":""))+'
'; 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(); diff --git a/yeto/dashboard/static/topology_diloco.js b/yeto/dashboard/static/topology_diloco.js index cb798a875..d77371c32 100644 --- a/yeto/dashboard/static/topology_diloco.js +++ b/yeto/dashboard/static/topology_diloco.js @@ -68,6 +68,8 @@ function islandNow(tr){var n=tr.island_now;if(!n)return null; return {stopped:["stopped: "+(n.reason||""),"mute"],done:["finished","mute"],down:["down (run down)","mute"],removed:["removed from the fleet","mute"], abandoned:["abandoned: "+(n.reason||"given up"),"bad"],failed:["failed: "+(n.reason||"")+(n.detail?" · "+n.detail:""),"bad"], 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} +// the controller's straggler mark: its record's when the island has one, else its last fleet.jsonl event +function straggler(tr){var n=tr.island_now;return (n&&"straggler" in n?n.straggler:tr.straggler)||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; var inow=islandNow(tr);if(inow)return inow; @@ -355,6 +357,7 @@ function paint(){ 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; + if(!tc.badge.textContent&&straggler(tr)&&!D.done){tc.badge.textContent="straggler";tc.badge.style.fill=C.warn} // no push merged for N merge cycles [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 L0=tc.l,lw=tc.lw; @@ -476,7 +479,7 @@ function matrix(tn){ h+=""; var finalOnSyncer=false; if(sft())h+=learnerRows(tn);else D.trainers.forEach(function(tr){var off=!tr.live&&!(tr.status==="done"||tr.finalized); - h+='Trainer '+esc(tr.id)+''+esc((tr.gpu||"")+(fin(tr.step)?" · step "+tr.step:fleet()?" · not trained yet":" · step —")+(tr.island_now?" · "+tr.island_now.state:off?" · "+(tr.status||"lost"):tr.failure?" · failed":""))+""; + h+='Trainer '+esc(tr.id)+''+esc((tr.gpu||"")+(fin(tr.step)?" · step "+tr.step:fleet()?" · not trained yet":" · step —")+(tr.island_now?" · "+tr.island_now.state:off?" · "+(tr.status||"lost"):tr.failure?" · failed":"")+(straggler(tr)&&!D.done?" · straggler":""))+""; for(var f=0;f=2?"lag2":lg===1?"lag1":"",ready=fin(s)&&H&&s>=H; var mk=pushed?'↑':lg&&tr.live?'↓'+lg+"":""; diff --git a/yeto/dashboard/topology_diloco.py b/yeto/dashboard/topology_diloco.py index 4009e4be3..fcd6e6744 100644 --- a/yeto/dashboard/topology_diloco.py +++ b/yeto/dashboard/topology_diloco.py @@ -757,6 +757,7 @@ def _trainer(iid: str, x: _Island, card: dict, st: dict, merges: list[dict], ver "arch": arch_of(card.get("gpu")), "status": st.get("status"), "live": bool(st.get("alive")), "reason": (card.get("left") or {}).get("reason"), "finalized": bool(card.get("finalized")), "island_now": card.get("island_now"), # its trainer island record (a fleet launched island by island) + "straggler": card.get("straggler"), # its last island_straggler event, None once cleared "last_event_ts": st.get("last_event_ts"), "step": step, "outer": _int(full.get("sync/outer_version")) if full else None, "versions": vec, "since": since, "pushed": {str(k): v for k, v in pushed.items()}, diff --git a/yeto/launch/fleet.py b/yeto/launch/fleet.py index 68375d288..8dc8f79c9 100644 --- a/yeto/launch/fleet.py +++ b/yeto/launch/fleet.py @@ -1063,30 +1063,56 @@ def _check_stall(self) -> None: def _poll_stragglers(self) -> None: """The straggler watch's signals for the islands running now (not draining): each one is written once (``island_straggler`` / ``island_straggler_cleared`` in fleet.jsonl, - ``straggler`` in the island's record) and its policy is asked what to do. Never - raises: a watch that fails is a missing view, not the end of supervision.""" + ``straggler`` in the island's record) and its policy is asked what to do; a flagged + island that stops running (recovering, draining, ended) is cleared, naming why. The + watch's notices (nothing can be watched here, or its tape stays silent) are written + once each as ``island_straggler_unavailable``. Never raises: a watch that fails is a + missing view, not the end of supervision.""" if self.straggler is None or self.recorder is None: return + from . import island_straggler as st + try: running, names = {}, {} for rec in self.learners.values(): ref = self.recorder.ref(rec["name"]) - if ref is None or ref.role == "sampler" or rec["state"] != RUNNING or rec.get("draining"): + if ref is None or ref.role == "sampler": continue - running[ref.island] = (rec.get("incarnation"), rec.get("job_id")) names[ref.island] = rec + if rec["state"] == RUNNING and not rec.get("draining"): + running[ref.island] = (rec.get("incarnation"), rec.get("job_id")) for signal in self.straggler.poll(running): rec = names.get(signal.island) if rec is not None: self._island_straggler(rec, signal) + # each trainer island of this launch names it (a nameless fleet.jsonl event would be + # priced as an island of its own); kept until the launch knows its islands + if names: + for why in self.straggler.notices(): + print(f"[launcher] island straggler watch: {why}", file=sys.stderr) + for rec in names.values(): + self._fleet(st.UNAVAILABLE_EVENT, rec["name"], reason=str(why)[:500]) except Exception as error: # noqa: BLE001 - a watch, never the end of supervision print(f"[launcher] island straggler watch: {type(error).__name__}: {error}"[:400], file=sys.stderr) + @staticmethod + def _not_running(rec) -> str: + """Why a flagged island's stretch ends without a merged push: its controller state.""" + if rec.get("draining") or rec.get("stop_request") is not None: + return "stopped or removed (island STOP)" + if rec["state"] == RECOVERING: + return "relaunched" + return f"not running ({rec['state']})" + def _island_straggler(self, rec, signal) -> None: + from dataclasses import replace + from . import island_straggler as st name = rec["name"] if signal.cleared: + if signal.reason == "not running": + signal = replace(signal, reason=self._not_running(rec)) print(f"[launcher] {name}: no longer a straggler ({signal.reason})", file=sys.stderr) self._fleet(st.CLEARED_EVENT, name, **st.signal_fields(signal, None)) self._record(rec, straggler=None) diff --git a/yeto/launch/island_straggler.py b/yeto/launch/island_straggler.py index b77aed107..495066e74 100644 --- a/yeto/launch/island_straggler.py +++ b/yeto/launch/island_straggler.py @@ -14,27 +14,41 @@ (the distinct ``fragment`` ids merged so far, 1 for a non-fragment pool) an island is a straggler once ``N x P`` merges in a row went by without a push of it in their weights. A push the syncer refused, or one still in flight, is not merged and does not count. -* **When counting starts.** At the island's first ``pool_join`` after it was (re)launched: - the time a launch takes to come up and join is not counted. A later re-JOIN of the same - incarnation (a lease that expired) does not restart the count. A merged push of the island - resets it. +* **Only this launch's history.** The watch reads only records stamped (``time_unix``) at or + after its own start, and the run store's copy from the tail of the newest syncer + incarnation it finds at its first read: a relaunched or moved island's new launch never + counts the merges its earlier launches missed. +* **When counting starts.** At the island's first ``pool_join`` after the watch started, or + after the controller relaunched it (a new incarnation token), or at a ``pool_join`` of a + new generation or syncer term (a relaunch the controller did not see). A later re-JOIN of + the same generation (a lease that expired) does not restart the count. A merged push of + the island resets it. An island adopted by a restarted launcher has joined before the + watch started: it is counted from its first merged push after that. * **Who is watched.** The islands the controller holds running (not draining, not - recovering): it passes their learner ids with a token of the incarnation; a new token - is a relaunch and starts the count again. + recovering): it passes their learner ids with a token of the incarnation. * **Signals.** One :class:`Straggler` when an island crosses the threshold, and one - ``cleared`` signal when a push of it is merged again (or when it was relaunched while - flagged). Nothing in between: the controller writes one event per stretch. + ``cleared`` signal when a push of it is merged again, when it rejoined as a new generation, + when it was relaunched, or when it stopped running (recovering, draining, ended): the + controller writes one event per stretch and closes each one. Sources (:func:`tape_source`): the syncer's tape file on this host (a head-mode syncer), or its copy in the run store (``tapes/syncer//.jsonl``, uploaded every 30 s -by ``yeto.rl.engine.tape_upload``). A source that does not read is skipped for that poll; -nothing here ever stops or slows the fleet. +by ``yeto.rl.engine.tape_upload``). A store read costs at most :data:`STORE_LISTS_PER_POLL` +listings of one incarnation's prefix after its last chunk read and :data:`STORE_GETS_PER_POLL` +chunk reads, and starts no new request after :data:`STORE_POLL_BUDGET_S`. Finding the syncer's +incarnations costs one listing page per incarnation, at the first read, every +:data:`STORE_DISCOVER_POLLS` reads and while none is known; the first read also lists the +newest incarnation once, for its tail. A source that does not read is skipped for that poll; nothing +here ever stops or slows the fleet. When nothing can be watched (no tape to read, the watch +turned off) or the tape stays silent for :data:`QUIET_POLLS` reads, the controller is given +one notice (``island_straggler_unavailable``). """ from __future__ import annotations import json import os +import time from collections.abc import Callable, Mapping from dataclasses import asdict, dataclass, field from pathlib import Path @@ -42,11 +56,16 @@ EVENT = "island_straggler" CLEARED_EVENT = "island_straggler_cleared" +UNAVAILABLE_EVENT = "island_straggler_unavailable" DEFAULT_CYCLES = 3 SYNCER_TAPES = "tapes/syncer/" STORE_POLL_S = 30.0 # the syncer's uploads are 30 s apart (tape_upload.DEFAULT_INTERVAL_S) +STORE_GETS_PER_POLL = 16 # chunk reads per poll; the rest waits for the next poll +STORE_LISTS_PER_POLL = 4 # listings of the incarnation being read per poll +STORE_DISCOVER_POLLS = 10 # a full listing of tapes/syncer/ (a restarted syncer) every this many reads +STORE_POLL_BUDGET_S = 5.0 # no new store request after this long in one poll MAX_READ_BYTES = 8 << 20 # one poll reads at most this much of a local tape -QUIET_POLLS = 40 # polls (20 min at 30 s) without a syncer record before that is said, once +QUIET_POLLS = 10 # reads with islands running and no syncer record yet before that is said, once WAIT = "wait" # the syncer merges without it; it is caught up once it delivers again REPLACE = "replace" # the island's provider replaces it (its own policy decides) @@ -69,7 +88,7 @@ class Straggler: """One signal about island ``island`` (its learner id).""" island: int - cleared: bool # False: it became a straggler; True: a push of it is merged again (or relaunched) + cleared: bool # False: it became a straggler; True: its stretch ended (``reason`` says how) missed_cycles: int # whole merge cycles since its last merged push (or its join) merges: int # merges since then fragments: int # P @@ -94,13 +113,29 @@ class _Island: absent: bool = False flagged: bool = False token: Any = None + generation: tuple | None = None # (syncer_epoch, generation) of the join counted from + since: float | None = None # wall time of its last relaunch: older records are another incarnation's + rejoined: str | None = None # a flagged island joined again as a new generation: why its stretch ends + + +def _time(record: Mapping[str, Any]) -> float | None: + value = record.get("time_unix") + if isinstance(value, bool): + return None + try: + return float(value) + except (TypeError, ValueError): + return None @dataclass class StragglerTracker: - """Folds syncer tape records (:meth:`feed`) and answers :meth:`check` (module doc).""" + """Folds syncer tape records (:meth:`feed`) and answers :meth:`check` (module doc). + ``since``: the watch's start (wall time); a record stamped before it is ignored.""" cycles: int = DEFAULT_CYCLES + since: float | None = None + clock: Callable[[], float] = time.time islands: dict[int, _Island] = field(default_factory=dict) fragments: set[int] = field(default_factory=set) newest_step: int | None = None @@ -112,15 +147,27 @@ def _island(self, k: int) -> _Island: def per_cycle(self) -> int: return max(1, len(self.fragments)) + @staticmethod + def _before(t: float | None, since: float | None) -> bool: + return t is not None and since is not None and t < since + def feed(self, record: Mapping[str, Any]) -> None: kind = record.get("kind") + t = _time(record) + if kind not in ("pool_join", "outer_step") or self._before(t, self.since): + return if kind == "pool_join": island = _int(record.get("island_id")) - if island is not None and not self._island(island).joined: - state = self._island(island) - state.joined, state.misses, state.absent = True, 0, False - return - if kind != "outer_step": + if island is None: + return + state = self._island(island) + if self._before(t, state.since): + return # an earlier incarnation's join, read late + generation = (record.get("syncer_epoch"), record.get("generation")) + if not state.joined or generation != state.generation: + if state.joined and state.flagged: + state.rejoined = f"rejoined (generation {generation[1]}, syncer term {generation[0]})" + state.joined, state.misses, state.absent, state.generation = True, 0, False, generation return step, fragment = _int(record.get("step")), _int(record.get("fragment")) if fragment is not None: @@ -130,10 +177,12 @@ def feed(self, record: Mapping[str, Any]) -> None: merged = {_int(entry[0]) for entry in _entries(record.get("weights")) + _entries(record.get("raw_weights"))} absent = {_int(i) for i in record.get("absent") or () if _int(i) is not None} for k, state in self.islands.items(): + if self._before(t, state.since): + continue # merged before its relaunch: not this incarnation's if k in merged: state.misses, state.absent = 0, False state.last_merged_step = step if step is not None else state.last_merged_step - state.joined = True # a merged push: it is in the pool whatever the tape showed of its join + state.joined = True # a merged push: it is in the pool (an adopted island's join came earlier) elif state.joined: state.misses += 1 state.absent = k in absent @@ -141,7 +190,8 @@ def feed(self, record: Mapping[str, Any]) -> None: self.islands[k] = _Island(joined=True, last_merged_step=step) def check(self, running: Mapping[int, Any]) -> list[Straggler]: - """The signals for the islands held running (learner id -> incarnation token).""" + """The signals for the islands held running (learner id -> incarnation token), and + the end of the stretch of a flagged island that is not running any more.""" out: list[Straggler] = [] threshold = self.cycles * self.per_cycle for k, token in running.items(): @@ -151,7 +201,12 @@ def check(self, running: Mapping[int, Any]) -> list[Straggler]: if state.flagged: out.append(self._signal(int(k), state, cleared=True, reason="relaunched")) state.joined, state.misses, state.absent, state.flagged = False, 0, False, False + state.generation, state.rejoined, state.since = None, None, self.clock() state.token = token + if state.rejoined is not None: + if state.flagged: + out.append(self._signal(int(k), state, cleared=True, reason=state.rejoined)) + state.flagged, state.rejoined = False, None if self.cycles <= 0 or not state.joined: continue if not state.flagged and state.misses >= threshold: @@ -163,8 +218,9 @@ def check(self, running: Mapping[int, Any]) -> list[Straggler]: state.flagged = False out.append(self._signal(int(k), state, cleared=True, reason="a push of it is merged again")) for k, state in self.islands.items(): - if k not in running: - state.flagged = False # not running (recovering, draining, ended): no stretch to close + if k not in running and state.flagged: + state.flagged = False + out.append(self._signal(k, state, cleared=True, reason="not running")) return out def _signal(self, k: int, state: _Island, *, cleared: bool, reason: str) -> Straggler: @@ -196,6 +252,8 @@ def __init__(self, path: str | os.PathLike[str], *, offset: int = 0) -> None: self.path = Path(os.path.expanduser(str(path))) self.offset = int(offset) # a reused host's tape: what an earlier syncer job wrote is not read self.label = str(self.path) + self.error: str | None = None + self.polled = True # every call reads def read(self) -> list[dict[str, Any]]: try: @@ -216,39 +274,118 @@ def read(self) -> list[dict[str, Any]]: return _records(data[: end + 1]) +def _incarnation_order(incarnation: str) -> tuple: + from yeto.dashboard.store_tapes import launch_started # noqa: PLC0415 + + started = launch_started(incarnation) + return (0 if started is None else 1, started or 0.0, incarnation) + + class StoreTape: - """The syncer's tape in the run store (``tapes/syncer//.jsonl``): the - chunks not read yet, incarnations in the order they started, each chunk once.""" + """The syncer's tape in the run store (``tapes/syncer//.jsonl``). + + The first read finds the newest syncer incarnation and starts at its tail: what the + syncer wrote before this watch is not read. From then on each read lists that + incarnation's prefix after its last chunk read (``start_after``) and reads its new chunks + in order, at most :data:`STORE_GETS_PER_POLL` (the rest at the next read). A newer + incarnation (a restarted syncer, found by a full listing every + :data:`STORE_DISCOVER_POLLS` reads) is read from its start once the current one has no + chunk left. A chunk read moves the cursor past it, so a request that fails keeps what was + read before it and is tried again at the next read (``error`` says why); no chunk is + read twice or skipped.""" def __init__(self, objects: Any, *, interval_s: float = STORE_POLL_S, - clock: Callable[[], float] | None = None) -> None: - import time - + clock: Callable[[], float] | None = None, gets_per_poll: int = STORE_GETS_PER_POLL, + discover_polls: int = STORE_DISCOVER_POLLS, budget_s: float = STORE_POLL_BUDGET_S) -> None: self.objects = objects self.interval_s = float(interval_s) self.clock = clock or time.monotonic + self.gets_per_poll, self.discover_polls, self.budget_s = int(gets_per_poll), int(discover_polls), budget_s + self.queue: list[str] = [] # the incarnations to read, the current one first + self.known: set[str] = set() self.cursors: dict[str, str] = {} # incarnation -> its last chunk read self.label = f"{getattr(objects, 'uri', 'store')}/{SYNCER_TAPES}" + self.error: str | None = None + self.polled = False # whether the last read() asked the store (False within the interval) + self.reads = 0 + self.requests = 0 # listings and chunk reads so far self._next: float | None = None - def read(self) -> list[dict[str, Any]]: - from yeto.dashboard.store_tapes import _launch_ordered # noqa: PLC0415 + def _incarnations(self) -> set[str]: + """The syncer incarnations under ``tapes/syncer/``: one listing page per incarnation + (a page that ends inside one jumps past the rest of its chunks).""" + page = getattr(self.objects, "list_page", None) + if not callable(page): + self.requests += 1 + return {str(k)[len(SYNCER_TAPES):].split("/")[0] for k in self.objects.list(SYNCER_TAPES) + if len(str(k)[len(SYNCER_TAPES):].split("/")) == 2} + found: set[str] = set() + cursor = "" + while True: + self.requests += 1 + keys, last = page(SYNCER_TAPES, start_after=cursor, limit=1000) + found |= {str(k)[len(SYNCER_TAPES):].split("/")[0] for k in keys + if len(str(k)[len(SYNCER_TAPES):].split("/")) == 2} + if last is None or not keys: + return found + cursor = f"{SYNCER_TAPES}{str(last)[len(SYNCER_TAPES):].split('/')[0]}/~" # past its chunks + + def _discover(self, *, first: bool) -> None: + new = sorted((inc for inc in self._incarnations() if inc not in self.known), key=_incarnation_order) + if first and new: + newest = new[-1] + self.known.update(new) + self.queue = [newest] + self.requests += 1 + chunks = [str(k) for k in self.objects.list(f"{SYNCER_TAPES}{newest}/") if str(k).endswith(".jsonl")] + self.cursors[newest] = max(chunks, default="") # its tail: what it wrote before the watch is not read + return + newer = [inc for inc in new if not self.queue or _incarnation_order(inc) > _incarnation_order(self.queue[-1])] + self.known.update(new) # an older one found late (its syncer ran before this watch): not read + self.queue += newer + def read(self) -> list[dict[str, Any]]: now = self.clock() + self.polled = False if self._next is not None and now < self._next: return [] self._next = now + self.interval_s - keys = [] - for key in self.objects.list(SYNCER_TAPES): - parts = str(key)[len(SYNCER_TAPES):].split("/") - if len(parts) == 2 and parts[1].endswith(".jsonl") and key > self.cursors.get(parts[0], ""): - keys.append(str(key)) - out: list[dict[str, Any]] = [] - for key in _launch_ordered(keys, "tapes/"): - data = self.objects.read(key) - self.cursors[key[len(SYNCER_TAPES):].split("/")[0]] = key - if data: - out += _records(data if isinstance(data, bytes) else str(data).encode()) + self.polled, self.error = True, None + started, out, gets, lists = self.clock(), [], 0, 0 + first = self.reads == 0 + self.reads += 1 + try: + if first or not self.queue or self.reads % self.discover_polls == 0: + self._discover(first=first) + if first: + return [] + while self.queue and gets < self.gets_per_poll and lists < STORE_LISTS_PER_POLL \ + and self.clock() - started < self.budget_s: + inc = self.queue[0] + lists += 1 + self.requests += 1 + keys = sorted(str(k) for k in self.objects.list(f"{SYNCER_TAPES}{inc}/", + start_after=self.cursors.get(inc, "")) + if str(k).endswith(".jsonl") and str(k) > self.cursors.get(inc, "")) + if not keys: + if len(self.queue) > 1: + self.queue.pop(0) # a newer syncer incarnation took over: read it from its start + continue + break + for key in keys: + if gets >= self.gets_per_poll or self.clock() - started >= self.budget_s: + break + gets += 1 + self.requests += 1 + data = self.objects.read(key) + self.cursors[inc] = key + if data: + out += _records(data if isinstance(data, bytes) else str(data).encode()) + else: + continue + break + except Exception as error: # noqa: BLE001 - what was read is kept; the rest at the next read + self.error = f"{type(error).__name__}: {error}"[:300] return out @@ -267,40 +404,66 @@ def _records(data: bytes) -> list[dict[str, Any]]: class StragglerWatch: """A tracker fed from one source: :meth:`poll` reads what the syncer added and returns the signals for the islands held running. A read that fails is logged once per stretch - of failures and tried again at the next poll.""" + of failures and tried again at the next poll. :meth:`notices` hands the controller, once, + why nothing is reported (the source stayed silent for :data:`QUIET_POLLS` reads).""" - def __init__(self, source: Any, *, cycles: int = DEFAULT_CYCLES, - log: Callable[[str], None] | None = None) -> None: + def __init__(self, source: Any, *, cycles: int = DEFAULT_CYCLES, since: float | None = None, + log: Callable[[str], None] | None = None, clock: Callable[[], float] = time.time) -> None: import sys self.source = source - self.tracker = StragglerTracker(cycles=int(cycles)) + self.tracker = StragglerTracker(cycles=int(cycles), since=since, clock=clock) self.log = log or (lambda m: print(m, file=sys.stderr, flush=True)) self._failing = False - self._empty_polls = 0 # polls with islands running and no syncer record read yet + self._quiet = 0 # reads with islands running and no syncer record yet; -1 once one was read + self._notices: list[str] = [] def poll(self, running: Mapping[int, Any]) -> list[Straggler]: try: records = self.source.read() - except Exception as error: # noqa: BLE001 - a watch, never the end of supervision + error = getattr(self.source, "error", None) + except Exception as raised: # noqa: BLE001 - a watch, never the end of supervision + records, error = [], f"{type(raised).__name__}: {raised}" + if error is not None: if not self._failing: self.log(f"[launcher] island straggler watch: the syncer tape {self.source.label} does not read " - f"({type(error).__name__}: {error}); tried again next poll"[:400]) + f"({error}); tried again next poll"[:400]) self._failing = True - records = [] else: self._failing = False for record in records: self.tracker.feed(record) if records: - self._empty_polls = -1 - elif running and self._empty_polls >= 0: - self._empty_polls += 1 - if self._empty_polls == QUIET_POLLS: - self.log(f"[launcher] island straggler watch: no syncer record read from {self.source.label} in " - f"{QUIET_POLLS} polls; no straggler is reported until the syncer's tape is there") + self._quiet = -1 + elif running and self._quiet >= 0 and getattr(self.source, "polled", True): + self._quiet += 1 + if self._quiet == QUIET_POLLS: + why = (f"no syncer record read from {self.source.label} in {QUIET_POLLS} reads; no straggler is " + "reported until the syncer's tape is there") + self.log(f"[launcher] WARNING: island straggler watch: {why}") + self._notices.append(why) return self.tracker.check(running) + def notices(self) -> list[str]: + out, self._notices = self._notices, [] + return out + + +class UnavailableWatch: + """An island pool whose stragglers cannot be watched from here: no signal ever, and one + notice saying why (the controller writes it as ``island_straggler_unavailable``).""" + + def __init__(self, reason: str) -> None: + self.reason = reason + self._notices = [reason] + + def poll(self, running: Mapping[int, Any]) -> list[Straggler]: + return [] + + def notices(self) -> list[str]: + out, self._notices = self._notices, [] + return out + def tape_source(*, local_tape: str | os.PathLike[str] | None = None, local_offset: int = 0, objects: Any = None) -> Any: @@ -314,28 +477,31 @@ def tape_source(*, local_tape: str | os.PathLike[str] | None = None, local_offse def watch_for(args: Any, *, local_tape: str | os.PathLike[str] | None = None, local_offset: int = 0, - objects: Any = None, log: Callable[[str], None] | None = None) -> StragglerWatch | None: + objects: Any = None, log: Callable[[str], None] | None = None, + no_source: str | None = None) -> StragglerWatch | UnavailableWatch | None: """The launcher's watch of an island pool (``--rl-island-straggler-cycles``, default 3; - 0 turns it off): None without an island pool, with the watch off, or with no syncer tape - to read from here (said once).""" + 0 turns it off): None without an island pool. With the watch off, or with no syncer + tape to read from here (``no_source``: why), an :class:`UnavailableWatch` that says so + once. The watch counts only what the syncer records from now on.""" import sys from .syncer import island_pool if getattr(args, "training_mode", "sft") != "rl" or not island_pool(args): return None + say = log or (lambda m: print(m, file=sys.stderr, flush=True)) cycles = straggler_cycles(args) if cycles == 0: - return None + say("[launcher] island straggler watch off (--rl-island-straggler-cycles 0)") + return UnavailableWatch("turned off (--rl-island-straggler-cycles 0)") source = tape_source(local_tape=local_tape, local_offset=local_offset, objects=objects) - say = log or (lambda m: print(m, file=sys.stderr, flush=True)) if source is None: - say("[launcher] island straggler watch off: no syncer tape to read here (a syncer on this host, or " - "the run store's tapes/syncer/)") - return None + why = no_source or "no syncer tape to read here (a syncer on this host, or the run store's tapes/syncer/)" + say(f"[launcher] island straggler watch off: {why}") + return UnavailableWatch(why) say(f"[launcher] island straggler watch: an island none of whose pushes is merged in {cycles} merge " f"cycle(s) is reported ({EVENT}); syncer tape {source.label}") - return StragglerWatch(source, cycles=cycles, log=log) + return StragglerWatch(source, cycles=cycles, since=time.time(), log=log) def signal_fields(signal: Straggler, action: str | None) -> dict[str, Any]: diff --git a/yeto/launcher.py b/yeto/launcher.py index 8ef0ebd31..3d0a402ac 100644 --- a/yeto/launcher.py +++ b/yeto/launcher.py @@ -702,12 +702,21 @@ def _island_straggler_watch(args, island_states, local_syncer): from .rl.engine.sample_roles import FLEET_ROLE_ISLAND, fleet_role from .rl.engine.tape_upload import upload_interval_s - uploaded = (fleet_role(args) == FLEET_ROLE_ISLAND and upload_interval_s() is not None - and is_object_store_uri(str(getattr(args, "rl_checkpoint_store", None) or ""))) + store = str(getattr(args, "rl_checkpoint_store", None) or "") + if fleet_role(args) != FLEET_ROLE_ISLAND: + why = ("the fleet's syncer runs on a VM of its own and a launch of every island does not copy its tape " + "to the run store; run the syncer on this host (--controller head) or launch the fleet island by " + "island (fleet.launch per_island)") + elif upload_interval_s() is None: + why = "the syncer launch's tape upload is off (YETO_RL_TAPE_UPLOAD_S=0)" + elif not is_object_store_uri(store): + why = f"the run store {store or '(none)'} is not an object store: the syncer launch uploads no tape to it" + else: + why = None try: return watch_for(args, local_tape=getattr(local_syncer, "event_tape", None), local_offset=int(getattr(local_syncer, "_event_offset", 0) or 0), - objects=getattr(island_states, "objects", None) if uploaded else None) + objects=getattr(island_states, "objects", None) if why is None else None, no_source=why) except ValueError as error: raise SystemExit(str(error)) from None From a91a93b09fff8c72d4c91ba4afe5732dca7f058c Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 21:04:55 +0800 Subject: [PATCH 03/13] island straggler: count from leaving running; per-island e2e over the run store - an island's count restarts when it leaves running, so a join its next incarnation writes before the controller holds it running is counted - e2e: the stuck case over the per-island wiring (the launcher's watch of each launch's argv, the tape uploaded to the run store in chunks next to an earlier syncer's history, a relaunch while reported); assertion limits noted - docs: what is counted, the clear reasons, island_straggler_unavailable and why a synced group with its own syncer VM has no report Co-Authored-By: Claude Opus 5.5 --- docs/OWN_CLUSTERS.md | 52 +++-- tests/test_dashboard_island_straggler.py | 3 +- tests/test_island_straggler.py | 41 +++- tests/test_own_clusters_islands_doc.py | 8 +- tests/test_ssh_island_fleet_e2e.py | 264 +++++++++++++++++++++-- yeto/launch/island_straggler.py | 43 ++-- 6 files changed, 364 insertions(+), 47 deletions(-) diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index fab94e271..607bc0e0f 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -504,11 +504,23 @@ when none of the island's pushes was merged in `N` merge cycles it writes: shown by `yeto island status`). A merge cycle is one outer step of every fragment, so with 4 fragments and `N = 3` the -island is reported after 12 merges without it. Counting starts when the island joins the -syncer after a launch or relaunch, so the time an island takes to start is not counted. A -push the syncer refused does not count as merged. The report is written once per stretch. -`island_straggler_cleared` follows once a push of the island is merged again, and its record's -`straggler` is set back to `null`. +island is reported after 12 merges without it. A push the syncer refused does not count as +merged. Counting starts when the island joins the syncer: + +- A launch counts only what the syncer records after the launch started. A relaunched or + moved island's new launch never counts the merges an earlier launch of it missed. +- When the island stops running (its controller relaunches it, or it is stopped), its count + starts again at its next join. The time an island takes to start is not counted. +- An island adopted by a restarted launcher joined before the launcher started. It is + counted from its first merged push. + +The report is written once per stretch. `island_straggler_cleared` closes the stretch, and its +`reason` says why: a push of the island is merged again, it was `relaunched`, it was stopped +or removed (island STOP), or it is no longer running. The record's `straggler` is set back to +`null` at the same time. + +The dashboard shows both events in its event stream. While the island is reported, its +trainer card carries a `straggler` badge and its row in "Islands now" says `straggler`. `action` is what the controller does about it. The default is `wait`: nothing is stopped or relaunched, because the syncer already merges without the island. A lost or unhealthy node @@ -527,13 +539,29 @@ The controller reads the syncer's tape in one of two places: - from the syncer's own file, when the syncer runs on the same host as the controller (`--controller head`); -- otherwise from its copy in the run store, `tapes/syncer//.jsonl`. The - syncer launch uploads it every 30 s (`YETO_RL_TAPE_UPLOAD_S`) when `--rl-checkpoint-store` - is an `s3://` store. With another store, or with the upload off (`YETO_RL_TAPE_UPLOAD_S=0`), - the launch prints `island straggler watch off` and nothing is reported. Training is not - affected either way. - -The report comes at most one upload interval after the merges it counts. +- otherwise, in a fleet launched island by island (`fleet.launch: per_island`), from its + copy in the run store, `tapes/syncer//.jsonl`. The syncer launch + uploads it every 30 s (`YETO_RL_TAPE_UPLOAD_S`) when `--rl-checkpoint-store` is an + `s3://` store. Each island launch reads it every 30 s, starting at the end of the newest + syncer incarnation it finds. + +The report comes at most one upload interval and one read interval after the merges it +counts. + +When the report cannot work, the launch prints `island straggler watch off` and writes +`island_straggler_unavailable` once, with the `reason`, in `fleet.jsonl`. Nothing is +reported then, and training is not affected. This happens: + +- with `--rl-island-straggler-cycles 0`; +- in a per-island fleet whose run store is not an object store, or with the upload off + (`YETO_RL_TAPE_UPLOAD_S=0`); +- in a fleet launched as one launch (`fleet.launch: synced_group`) whose syncer runs on a VM + of its own (any `--controller` other than `head`). That syncer's tape stays on its VM: + the launch does not upload it to the run store, so the controller has nothing to read. + Run the syncer on the controller's host (`--controller head`) or launch the fleet island + by island to get the report. +- when the launch reads no syncer record for 10 reads in a row (the store copy is missing + or stale). ### Removing an island diff --git a/tests/test_dashboard_island_straggler.py b/tests/test_dashboard_island_straggler.py index b03b4f722..68c5fdc27 100644 --- a/tests/test_dashboard_island_straggler.py +++ b/tests/test_dashboard_island_straggler.py @@ -18,7 +18,8 @@ from yeto.launch import island_straggler as st # the topology page's smoke, also printing the event stream -EV_SMOKE = SMOKE.replace('legend: mk("topoLg").innerHTML', 'legend: mk("topoLg").innerHTML, events: mk("evs").innerHTML') +LEGEND = 'legend: mk("topoLg").innerHTML' +EV_SMOKE = SMOKE.replace(LEGEND, LEGEND + ', events: mk("evs").innerHTML') assert EV_SMOKE != SMOKE diff --git a/tests/test_island_straggler.py b/tests/test_island_straggler.py index 11e8c5b68..8fc36d7e6 100644 --- a/tests/test_island_straggler.py +++ b/tests/test_island_straggler.py @@ -10,8 +10,8 @@ import types import pytest - from test_controller import RUNNING, SYNCER, FakeOps, ImmediateThread + from yeto.launch import island_lifecycle as lc from yeto.launch import island_straggler as st from yeto.launch.fleet import FleetController @@ -186,6 +186,41 @@ def test_a_relaunch_ignores_the_earlier_incarnation_s_records_read_late(): assert [s.merges for s in tracker.check({0: (0, 1), 1: (1, 2)})] == [1] +def test_a_join_recorded_before_the_controller_holds_the_new_incarnation_running_counts(): + """Recovering at 6000 (the island left running), its new incarnation joins at 6100, and only + then does the controller hold it running (a new token): the join is the new incarnation's, + so the island is counted from it, not left uncounted until a push of it merges.""" + now = [5000.0] + tracker = st.StragglerTracker(cycles=1, clock=lambda: now[0]) + tracker.feed(_at(_join(1), 4000.0)) + tracker.check(RUN2) + now[0] = 6000.0 + assert tracker.check({0: (0, 1)}) == [] # island 1 recovering + tracker.feed(_at(_step(1, [0], fragments=1), 5900.0)) # its earlier incarnation's stretch + tracker.feed(_at(dict(_join(1), catch_up=True), 6100.0)) + assert tracker.check({0: (0, 1)}) == [] # not held running: never reported + tracker.feed(_at(_step(2, [0], fragments=1), 6200.0)) + now[0] = 6300.0 + (signal,) = tracker.check({0: (0, 1), 1: (1, 2)}) # running again: counted from its join + assert not signal.cleared and signal.island == 1 and signal.merges == 1 + + +def test_an_island_back_running_as_the_same_incarnation_keeps_its_place_in_the_pool(): + tracker = st.StragglerTracker(cycles=1) + tracker.feed(_join(1)) + tracker.check(RUN2) + assert tracker.check({0: (0, 1)}) == [] + tracker.check(RUN2) # the same token back + tracker.feed(_step(1, [0], fragments=1)) + assert [s.island for s in tracker.check(RUN2)] == [1] + fresh = st.StragglerTracker(cycles=1) # never joined before it left: still not counted + fresh.check(RUN2) + fresh.check({0: (0, 1)}) + fresh.check(RUN2) + fresh.feed(_step(1, [0], fragments=1)) + assert fresh.check(RUN2) == [] + + # -- the syncer's tape --------------------------------------------------------------------------- def test_the_local_tape_is_read_line_by_line_from_its_offset(tmp_path): @@ -432,7 +467,7 @@ def __call__(self, name, signal): def replace(self, name, signal): replaced.append(name) - ctl, _ops, store, tape, log = _controller(tmp_path, policy=Policy()) + ctl, _ops, store, tape, _log = _controller(tmp_path, policy=Policy()) tape.pending += [_join(0), _join(1), _step(1, [0], fragments=1)] ctl._poll_stragglers() assert asked == [("r-l1", 1)] and replaced == ["r-l1"] @@ -481,7 +516,7 @@ def test_the_launcher_reads_the_store_copy_for_an_island_launch_only(tmp_path, m monkeypatch.delenv("YETO_RL_TAPE_UPLOAD_S", raising=False) states = types.SimpleNamespace(objects=DirectoryObjectStore(tmp_path / "s")) - base = dict(training_mode="rl", rl_sync_island_lease_s=30.0, rl_checkpoint_store="s3://b/runs/r") + base = {"training_mode": "rl", "rl_sync_island_lease_s": 30.0, "rl_checkpoint_store": "s3://b/runs/r"} island = types.SimpleNamespace(**base, rl_fleet_role="island") assert isinstance(launcher._island_straggler_watch(island, states, None).source, st.StoreTape) group = types.SimpleNamespace(**base, rl_fleet_role=None) # one launch: its syncer's tape is not uploaded diff --git a/tests/test_own_clusters_islands_doc.py b/tests/test_own_clusters_islands_doc.py index 1101815c5..794d31cc4 100644 --- a/tests/test_own_clusters_islands_doc.py +++ b/tests/test_own_clusters_islands_doc.py @@ -10,6 +10,7 @@ from pathlib import Path from test_fleet_island_changes import fleet_store # noqa: F401 - fixture + from yeto.launch import island_straggler as st from yeto.rl import fleet, fleet_islands @@ -26,7 +27,7 @@ def section() -> str: def commands() -> list[list[str]]: out = [] - for block in re.findall(r"```bash\n(.*?)```", section(), flags=re.S): + for block in re.findall(r"```bash\n(.*?)```", section(), flags=re.DOTALL): out += [shlex.split(line) for line in block.replace("\\\n", " ").splitlines() if line.strip()] inline = re.findall(r"`(yeto island (?:stop|start) [^`]+)`", section()) return out + [shlex.split(c) for c in inline] @@ -35,8 +36,9 @@ def commands() -> list[list[str]]: def test_the_section_names_the_code_s_flags_and_events(): text = section() assert "--rl-island-straggler-cycles" in text and f"`{st.DEFAULT_CYCLES}` is the default" in text - for name in (st.EVENT, st.CLEARED_EVENT, st.WAIT, st.SYNCER_TAPES.rstrip("/")): + for name in (st.EVENT, st.CLEARED_EVENT, st.UNAVAILABLE_EVENT, st.WAIT, st.SYNCER_TAPES.rstrip("/")): assert name in text + assert f"{st.QUIET_POLLS} reads in a row" in text and f"every {st.STORE_POLL_S:g} s" in text for field in st.Straggler.__dataclass_fields__: if field not in ("island", "cleared", "cycles", "reason"): assert f"`{field}`" in text, field @@ -45,7 +47,7 @@ def test_the_section_names_the_code_s_flags_and_events(): def test_the_section_commands_run_in_order(fleet_store, capsys): # noqa: F811 from yeto.cli import build_parser - cfg, objects, store, run_cli, samplers = fleet_store + cfg, _objects, store, run_cli, _samplers = fleet_store argvs = commands() assert {a[1] for a in argvs} == {"fleet", "island"} for argv in argvs: diff --git a/tests/test_ssh_island_fleet_e2e.py b/tests/test_ssh_island_fleet_e2e.py index b3cd3d2c2..166c18430 100644 --- a/tests/test_ssh_island_fleet_e2e.py +++ b/tests/test_ssh_island_fleet_e2e.py @@ -23,6 +23,10 @@ Each case checks that the other islands' processes never restarted (one start per node, no kill before the end, one launch), that the merged steps run 1..N without a gap or a repeat, that no push is merged twice, and that the resource ledger holds each SSH incarnation once. + +A fourth test runs the stuck case over the per-island wiring: each launch's watch is the +launcher's own for its argv and reads the syncer's tape from the run store, uploaded in +chunks, past an earlier syncer's history; island 1 is relaunched while it is reported. """ from __future__ import annotations @@ -33,13 +37,27 @@ from collections import Counter import pytest - from test_fleet_island_launches import example_doc from test_fleet_trainer_worker import FakeLaunches -from test_rl_full_parameter_async import _f32, _initial, _start_async_syncer, _wait, needs_cargo -from test_rl_full_parameter_async import syncer_binary # noqa: F401 - fixture -from test_rl_full_parameter_dynamic_members import LAUNCHED, MAX_LEARNERS, P, POOL, _client, _delta, _outer_steps +from test_rl_full_parameter_async import ( + _f32, + _initial, + _start_async_syncer, + _wait, + needs_cargo, + syncer_binary, # noqa: F401 - fixture +) +from test_rl_full_parameter_dynamic_members import ( + LAUNCHED, + MAX_LEARNERS, + POOL, + P, + _client, + _delta, + _outer_steps, +) from test_rl_ssh_resident import FakeCluster, b300 + from yeto.cost.ledger import ResourceLedger from yeto.hw import card_tools from yeto.launch import island_lifecycle as lifecycle @@ -51,8 +69,7 @@ from yeto.launch.ssh_trainer_island import SshTrainerSpec from yeto.launch.ssh_trainer_ledger import KIND as SSH_TRAINER from yeto.modal_runner import RoutingOps -from yeto.rl import fleet, fleet_islands, island_launches, trainer_worker -from yeto.rl import up +from yeto.rl import fleet, fleet_islands, island_launches, trainer_worker, up from yeto.rl.engine.object_store import DirectoryObjectStore GPU = "ssh:2x8xb300@bm" @@ -78,6 +95,7 @@ def __init__(self) -> None: self.rank0 = {nodes[0].name: k for k, nodes in NODES.items()} self.trainer_starts: list[int] = [] self.trainer_kills: list[int] = [] + self.trainer_events: list[tuple[str, int]] = [] # both, in order (a relaunch: kill, then start) self.guard = threading.Lock() def start(self, node, script): @@ -85,6 +103,7 @@ def start(self, node, script): if "setsid bash -c" in script and node.name in self.rank0: with self.guard: self.trainer_starts.append(self.rank0[node.name]) + self.trainer_events.append(("start", self.rank0[node.name])) return stream def run(self, node, script, *, timeout=300.0): @@ -92,13 +111,15 @@ def run(self, node, script, *, timeout=300.0): if "kill -TERM" in script and node.name in self.rank0: with self.guard: self.trainer_kills.append(self.rank0[node.name]) + self.trainer_events.append(("kill", self.rank0[node.name])) return out def finish(self, k: int) -> None: - """Island k's trainer ended its run: every rank exits 0 (rank 0 last).""" + """Island k's trainer ended its run: every rank of its newest incarnation exits 0 (rank 0 last).""" for node in reversed(NODES[k]): - if self.runs[node.name].get(0, {}).get("state") == "running": - self.exit(node.name, 0, 0) + runs = self.runs[node.name] + if runs and runs[max(runs)].get("state") == "running": + self.exit(node.name, max(runs), 0) class FastClock: @@ -148,9 +169,12 @@ class SshIslandLaunches(FakeLaunches): fleet: the resident ssh: island ops on its inventory nodes and the fleet controller supervising it (its island STOP, its record, the straggler watch), on a thread.""" - def __init__(self, tmp_path, cluster: TrainerCluster, objects, tape) -> None: + def __init__(self, tmp_path, cluster: TrainerCluster, objects, tape, watch=None) -> None: super().__init__() self.tmp_path, self.cluster, self.objects, self.tape = tmp_path, cluster, objects, tape + # the straggler watch of a launch (its argv, its island records); the syncer's tape file by default + self.watch = watch or (lambda argv, states: st.StragglerWatch(st.FileTape(tape), cycles=CYCLES, + log=lambda m: None)) self.controllers: dict[int, FleetController] = {} self.logs: dict[int, FleetLog] = {} self.errors: list[BaseException] = [] @@ -166,13 +190,13 @@ def start(self, prefix: str, argv: list[str]) -> int: ops.add(name, spec) job = ops.start(name) log = self.logs[k] = FleetLog() - recorder = lifecycle.FleetRecorder(lifecycle.IslandStateStore(self.objects, log=lambda m: None), - {name: lifecycle.IslandRef(k, "ssh")}) + states = lifecycle.IslandStateStore(self.objects, log=lambda m: None) + recorder = lifecycle.FleetRecorder(states, {name: lifecycle.IslandRef(k, "ssh")}) ctl = self.controllers[k] = FleetController( learners={name: (spec, job)}, syncer=None, sky_ops=RoutingOps(FastClock(), None, ssh_ops=ops), poll_interval=30.0, recover_timeout=600.0, thread_cls=_SyncThread, recorder=recorder, elastic=True, deterministic_stop=True, fleet_log=log, - straggler=st.StragglerWatch(st.FileTape(self.tape), cycles=CYCLES, log=lambda m: None)) + straggler=self.watch(argv, states)) def supervise(): code = 0 @@ -334,7 +358,10 @@ def poll(): process.wait(timeout=10) assert not launches.errors, launches.errors - # -- the other islands were never touched: one start per node, one launch, no kill before the end + # -- the other islands were never touched: one start per node, one launch, no kill before the end. + # Limit: these count the start / kill scripts the control plane sent to the fake nodes (and the + # worker's launches), not OS processes; they prove yeto restarted nothing, not that nothing on + # a real node could restart a rank by itself. others = {"add": [0, 1], "remove": [0], "stuck": [0, 1]}[case] for k in others: assert started[k] == 1 and launches.started(f"r-i{k}") == 1 @@ -348,7 +375,9 @@ def poll(): worker.step() assert worker.load(1)["state"] == trainer_worker.REMOVED - # -- the merges: steps 1..N without a gap or a repeat, no push merged twice + # -- the merges: steps 1..N without a gap or a repeat, no push merged twice. + # Limit: a push is keyed by (island, the step it was pushed for); a delta carried into a later + # round keeps its own step, so this catches a double merge, not a wrong carry-over discount. steps = _outer_steps(tape.read_text()) assert [r["step"] for r in steps] == list(range(1, total_steps * P + 1)) merged = [(int(e[0]), pushed) for r in steps for e, pushed in zip(r["raw_weights"], r["pushed_for"])] @@ -362,6 +391,9 @@ def poll(): assert min(state["joined_at"]) >= change_at and first > max(state["joined_at"]) if case == "remove": leave = next(r for r in _records(tape) if r.get("kind") == "pool_leave" and int(r["island_id"]) == 1) + # Limit: by wall time, skipping one cycle of rounds per fragment pair (2 x P): the rounds open + # at the leave may still merge a push island 1 sent before it; this does not pin the round + # its last push merged in, only that island 0 merges alone from then on. after = [r for r in steps if r.get("time_unix", 0) > leave.get("time_unix", 0)][2 * P:] assert after and all([int(e[0]) for e in r["raw_weights"]] == [0] for r in after) @@ -373,7 +405,9 @@ def poll(): assert len(launches.logs[1].kinds(st.CLEARED_EVENT)) == 1 assert states.read(1)["straggler"] is None # cleared in its record too absent = [r for r in steps if r["absent"] == [1]] - assert any(r["timed_out"] for r in absent) # merged at the quorum deadline without it + # merged at the quorum deadline without it. Limit: "any", because which of the rounds without + # island 1 waited for the deadline depends on when its PULL was answered before it went silent + assert any(r["timed_out"] for r in absent) assert launches.controllers[1].learners["r-i1-trainer"]["relaunches"] == 0 for k, log in launches.logs.items(): if case != "stuck" or k != 1: @@ -388,6 +422,204 @@ def poll(): assert set(created.values()) == {1} and all(n == 1 for n in released.values()) +def _launch_args(argv): + """The args ``yeto launch`` parses from an island launch's argv.""" + from yeto.cli import build_parser + + return build_parser().parse_args(["launch", *argv]) + + +@needs_cargo +def test_a_stuck_island_relaunched_mid_run_is_watched_over_the_run_store(syncer_binary, tmp_path, # noqa: F811 + monkeypatch): + """The stuck case over the per-island wiring: each island launch's watch is the launcher's + own (``launcher._island_straggler_watch`` of its parsed argv and its island records), so it + reads the syncer's tape from the run store (a ``DirectoryObjectStore`` here), where the + syncer launch's uploaders copy it chunk by chunk (``tapes/syncer//``). The + store also holds an earlier syncer's history in which island 1 missed 40 merges: it is + never counted. Island 1 stops pushing and is reported once; then one of its ranks fails, + its controller relaunches it (cleared: relaunched); the new incarnation joins again + (catch-up) and stays silent: it is reported again only after N merge cycles counted from + that join; then it pushes and the mark is cleared. Island 0 is never touched.""" + from yeto import launcher + from yeto.rl.engine.tape_upload import syncer_incarnation, syncer_uploaders + + monkeypatch.delenv("YETO_RL_TAPE_UPLOAD_S", raising=False) + cfg = _config(tmp_path) + plan = fleet.plan_of(cfg) + objects = DirectoryObjectStore(tmp_path / "store") + store = dz.DesiredStore(objects) + store.apply({"members": [*island_launches.trainer_members(cfg, plan), + *({"kind": "sampler_pool", "name": p.name, "island": i.index, + "pool": {"provider": "modal"}} for i in plan.islands for p in i.pools)]}, expect=0) + old = time.time() - 3600 # an earlier syncer of the run: island 1 missing from its last 40 merges + history = [{"kind": "pool_join", "island_id": k, "generation": 0, "syncer_epoch": 0, "time_unix": old} + for k in (0, 1)] + history += [{"kind": "outer_step", "step": n, "fragment": (n - 1) % P, "weights": [[0, n - 1, 1.0]], + "raw_weights": [[0, n - 1, 1.0]], "absent": [1], "time_unix": old + n} for n in range(1, 41)] + objects.write(f"{st.SYNCER_TAPES}oldhost-20200101T000000Z/00000000.jsonl", + "".join(json.dumps(r) + "\n" for r in history).encode()) + total_steps, change_at = 30, 3 + process, port, profile_hash = _start_async_syncer(syncer_binary, tmp_path, *STUCK_POOL, total_steps=total_steps, + log_file=tmp_path / "syncer.log") + tape = tmp_path / "tape.jsonl" + uploaders = syncer_uploaders(objects, tape, incarnation=syncer_incarnation(), interval_s=0.3, from_end=False, + log=lambda m: None) + island_launches.write_syncer_record(objects, addr=f"127.0.0.1:{port}", syncer_epoch=0, learners=LAUNCHED, + max_learners=MAX_LEARNERS, run="r") + states = lifecycle.IslandStateStore(objects, log=lambda m: None) + watches = {} + + def watch(argv, island_states): + w = launcher._island_straggler_watch(_launch_args(argv), island_states, None) + w.source.interval_s = 0.2 # a store read every 0.2 s, not every 30 s + watches[int(argv[argv.index("--rl-fleet-learner-id") + 1])] = w + return w + + cluster = TrainerCluster() + launches = SshIslandLaunches(tmp_path, cluster, objects, tape, watch=watch) + worker = trainer_worker.TrainerWorker(store, objects, launches, states, log=lambda m: None) + + clients: dict[int, object] = {} + catching: dict[int, dict] = {} + versions = {k: [0] * P for k in range(LAUNCHED)} + seen: dict[int, set] = {k: set() for k in range(LAUNCHED)} + held: dict[int, list] = {} + phase = {"name": "train", "events": 0} + beat = [0.0] + + def follow_the_nodes(): + with cluster.guard: + events = list(cluster.trainer_events) + for what, k in events[phase["events"]:]: + phase["events"] += 1 + if what == "kill" and k in clients: # its incarnation torn down: the connection drops + clients.pop(k).close() + elif what == "start": + if k in clients: + clients.pop(k).close() + clients[k] = _client(k, port, profile_hash) + clients[k].start() + if phase["name"] != "train": # a relaunched trainer catches up before it answers + catching[k] = {} + seen[k].clear() + + def drain(k): + client = clients[k] + client.check_health() + if k in catching: + for update in client.drain_updates(): + catching[k].setdefault(update.fragment_id, update.version) + held.setdefault(k, []).extend(client.drain_pulls()) + if len(catching[k]) < P: + return + caught = catching.pop(k) + versions[k] = [caught[fid] for fid in range(P)] + for update in client.drain_updates(): + versions[k][update.fragment_id] = max(versions[k][update.fragment_id], update.version) + if k == 1 and phase["name"] in ("stuck", "relaunching", "stuck again"): + held.pop(k, None) + client.drain_pulls() + return # connected (its heartbeats go on), delivering nothing + for permit in held.pop(k, []) + client.drain_pulls(): + key = (permit.global_step, permit.round_attempt) + if key in seen[k]: + continue + seen[k].add(key) + client.push_fragment(permit.fragment_id, permit.global_step, permit.round_attempt, + versions[k][permit.fragment_id], permit.global_step, 1, 7, + _f32(_delta(k, permit.global_step))) + + def poll(): + assert not launches.errors, launches.errors + if time.monotonic() - beat[0] > 1: + beat[0] = time.monotonic() + for client in list(clients.values()): + client.heartbeat(0) + worker.step() + follow_the_nodes() + for k in list(clients): + drain(k) + log = launches.logs[1] + if phase["name"] == "train" and len(clients) == LAUNCHED and min(versions[0]) >= change_at: + # the history in the store and the merges so far reported nobody + assert not log.kinds(st.EVENT) and not launches.logs[0].kinds(st.EVENT) + phase["name"] = "stuck" + elif phase["name"] == "stuck" and log.kinds(st.EVENT): + phase["name"] = "relaunching" + node = NODES[1][1].name + cluster.exit(node, max(cluster.runs[node]), 1) # incarnation 0's rank 1 fails + elif phase["name"] == "relaunching" and log.kinds(st.CLEARED_EVENT) and 1 in clients and 1 not in catching: + phase["name"] = "stuck again" + elif phase["name"] == "stuck again" and len(log.kinds(st.EVENT)) == 2: + phase["name"] = "pushing" + return phase["name"] == "pushing" and len(log.kinds(st.CLEARED_EVENT)) == 2 \ + and all(c.finalizing.is_set() for c in clients.values()) + + try: + worker.step() + follow_the_nodes() + assert sorted(clients) == [0, 1] + for fid in range(P): + clients[0].send_init(fid, _f32(_initial(fid))) + _wait(poll, "the fleet never finalized (stuck, relaunched)", timeout=300) + for client in clients.values(): + manifest, _fragments = client.wait_for_final_fragments(timeout=30) + client.acknowledge_finalization(manifest) + assert process.wait(timeout=15) == 0 + for k in list(clients): + cluster.finish(k) + _wait(lambda: all(launches.ended(m["prefix"]) is not None for m in dz.trainers(store.read()).values()), + "an island launch did not end", timeout=60) + finally: + for client in clients.values(): + client.close() + for up_ in uploaders: + up_.stop(5.0) + if process.poll() is None: + process.terminate() + process.wait(timeout=10) + assert not launches.errors, launches.errors + + # -- the watch read the run store's copy, uploaded chunk by chunk + assert all(isinstance(w.source, st.StoreTape) and w.source.requests > 0 for w in watches.values()) + current = [key for key in objects.list(st.SYNCER_TAPES) if "oldhost-" not in key] + assert len(current) >= 2 and len({key.rsplit("/", 2)[1] for key in current}) == 1 + + # -- island 1: reported, relaunched (cleared), reported again N cycles after its new join, cleared + first, second = launches.logs[1].kinds(st.EVENT) + for event in (first, second): + assert event[2]["action"] == st.WAIT and event[2]["missed_cycles"] == CYCLES and event[2]["fragments"] == P + assert first[2]["last_merged_step"] is not None # its own stretch, not the history's 40 merges + assert first[2]["newest_step"] - first[2]["last_merged_step"] >= CYCLES * P + relaunched, back = launches.logs[1].kinds(st.CLEARED_EVENT) + assert relaunched[2]["reason"] == "relaunched" and back[2]["reason"] == "a push of it is merged again" + steps = _outer_steps(tape.read_text()) + joins = [r for r in _records(tape) if r.get("kind") == "pool_join" and int(r["island_id"]) == 1 + and r.get("catch_up") and r["base_version"] <= second[2]["newest_step"]] + rejoin = max(r["base_version"] for r in joins) # the relaunched incarnation's join + assert rejoin >= first[2]["newest_step"] # after the first report (the relaunch may beat the next merge) + assert second[2]["newest_step"] - rejoin >= CYCLES * P # counted from that join, not before + assert states.read(1)["straggler"] is None + ctl = launches.controllers[1] + assert ctl.learners["r-i1-trainer"]["relaunches"] == 1 and launches.started("r-i1") == 1 + + # -- island 0 untouched; the merges continuous, no push merged twice; nobody else reported + assert launches.started("r-i0") == 1 + assert [sum(1 for c in cluster.calls if c[:2] == ("start", n.name)) for n in NODES[0]] == [1, 1] + assert not launches.logs[0].kinds(st.EVENT) and not launches.logs[0].kinds(st.UNAVAILABLE_EVENT) + assert [r["step"] for r in steps] == list(range(1, total_steps * P + 1)) + merged = [(int(e[0]), pushed) for r in steps for e, pushed in zip(r["raw_weights"], r["pushed_for"])] + assert len(merged) == len(set(merged)), Counter(merged).most_common(3) + + # -- the ledger: island 1's two incarnations, each created once + rows = [r for r in ResourceLedger(tmp_path / "ledger.jsonl").records() if r["kind"] == SSH_TRAINER] + created = Counter(r["id"] for r in rows if r["op"] == "create") + assert sorted(created) == ["r-i0/r-i0-trainer-i0", "r-i1/r-i1-trainer-i0", "r-i1/r-i1-trainer-i1"] + assert set(created.values()) == {1} + assert all(n == 1 for n in Counter(r["id"] for r in rows if r["op"] == "release").values()) + + def worker_members(store, case): members = list(dz.trainers(store.read()).values()) if case == "remove": diff --git a/yeto/launch/island_straggler.py b/yeto/launch/island_straggler.py index 495066e74..7a6b263f8 100644 --- a/yeto/launch/island_straggler.py +++ b/yeto/launch/island_straggler.py @@ -19,8 +19,10 @@ incarnation it finds at its first read: a relaunched or moved island's new launch never counts the merges its earlier launches missed. * **When counting starts.** At the island's first ``pool_join`` after the watch started, or - after the controller relaunched it (a new incarnation token), or at a ``pool_join`` of a - new generation or syncer term (a relaunch the controller did not see). A later re-JOIN of + after it left running (recovering, draining; a relaunch is a new incarnation token), or at + a ``pool_join`` of a new generation or syncer term (a relaunch the controller did not + see). What the syncer records after the island left running is its next incarnation's: a + join written before the controller holds the new incarnation running is counted. A later re-JOIN of the same generation (a lease that expired) does not restart the count. A merged push of the island resets it. An island adopted by a restarted launcher has joined before the watch started: it is counted from its first merged push after that. @@ -114,8 +116,10 @@ class _Island: flagged: bool = False token: Any = None generation: tuple | None = None # (syncer_epoch, generation) of the join counted from - since: float | None = None # wall time of its last relaunch: older records are another incarnation's + since: float | None = None # wall time it last left running: older records are another incarnation's rejoined: str | None = None # a flagged island joined again as a new generation: why its stretch ends + away: bool = False # not running now (recovering, draining, ended): its count restarts at its next join + was_joined: bool = False # whether it was in the pool when it left running def _time(record: Mapping[str, Any]) -> float | None: @@ -194,15 +198,26 @@ def check(self, running: Mapping[int, Any]) -> list[Straggler]: the end of the stretch of a flagged island that is not running any more.""" out: list[Straggler] = [] threshold = self.cycles * self.per_cycle + for k, state in self.islands.items(): + if k in running or state.token is None or state.away: + continue + # it left running: what the syncer records from now on is its next incarnation's (a + # join of it may come before its controller holds it running again) + if state.flagged: + out.append(self._signal(k, state, cleared=True, reason="not running")) + was_joined = state.joined + self._restart(state) + state.away, state.was_joined = True, was_joined for k, token in running.items(): state = self._island(int(k)) - if state.token != token: - if state.token is not None: # relaunched: its count starts at its next join - if state.flagged: - out.append(self._signal(int(k), state, cleared=True, reason="relaunched")) - state.joined, state.misses, state.absent, state.flagged = False, 0, False, False - state.generation, state.rejoined, state.since = None, None, self.clock() - state.token = token + if state.away and state.token == token: # the same incarnation back: counted from now + state.joined = state.joined or state.was_joined + elif state.token != token and state.token is not None and not state.away: + # relaunched between two checks: its count starts at its next join + if state.flagged: + out.append(self._signal(int(k), state, cleared=True, reason="relaunched")) + self._restart(state) + state.token, state.away = token, False if state.rejoined is not None: if state.flagged: out.append(self._signal(int(k), state, cleared=True, reason=state.rejoined)) @@ -218,11 +233,15 @@ def check(self, running: Mapping[int, Any]) -> list[Straggler]: state.flagged = False out.append(self._signal(int(k), state, cleared=True, reason="a push of it is merged again")) for k, state in self.islands.items(): - if k not in running and state.flagged: + if k not in running and state.flagged: # never held running here state.flagged = False out.append(self._signal(k, state, cleared=True, reason="not running")) return out + def _restart(self, state: _Island) -> None: + state.joined, state.misses, state.absent, state.flagged = False, 0, False, False + state.generation, state.rejoined, state.since = None, None, self.clock() + def _signal(self, k: int, state: _Island, *, cleared: bool, reason: str) -> Straggler: return Straggler(island=k, cleared=cleared, missed_cycles=state.misses // self.per_cycle, merges=state.misses, fragments=self.per_cycle, cycles=self.cycles, @@ -275,7 +294,7 @@ def read(self) -> list[dict[str, Any]]: def _incarnation_order(incarnation: str) -> tuple: - from yeto.dashboard.store_tapes import launch_started # noqa: PLC0415 + from yeto.dashboard.store_tapes import launch_started started = launch_started(incarnation) return (0 if started is None else 1, started or 0.0, incarnation) From 967914290ce71340b40e1dbfe5a021bc07b18985 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 21:08:35 +0800 Subject: [PATCH 04/13] island straggler: an island back as the same incarnation is counted from its return Co-Authored-By: Claude Opus 5.5 --- tests/test_island_straggler.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/test_island_straggler.py b/tests/test_island_straggler.py index 8fc36d7e6..04112cc2c 100644 --- a/tests/test_island_straggler.py +++ b/tests/test_island_straggler.py @@ -213,6 +213,14 @@ def test_an_island_back_running_as_the_same_incarnation_keeps_its_place_in_the_p tracker.check(RUN2) # the same token back tracker.feed(_step(1, [0], fragments=1)) assert [s.island for s in tracker.check(RUN2)] == [1] + again = st.StragglerTracker(cycles=2) # counted from its return: what it missed before is not + again.feed(_join(1)) + again.feed(_step(1, [0], fragments=1)) + again.check(RUN2) + again.check({0: (0, 1)}) + again.check(RUN2) + again.feed(_step(2, [0], fragments=1)) + assert again.check(RUN2) == [] fresh = st.StragglerTracker(cycles=1) # never joined before it left: still not counted fresh.check(RUN2) fresh.check({0: (0, 1)}) From d61fd9fd1bab2fca21c19bac0ced7eb33edc5b3d Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 23:14:14 +0800 Subject: [PATCH 05/13] island straggler: only the controller restarts a count; adopted islands, restarts, tails, clocks - a reconnect (new connection generation) or a syncer that took over (new term) keeps the count and the mark; only leaving running or a relaunch restarts them - an island a merge lists absent is in the pool (an adopted island is counted) - a launcher that starts on a record holding a report closes it (controller restarted) and judges the island again - the store tail is established once every request of the first read worked; the newest incarnation is the furthest syncer (term, step), not a name - the watch-start filter allows 10 minutes of clock skew; no other decision reads a clock - silence is said only after the first record about this launch's islands, and taken back (island_straggler_available) when records come again - dashboard: "straggler" in warn colour in place of "ok", on one line; the cleared event shows its reason only; no mark in the Fragments rows - docs: what restarts a count, how late a report can be Co-Authored-By: Claude Opus 5.5 --- docs/OWN_CLUSTERS.md | 44 +++-- tests/test_dashboard_island_straggler.py | 7 +- tests/test_island_straggler.py | 218 ++++++++++++++++----- tests/test_own_clusters_islands_doc.py | 5 +- tests/test_ssh_island_fleet_e2e.py | 4 +- yeto/dashboard/reducer.py | 3 +- yeto/dashboard/static/app.js | 9 +- yeto/dashboard/static/sft.js | 7 +- yeto/dashboard/static/topology_diloco.js | 2 +- yeto/launch/fleet.py | 36 +++- yeto/launch/island_straggler.py | 234 +++++++++++++---------- 11 files changed, 390 insertions(+), 179 deletions(-) diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 607bc0e0f..c335241d9 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -508,16 +508,25 @@ island is reported after 12 merges without it. A push the syncer refused does no merged. Counting starts when the island joins the syncer: - A launch counts only what the syncer records after the launch started. A relaunched or - moved island's new launch never counts the merges an earlier launch of it missed. -- When the island stops running (its controller relaunches it, or it is stopped), its count - starts again at its next join. The time an island takes to start is not counted. -- An island adopted by a restarted launcher joined before the launcher started. It is - counted from its first merged push. + moved island's new launch never counts the merges an earlier launch of it missed. Records + stamped up to 10 minutes before the launch started still count, in case the syncer host's + clock runs behind. +- An island also counts as joined once a merge lists it `absent`: the syncer expects it. An + island that a restarted launcher adopted joined before that launcher started, and is + counted this way. +- Only the island's controller restarts the count. When the island stops running (its + controller relaunches it, or it is stopped), its count starts again once it runs again: at + its next join after a relaunch, so the time it takes to start is not counted. +- A reconnect of the same trainer, or a syncer that takes over, writes a new join to the + syncer's tape. That join keeps the count and the report: an island whose link keeps + dropping and that never delivers is still reported. The report is written once per stretch. `island_straggler_cleared` closes the stretch, and its `reason` says why: a push of the island is merged again, it was `relaunched`, it was stopped -or removed (island STOP), or it is no longer running. The record's `straggler` is set back to -`null` at the same time. +or removed (island STOP), it is no longer running, or `controller restarted`. The last one is +written by a launcher that starts, or adopts the island, while its record still holds a +report from an earlier launcher; the new launcher then judges the island again. The +record's `straggler` is set back to `null` at the same time. The dashboard shows both events in its event stream. While the island is reported, its trainer card carries a `straggler` badge and its row in "Islands now" says `straggler`. @@ -542,11 +551,20 @@ The controller reads the syncer's tape in one of two places: - otherwise, in a fleet launched island by island (`fleet.launch: per_island`), from its copy in the run store, `tapes/syncer//.jsonl`. The syncer launch uploads it every 30 s (`YETO_RL_TAPE_UPLOAD_S`) when `--rl-checkpoint-store` is an - `s3://` store. Each island launch reads it every 30 s, starting at the end of the newest - syncer incarnation it finds. + `s3://` store. Each island launch reads it every 30 s. Its first read starts at the end of + the syncer incarnation that got furthest (the newest syncer term, then the newest step). -The report comes at most one upload interval and one read interval after the merges it -counts. +How late the report can be, with the store copy: + +- Normally one upload interval and one read interval after the merges it counts (about + 1 minute). +- One read takes at most 16 chunks, about 8 minutes of tape. A backlog left by a store + outage is read in about one fifteenth of the outage's length: 1 hour of outage is caught + up in about 4 minutes. +- A restarted syncer writes to a new incarnation. The launch finds it at its next full + listing, which comes every 10 reads (about 5 minutes), and reads it from its start. +- If the first read fails, every later read tries it again. Until one works nothing is + read, and the syncer's earlier records are never read. When the report cannot work, the launch prints `island straggler watch off` and writes `island_straggler_unavailable` once, with the `reason`, in `fleet.jsonl`. Nothing is @@ -561,7 +579,9 @@ reported then, and training is not affected. This happens: Run the syncer on the controller's host (`--controller head`) or launch the fleet island by island to get the report. - when the launch reads no syncer record for 10 reads in a row (the store copy is missing - or stale). + or stale). This is counted only after the first record about the launch's islands, so a + fleet whose trainers are still starting is not reported. Once records are read again, + the launch writes `island_straggler_available`. ### Removing an island diff --git a/tests/test_dashboard_island_straggler.py b/tests/test_dashboard_island_straggler.py index 68c5fdc27..d73f98556 100644 --- a/tests/test_dashboard_island_straggler.py +++ b/tests/test_dashboard_island_straggler.py @@ -78,7 +78,9 @@ def test_an_unavailable_watch_is_no_mark(): def test_the_trainer_card_draws_a_straggler_badge_until_cleared(tmp_path): flagged = _smoke(tmp_path / "a", _reducer(_flagged())) assert "straggler" in flagged["texts"] # the topology's trainer card - assert flagged["nodes"].count("straggler") == 1 # Islands now: trainer 1's row only + # Islands now: trainer 1's row says straggler in warn colour in place of "ok", once + assert flagged["nodes"].count('straggler') == 1 + assert "ok · straggler" not in flagged["nodes"] and "straggler" not in flagged["matrix"] # not in Fragments for r in (_reducer(), _reducer(_flagged(), _cleared())): out = _smoke(tmp_path / str(len(r.fleet_records)), r) assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] @@ -106,4 +108,7 @@ def test_the_event_stream_shows_the_straggler_events(tmp_path): events = _smoke(tmp_path, _reducer(_flagged(at=end + 10), _cleared(at=end + 20)))["events"] assert "island_straggler" in events and "missed_cycles=3" in events and "action=wait" in events assert "island_straggler_cleared" in events and "reason=a push of it is merged again" in events + cleared = events.split("island_straggler_cleared", 1)[1].split("", 1)[0] + assert "missed_cycles" not in cleared # its reason only assert 'title="lag"' in events and 'title="back"' in events + assert "island_straggler trainer 1 action=wait missed_cycles=3" in events diff --git a/tests/test_island_straggler.py b/tests/test_island_straggler.py index 04112cc2c..a4f33c6b6 100644 --- a/tests/test_island_straggler.py +++ b/tests/test_island_straggler.py @@ -140,68 +140,99 @@ def _at(record, t): def test_records_from_before_the_watch_started_are_not_counted(): """A relaunched or moved island's new launch reads the syncer's history: the merges its earlier launch missed, and its earlier join, are stamped before the watch started.""" - tracker = st.StragglerTracker(cycles=1, since=1000.0) - tracker.feed(_at(_join(1), 900.0)) + tracker = st.StragglerTracker(cycles=1, since=10_000.0) + tracker.feed(_at(_join(1), 9_000.0)) for step in range(1, 9): - tracker.feed(_at(_step(step, [0], fragments=1), 900.0 + step)) + tracker.feed(_at(_step(step, [0], fragments=1, absent=[1]), 9_000.0 + step)) assert tracker.check(RUN2) == [] # nothing of it counts: island 1 has not joined since - tracker.feed(_at(_join(1), 1001.0)) + tracker.feed(_at(_join(1), 10_001.0)) assert tracker.check(RUN2) == [] - tracker.feed(_at(_step(9, [0], fragments=1), 1002.0)) + tracker.feed(_at(_step(9, [0], fragments=1), 10_002.0)) (signal,) = tracker.check(RUN2) assert signal.merges == 1 and signal.last_merged_step is None -def test_a_join_of_a_new_generation_or_syncer_term_starts_the_count_again(): +def test_a_syncer_clock_300_s_behind_is_still_counted(): + """The syncer host's clock may run behind the launcher's: its records of now are stamped up + to CLOCK_SKEW_S before the watch's start and still count.""" + tracker = st.StragglerTracker(cycles=1, since=10_000.0) + tracker.feed(_at(_join(1), 9_700.0)) + tracker.feed(_at(_step(1, [0], fragments=1), 9_701.0)) + assert [s.island for s in tracker.check(RUN2)] == [1] + assert st.CLOCK_SKEW_S >= 300 + + +def test_a_link_that_reconnects_keeps_the_count_and_the_mark(): + """Each reconnect of the same process is a new connection generation, and the syncer + writes a new pool_join for it: none restarts the count or clears the mark. An island that + reconnects every 2 merges and never delivers is reported once, and stays reported.""" + tracker = st.StragglerTracker(cycles=3) + signals = [] + for step in range(1, 41): + if step % 2 == 1: + tracker.feed(dict(_join(1), generation=step)) + signals += tracker.check(RUN2) + tracker.feed(_step(step, [0], fragments=1, absent=[1])) + signals += tracker.check(RUN2) + assert [(s.island, s.cleared, s.merges) for s in signals] == [(1, False, 3)] + + +def test_a_new_syncer_term_keeps_the_count_and_the_mark(): tracker = st.StragglerTracker(cycles=2) tracker.feed(_join(1)) - for step in range(1, 3): + for step in (1, 2): tracker.feed(_step(step, [0], fragments=1)) (signal,) = tracker.check(RUN2) assert not signal.cleared - tracker.feed(dict(_join(1), generation=1)) # a relaunch the controller did not see + tracker.feed(dict(_join(1), syncer_epoch=4, generation=7)) # a syncer that took over + assert tracker.check(RUN2) == [] # still reported: nothing written + tracker.feed(_step(3, [1], fragments=1)) (cleared,) = tracker.check(RUN2) - assert cleared.cleared and cleared.reason.startswith("rejoined (generation 1") - tracker.feed(_step(3, [0], fragments=1)) - assert tracker.check(RUN2) == [] # counted from 0 at that join: 1 of 2 - tracker.feed(dict(_join(1), generation=1, syncer_epoch=4)) # a restarted syncer's term - tracker.feed(_step(4, [0], fragments=1)) - assert tracker.check(RUN2) == [] - tracker.feed(_step(5, [0], fragments=1)) - assert [s.merges for s in tracker.check(RUN2)] == [2] + assert cleared.cleared and cleared.reason == "a push of it is merged again" + + +def test_an_island_the_syncer_lists_absent_is_counted_without_a_join(): + """A restarted launcher adopts a stuck island: its join came before this watch. The syncer + expects it (absent in its merges), so it is counted from the first such merge.""" + tracker = st.StragglerTracker(cycles=2) + for step in (1, 2): + tracker.feed(_step(step, [0], fragments=1, absent=[] if step == 1 else [1])) + assert tracker.check(RUN2) == [] # one merge listed it absent: 1 of 2 + tracker.feed(_step(3, [0], fragments=1, absent=[1])) + (signal,) = tracker.check(RUN2) + assert signal.island == 1 and signal.merges == 2 and signal.absent -def test_a_relaunch_ignores_the_earlier_incarnation_s_records_read_late(): - now = [5000.0] - tracker = st.StragglerTracker(cycles=1, clock=lambda: now[0]) - tracker.feed(_at(_join(1), 4000.0)) +def test_records_of_the_earlier_incarnation_read_late_do_not_count(): + """Relaunched (it left running, then runs as a new token): merges of its earlier + incarnation read late, even ones that list it absent, start nothing; it is counted + from its next join.""" + tracker = st.StragglerTracker(cycles=1) + tracker.feed(_join(1)) tracker.check(RUN2) - now[0] = 6000.0 - assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] # relaunched at 6000 - tracker.feed(_at(_join(1), 5500.0)) # its earlier join, in a chunk read late - tracker.feed(_at(_step(1, [0], fragments=1), 5600.0)) - assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] - tracker.feed(_at(_join(1), 6100.0)) - tracker.feed(_at(_step(2, [0], fragments=1), 6200.0)) + assert tracker.check({0: (0, 1)}) == [] # recovering + tracker.feed(_step(1, [0], fragments=1, absent=[1])) # read late + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] # running as its next incarnation + tracker.feed(_step(2, [0], fragments=1)) + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] # not joined yet: starting + tracker.feed(_join(1)) + tracker.feed(_step(3, [0], fragments=1)) assert [s.merges for s in tracker.check({0: (0, 1), 1: (1, 2)})] == [1] def test_a_join_recorded_before_the_controller_holds_the_new_incarnation_running_counts(): - """Recovering at 6000 (the island left running), its new incarnation joins at 6100, and only - then does the controller hold it running (a new token): the join is the new incarnation's, - so the island is counted from it, not left uncounted until a push of it merges.""" - now = [5000.0] - tracker = st.StragglerTracker(cycles=1, clock=lambda: now[0]) - tracker.feed(_at(_join(1), 4000.0)) + """Recovering (the island left running), its new incarnation joins, and only then does + the controller hold it running (a new token): the join is the new incarnation's, so the + island is counted from its return, not left uncounted until a push of it merges.""" + tracker = st.StragglerTracker(cycles=1) + tracker.feed(_join(1)) tracker.check(RUN2) - now[0] = 6000.0 assert tracker.check({0: (0, 1)}) == [] # island 1 recovering - tracker.feed(_at(_step(1, [0], fragments=1), 5900.0)) # its earlier incarnation's stretch - tracker.feed(_at(dict(_join(1), catch_up=True), 6100.0)) + tracker.feed(dict(_join(1), catch_up=True)) assert tracker.check({0: (0, 1)}) == [] # not held running: never reported - tracker.feed(_at(_step(2, [0], fragments=1), 6200.0)) - now[0] = 6300.0 - (signal,) = tracker.check({0: (0, 1), 1: (1, 2)}) # running again: counted from its join + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] # running again + tracker.feed(_step(1, [0], fragments=1)) + (signal,) = tracker.check({0: (0, 1), 1: (1, 2)}) assert not signal.cleared and signal.island == 1 and signal.merges == 1 @@ -326,7 +357,7 @@ def list(self, prefix, *, start_after=""): def read(self, key): self.reads += 1 - if self.reads == 3 and not self.failed: + if self.reads == 4 and not self.failed: # the tail's read is the 1st self.failed = True raise OSError("read timed out") return self.inner.read(key) @@ -343,6 +374,53 @@ def read(self, key): assert [r["step"] for r in second] == [13, 14, 15] and flaky.error is None # none twice, none skipped +def test_a_failed_first_read_tries_the_tail_again_and_never_reads_the_history(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + for seq in range(5): + _chunk(objects, inc, seq, _step(seq + 1, [0])) # the history + + class Down: + def __init__(self, inner, fail): + self.inner, self.fail = inner, set(fail) + + def list(self, prefix, *, start_after=""): + if ("root" if prefix == "tapes/syncer/" else "inc") in self.fail: + raise OSError("list failed") + return self.inner.list(prefix, start_after=start_after) + + def read(self, key): + return self.inner.read(key) + + clock = [0.0] + for fail in ({"root"}, {"inc"}): # the incarnations' listing, then the newest one's chunks + clock[0] = 0.0 + down = Down(objects, fail) + source = st.StoreTape(down, interval_s=30, clock=lambda: clock[0]) + assert source.read() == [] and "list failed" in source.error and not source.tailed + down.fail = set() + clock[0] = 31.0 + assert source.read() == [] and source.tailed # the tail now: still no history + _chunk(objects, inc, 5 + len(fail) + (fail == {"inc"}), _step(99, [0])) + clock[0] = 62.0 + assert [r["step"] for r in source.read()] == [99] + + +def test_the_newest_incarnation_is_the_furthest_syncer_not_the_newest_name(tmp_path): + """No clock: the syncer that took over (a newer term) is read even when its folder's name + sorts first and its steps are behind.""" + objects = DirectoryObjectStore(tmp_path / "store") + _chunk(objects, "z-20991231T000000Z", 0, dict(_step(50, [0]), syncer_epoch=1)) + _chunk(objects, "a-20000101T000000Z", 0, dict(_step(40, [0]), syncer_epoch=2)) + clock = [0.0] + source = st.StoreTape(objects, interval_s=30, clock=lambda: clock[0]) + assert source.read() == [] and source.queue == ["a-20000101T000000Z"] + _chunk(objects, "a-20000101T000000Z", 1, dict(_step(41, [0]), syncer_epoch=2)) + _chunk(objects, "z-20991231T000000Z", 1, dict(_step(51, [0]), syncer_epoch=1)) # the old one, late + clock[0] = 31.0 + assert [r["step"] for r in source.read()] == [41] + + def test_a_store_poll_starts_no_request_past_its_budget(tmp_path): objects = DirectoryObjectStore(tmp_path / "store") inc = "hosta-20261126T130000Z" @@ -382,10 +460,12 @@ def test_the_launcher_watches_an_island_pool_only(tmp_path): assert st.watch_for(types.SimpleNamespace(training_mode="rl"), objects=object(), log=lines.append) is None off = st.watch_for(types.SimpleNamespace(**vars(pool), rl_island_straggler_cycles=0), objects=object(), log=lines.append) - assert isinstance(off, st.UnavailableWatch) and off.notices() == ["turned off (--rl-island-straggler-cycles 0)"] + assert isinstance(off, st.UnavailableWatch) + assert off.notices() == [(st.UNAVAILABLE_EVENT, "turned off (--rl-island-straggler-cycles 0)")] assert off.notices() == [] and off.poll(RUN2) == [] none = st.watch_for(pool, log=lines.append, no_source="the syncer runs on its own VM") - assert isinstance(none, st.UnavailableWatch) and none.notices() == ["the syncer runs on its own VM"] + assert isinstance(none, st.UnavailableWatch) + assert none.notices() == [(st.UNAVAILABLE_EVENT, "the syncer runs on its own VM")] assert "watch off: the syncer runs on its own VM" in lines[-1] watch = st.watch_for(pool, local_tape=tmp_path / "tape.jsonl", objects=object(), log=lines.append) assert isinstance(watch.source, st.FileTape) and watch.tracker.cycles == 3 and watch.tracker.since > 0 @@ -503,20 +583,32 @@ def test_without_a_watch_the_controller_reads_nothing(tmp_path): assert log.events == [] -def test_a_watch_that_reads_no_syncer_record_says_so_once(): +def test_a_slow_start_is_never_said_unavailable(): + """Nothing about this launch's islands read yet (its trainers still load): no notice.""" lines, tape = [], ScriptedTape() watch = st.StragglerWatch(tape, cycles=1, log=lines.append) - for _ in range(st.QUIET_POLLS + 5): + tape.pending.append(_join(5)) # another launch's island: not this one's first record + for _ in range(st.QUIET_POLLS * 3): watch.poll(RUN2) - assert len(lines) == 1 and "no syncer record read from test tape in 10 reads" in lines[0] - (notice,) = watch.notices() - assert "no syncer record" in notice and watch.notices() == [] - lines.clear() - read = st.StragglerWatch(tape, cycles=1, log=lines.append) + assert lines == [] and watch.notices() == [] + + +def test_a_tape_silent_after_its_first_record_is_said_once_then_taken_back(): + lines, tape = [], ScriptedTape() + watch = st.StragglerWatch(tape, cycles=1, log=lines.append) tape.pending.append(_join(0)) - for _ in range(st.QUIET_POLLS + 5): - read.poll(RUN2) - assert lines == [] # it read the syncer once: a quiet stretch later is the syncer's, not the source's + watch.poll(RUN2) + for _ in range(st.QUIET_POLLS * 2): + watch.poll(RUN2) + assert len(lines) == 1 and "no syncer record read from test tape in 10 reads" in lines[0] + ((kind, why),) = watch.notices() + assert kind == st.UNAVAILABLE_EVENT and "no syncer record" in why and watch.notices() == [] + tape.pending.append(_step(1, [0, 1])) + watch.poll(RUN2) + assert watch.notices() == [(st.AVAILABLE_EVENT, "syncer records read again from test tape")] + for _ in range(st.QUIET_POLLS - 1): + watch.poll(RUN2) + assert watch.notices() == [] # one read short of a new silent stretch def test_the_launcher_reads_the_store_copy_for_an_island_launch_only(tmp_path, monkeypatch): @@ -566,3 +658,25 @@ def test_the_watch_s_notices_are_written_once_as_unavailable(tmp_path): ctl._poll_stragglers() why = {"reason": "the run store is not an object store"} assert [e[1:] for e in log.kinds(st.UNAVAILABLE_EVENT)] == [("r-l0", why), ("r-l1", why)] # once per island + + +def test_a_watch_read_again_writes_available(tmp_path): + ctl, _ops, _store, _tape, log = _controller(tmp_path) + ctl.straggler._notices.append((st.AVAILABLE_EVENT, "syncer records read again")) + ctl._poll_stragglers() + assert [e[1] for e in log.kinds(st.AVAILABLE_EVENT)] == ["r-l0", "r-l1"] + + +def test_a_mark_an_earlier_launcher_left_is_cleared_once_and_judged_again(tmp_path): + ctl, _ops, store, tape, log = _controller(tmp_path) + store.write(1, "running", straggler={"action": "wait", "missed_cycles": 3, "merges": 3, "fragments": 1, + "newest_step": 9, "last_merged_step": 6, "at": 1.0}) + ctl._poll_stragglers() + (cleared,) = log.kinds(st.CLEARED_EVENT) + assert cleared[1] == "r-l1" and cleared[2]["reason"] == "controller restarted" + assert cleared[2]["missed_cycles"] == 3 and store.read(1)["straggler"] is None + assert (store.read(0) or {}).get("straggler") is None and not log.kinds(st.EVENT) + tape.pending += [_join(1), _step(1, [0], fragments=1)] + ctl._poll_stragglers() + assert [e[1] for e in log.kinds(st.EVENT)] == ["r-l1"] # judged again by this watch + assert len(log.kinds(st.CLEARED_EVENT)) == 1 diff --git a/tests/test_own_clusters_islands_doc.py b/tests/test_own_clusters_islands_doc.py index 794d31cc4..4821886e7 100644 --- a/tests/test_own_clusters_islands_doc.py +++ b/tests/test_own_clusters_islands_doc.py @@ -36,9 +36,12 @@ def commands() -> list[list[str]]: def test_the_section_names_the_code_s_flags_and_events(): text = section() assert "--rl-island-straggler-cycles" in text and f"`{st.DEFAULT_CYCLES}` is the default" in text - for name in (st.EVENT, st.CLEARED_EVENT, st.UNAVAILABLE_EVENT, st.WAIT, st.SYNCER_TAPES.rstrip("/")): + for name in (st.EVENT, st.CLEARED_EVENT, st.UNAVAILABLE_EVENT, st.AVAILABLE_EVENT, st.WAIT, + st.SYNCER_TAPES.rstrip("/"), "controller restarted"): assert name in text assert f"{st.QUIET_POLLS} reads in a row" in text and f"every {st.STORE_POLL_S:g} s" in text + assert f"at most {st.STORE_GETS_PER_POLL} chunks" in text and f"every {st.STORE_DISCOVER_POLLS} reads" in text + assert f"up to {st.CLOCK_SKEW_S / 60:g} minutes before" in text for field in st.Straggler.__dataclass_fields__: if field not in ("island", "cleared", "cycles", "reason"): assert f"`{field}`" in text, field diff --git a/tests/test_ssh_island_fleet_e2e.py b/tests/test_ssh_island_fleet_e2e.py index 166c18430..f00ba8d8d 100644 --- a/tests/test_ssh_island_fleet_e2e.py +++ b/tests/test_ssh_island_fleet_e2e.py @@ -472,7 +472,9 @@ def test_a_stuck_island_relaunched_mid_run_is_watched_over_the_run_store(syncer_ def watch(argv, island_states): w = launcher._island_straggler_watch(_launch_args(argv), island_states, None) - w.source.interval_s = 0.2 # a store read every 0.2 s, not every 30 s + # a store read every 0.5 s, not every 30 s: QUIET_POLLS reads (5 s) stay longer than the + # 2 s quorum deadline between merges, as 10 x 30 s does against a real run's merges + w.source.interval_s = 0.5 watches[int(argv[argv.index("--rl-fleet-learner-id") + 1])] = w return w diff --git a/yeto/dashboard/reducer.py b/yeto/dashboard/reducer.py index e5aa6f32c..ebe55e9c9 100644 --- a/yeto/dashboard/reducer.py +++ b/yeto/dashboard/reducer.py @@ -43,7 +43,8 @@ # a trainer island the syncer has merged no push of for N merge cycles, and its end (or why # that cannot be watched): fleet.jsonl events that are not lifecycle states -STRAGGLER_EVENTS = frozenset({"island_straggler", "island_straggler_cleared", "island_straggler_unavailable"}) +STRAGGLER_EVENTS = frozenset({"island_straggler", "island_straggler_cleared", "island_straggler_unavailable", + "island_straggler_available"}) FLEET_EVENTS = frozenset({"island_launch", "island_ready", "island_lost", "island_stop", "island_done", "cost_tick"}) | STRAGGLER_EVENTS POLICY_SWEEP_LEDGER_EVENT = "policy_sweep_ledger" diff --git a/yeto/dashboard/static/app.js b/yeto/dashboard/static/app.js index 730cb7534..82a7aae1a 100644 --- a/yeto/dashboard/static/app.js +++ b/yeto/dashboard/static/app.js @@ -446,16 +446,17 @@ function cost(){ var EV_KEEP={rl_engine_selected:1,rl_driver_start:1,rl_driver_phase:1,rl_publication:1,rl_round_trained:1,rl_reconfiguration:1,rl_learner_finalized:1, island_ready:1,island_lost:1,island_stop:1,island_done:1,island_leave:1,operator_stop:1,dashboard_source_lost:1,rl_elastic_recommendation:1, rl_policy_released:1,rl_sampler_start:1,rl_sampler_join:1,rl_sampler_policy_loaded:1,rl_sampler_backlog_full:1,rl_sampler_admitted:1,rl_sampler_stopped:1, - island_straggler:1,island_straggler_cleared:1,island_straggler_unavailable:1}; + island_straggler:1,island_straggler_cleared:1,island_straggler_unavailable:1,island_straggler_available:1}; var POOL_BAD=/evicted|node_lost|crash_loop|failed|breaker|timeout|overdue|orphan|refused|manual_release/; function keepEv(t){return EV_KEEP[t]||/^nc_elastic_/.test(t)} var EVENTS=[],EV_CURSOR=0; function evLevel(t,rec){if(t==="operator_stop")return ["mu","stop"]; - if(t==="island_straggler")return ["wn","lag"];if(t==="island_straggler_cleared")return ["ok","back"];if(t==="island_straggler_unavailable")return ["mu","info"]; + if(t==="island_straggler")return ["wn","lag"];if(t==="island_straggler_cleared")return ["ok","back"];if(t==="island_straggler_unavailable"||t==="island_straggler_available")return ["mu","info"]; if(/^nc_elastic_/.test(t))return POOL_BAD.test(t)?["bd","pool"]:["wn","pool"];if(t==="island_leave")return ["wn","left"];if(t==="island_lost"||(t==="rl_reconfiguration"&&rec.result==="RECOVERY_REQUIRED"))return ["bd","failure"]; if(t==="rl_publication"||t==="rl_round_trained")return ["ok","done"];if(t==="rl_reconfiguration"||t==="dashboard_source_lost")return ["wn","change"];return ["mu","info"]} -var EV_STRAGGLER_KEYS=["action","missed_cycles","newest_step","last_merged_step","reason"]; -function evText(e){var r=e.record||{},keys=/^island_straggler/.test(e.type)?EV_STRAGGLER_KEYS:["phase","rollout_id","policy_version","result","cause","recommendation","marker","reason_name","backlog_groups","buffer_selected","ticket","shard","why","detail"]; +// a straggler report: its count; its end and the watch's notices: their reason only +var EV_STRAGGLER_KEYS={island_straggler:["action","missed_cycles","newest_step","last_merged_step"]}; +function evText(e){var r=e.record||{},keys=/^island_straggler/.test(e.type)?EV_STRAGGLER_KEYS[e.type]||["reason"]:["phase","rollout_id","policy_version","result","cause","recommendation","marker","reason_name","backlog_groups","buffer_selected","ticket","shard","why","detail"]; return keys.filter(function(k){return r[k]!=null}).map(function(k){return k+"="+String(r[k]).slice(0,80)}).join(" ")} /* newest first by event time; the tapes are read one after another, so arrival (seq) order is not time order. One total-order key per event: its time (an event without one takes the time of the last timed event that diff --git a/yeto/dashboard/static/sft.js b/yeto/dashboard/static/sft.js index c7805de16..115f2b05c 100644 --- a/yeto/dashboard/static/sft.js +++ b/yeto/dashboard/static/sft.js @@ -574,9 +574,10 @@ function rlm(V){ 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 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 trainer island the syncer has merged no push of for N merge cycles (its record's mark, else its fleet event) - ((c.island_now&&"straggler" in c.island_now?c.island_now.straggler:c.straggler)&&liv?" · straggler":""))+'
'; + // a trainer island the syncer has merged no push of for N merge cycles (its record's mark, else its fleet + // event): "straggler" in warn colour in place of its live status + var sg=liv&&!!(c.island_now&&"straggler" in c.island_now?c.island_now.straggler:c.straggler); + var row='
'+(sg?'':rlDot(c.status))+''+esc(c.label)+'
'+esc([c.name,c.gpu?c.gpu+" × "+c.cards:null,c.backend_label].filter(Boolean).join(" · ")||"n/a")+' · '+(sg?'straggler':esc(c.status))+esc((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)":""))+'
'; 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(); diff --git a/yeto/dashboard/static/topology_diloco.js b/yeto/dashboard/static/topology_diloco.js index d77371c32..9a48f5c34 100644 --- a/yeto/dashboard/static/topology_diloco.js +++ b/yeto/dashboard/static/topology_diloco.js @@ -479,7 +479,7 @@ function matrix(tn){ h+=""; var finalOnSyncer=false; if(sft())h+=learnerRows(tn);else D.trainers.forEach(function(tr){var off=!tr.live&&!(tr.status==="done"||tr.finalized); - h+='Trainer '+esc(tr.id)+''+esc((tr.gpu||"")+(fin(tr.step)?" · step "+tr.step:fleet()?" · not trained yet":" · step —")+(tr.island_now?" · "+tr.island_now.state:off?" · "+(tr.status||"lost"):tr.failure?" · failed":"")+(straggler(tr)&&!D.done?" · straggler":""))+""; + h+='Trainer '+esc(tr.id)+''+esc((tr.gpu||"")+(fin(tr.step)?" · step "+tr.step:fleet()?" · not trained yet":" · step —")+(tr.island_now?" · "+tr.island_now.state:off?" · "+(tr.status||"lost"):tr.failure?" · failed":""))+""; for(var f=0;f=2?"lag2":lg===1?"lag1":"",ready=fin(s)&&H&&s>=H; var mk=pushed?'↑':lg&&tr.live?'↓'+lg+"":""; diff --git a/yeto/launch/fleet.py b/yeto/launch/fleet.py index 8dc8f79c9..88adeb7c3 100644 --- a/yeto/launch/fleet.py +++ b/yeto/launch/fleet.py @@ -1065,8 +1065,10 @@ def _poll_stragglers(self) -> None: is written once (``island_straggler`` / ``island_straggler_cleared`` in fleet.jsonl, ``straggler`` in the island's record) and its policy is asked what to do; a flagged island that stops running (recovering, draining, ended) is cleared, naming why. The - watch's notices (nothing can be watched here, or its tape stays silent) are written - once each as ``island_straggler_unavailable``. Never raises: a watch that fails is a + watch's notices (nothing can be watched here, its tape went silent, it is read again) + are written once each (``island_straggler_unavailable`` / ``_available``). At its first + poll, a mark an earlier launcher left in an island's record is cleared (``controller + restarted``): this watch judges the island again. Never raises: a watch that fails is a missing view, not the end of supervision.""" if self.straggler is None or self.recorder is None: return @@ -1081,6 +1083,9 @@ def _poll_stragglers(self) -> None: names[ref.island] = rec if rec["state"] == RUNNING and not rec.get("draining"): running[ref.island] = (rec.get("incarnation"), rec.get("job_id")) + if not getattr(self, "_straggler_marks_checked", False): + self._straggler_marks_checked = True + self._clear_left_marks(names) for signal in self.straggler.poll(running): rec = names.get(signal.island) if rec is not None: @@ -1088,13 +1093,36 @@ def _poll_stragglers(self) -> None: # each trainer island of this launch names it (a nameless fleet.jsonl event would be # priced as an island of its own); kept until the launch knows its islands if names: - for why in self.straggler.notices(): + for kind, why in self.straggler.notices(): print(f"[launcher] island straggler watch: {why}", file=sys.stderr) for rec in names.values(): - self._fleet(st.UNAVAILABLE_EVENT, rec["name"], reason=str(why)[:500]) + self._fleet(kind, rec["name"], reason=str(why)[:500]) except Exception as error: # noqa: BLE001 - a watch, never the end of supervision print(f"[launcher] island straggler watch: {type(error).__name__}: {error}"[:400], file=sys.stderr) + def _clear_left_marks(self, names) -> None: + """Close the stretch an earlier launcher of this run left open in a record (it was + restarted, or this one adopted the island): written once, then judged again.""" + from . import island_straggler as st + + store = getattr(self.recorder, "store", None) + if store is None: + return + for island, rec in names.items(): + try: + left = (store.read(island) or {}).get("straggler") + except Exception as error: # noqa: BLE001 - its record does not read: nothing to close + print(f"[launcher] {rec['name']}: island record: {type(error).__name__}: {error}"[:300], + file=sys.stderr) + continue + if not left: + continue + fields = {k: left.get(k) for k in ("missed_cycles", "merges", "fragments", "newest_step", + "last_merged_step") if isinstance(left, dict) and k in left} + print(f"[launcher] {rec['name']}: no longer a straggler (controller restarted)", file=sys.stderr) + self._fleet(st.CLEARED_EVENT, rec["name"], **fields, reason="controller restarted") + self._record(rec, straggler=None) + @staticmethod def _not_running(rec) -> str: """Why a flagged island's stretch ends without a merged push: its controller state.""" diff --git a/yeto/launch/island_straggler.py b/yeto/launch/island_straggler.py index 7a6b263f8..cb4bda816 100644 --- a/yeto/launch/island_straggler.py +++ b/yeto/launch/island_straggler.py @@ -14,24 +14,25 @@ (the distinct ``fragment`` ids merged so far, 1 for a non-fragment pool) an island is a straggler once ``N x P`` merges in a row went by without a push of it in their weights. A push the syncer refused, or one still in flight, is not merged and does not count. -* **Only this launch's history.** The watch reads only records stamped (``time_unix``) at or - after its own start, and the run store's copy from the tail of the newest syncer +* **Only this launch's history.** The watch ignores records stamped (``time_unix``) more than + :data:`CLOCK_SKEW_S` before its own start (the launcher's and the syncer host's clocks may + differ that much), and reads the run store's copy from the tail of the furthest syncer incarnation it finds at its first read: a relaunched or moved island's new launch never - counts the merges its earlier launches missed. -* **When counting starts.** At the island's first ``pool_join`` after the watch started, or - after it left running (recovering, draining; a relaunch is a new incarnation token), or at - a ``pool_join`` of a new generation or syncer term (a relaunch the controller did not - see). What the syncer records after the island left running is its next incarnation's: a - join written before the controller holds the new incarnation running is counted. A later re-JOIN of - the same generation (a lease that expired) does not restart the count. A merged push of - the island resets it. An island adopted by a restarted launcher has joined before the - watch started: it is counted from its first merged push after that. + counts the merges its earlier launches missed. No other decision reads a clock. +* **When counting starts.** At the island's first ``pool_join`` read by this watch, or at the + first merge that lists it ``absent`` (the syncer expects it: an island a restarted launcher + adopted joined before this watch), or at its first merged push. Only its controller resets + the count: when the island leaves running (recovering, draining, stopped) it starts again + once it runs again, from its next join for a new incarnation (a relaunch; a join written + before the controller holds it running counts) or at once for the same one. A ``pool_join`` + of a reconnect (each connection is a new generation) or of a syncer that took over (a new + term) keeps the count and the mark. A merged push of the island resets the count. * **Who is watched.** The islands the controller holds running (not draining, not recovering): it passes their learner ids with a token of the incarnation. * **Signals.** One :class:`Straggler` when an island crosses the threshold, and one - ``cleared`` signal when a push of it is merged again, when it rejoined as a new generation, - when it was relaunched, or when it stopped running (recovering, draining, ended): the - controller writes one event per stretch and closes each one. + ``cleared`` signal when a push of it is merged again, when it was relaunched, or when it + stopped running (recovering, draining, ended): the controller writes one event per stretch + and closes each one. Sources (:func:`tape_source`): the syncer's tape file on this host (a head-mode syncer), or its copy in the run store (``tapes/syncer//.jsonl``, uploaded every 30 s @@ -39,11 +40,13 @@ listings of one incarnation's prefix after its last chunk read and :data:`STORE_GETS_PER_POLL` chunk reads, and starts no new request after :data:`STORE_POLL_BUDGET_S`. Finding the syncer's incarnations costs one listing page per incarnation, at the first read, every -:data:`STORE_DISCOVER_POLLS` reads and while none is known; the first read also lists the -newest incarnation once, for its tail. A source that does not read is skipped for that poll; nothing -here ever stops or slows the fleet. When nothing can be watched (no tape to read, the watch -turned off) or the tape stays silent for :data:`QUIET_POLLS` reads, the controller is given -one notice (``island_straggler_unavailable``). +:data:`STORE_DISCOVER_POLLS` reads and while none is known; the first read also lists each +incarnation once and reads its last chunk, for its tail. A source that does not read is skipped +for that poll; nothing here ever stops or slows the fleet. When nothing can be watched (no tape +to read, the watch turned off), or the tape goes silent for :data:`QUIET_POLLS` reads after its +first record about this launch's islands, the controller is given one notice +(``island_straggler_unavailable``), and one more when records are read again +(``island_straggler_available``). """ from __future__ import annotations @@ -59,6 +62,7 @@ EVENT = "island_straggler" CLEARED_EVENT = "island_straggler_cleared" UNAVAILABLE_EVENT = "island_straggler_unavailable" +AVAILABLE_EVENT = "island_straggler_available" # the syncer's records are read again after a silent stretch DEFAULT_CYCLES = 3 SYNCER_TAPES = "tapes/syncer/" STORE_POLL_S = 30.0 # the syncer's uploads are 30 s apart (tape_upload.DEFAULT_INTERVAL_S) @@ -67,7 +71,8 @@ STORE_DISCOVER_POLLS = 10 # a full listing of tapes/syncer/ (a restarted syncer) every this many reads STORE_POLL_BUDGET_S = 5.0 # no new store request after this long in one poll MAX_READ_BYTES = 8 << 20 # one poll reads at most this much of a local tape -QUIET_POLLS = 10 # reads with islands running and no syncer record yet before that is said, once +QUIET_POLLS = 10 # reads without a syncer record, after the first one of this launch's islands, before that is said +CLOCK_SKEW_S = 600.0 # the launcher's and the syncer host's clocks may differ by this much WAIT = "wait" # the syncer merges without it; it is caught up once it delivers again REPLACE = "replace" # the island's provider replaces it (its own policy decides) @@ -115,11 +120,9 @@ class _Island: absent: bool = False flagged: bool = False token: Any = None - generation: tuple | None = None # (syncer_epoch, generation) of the join counted from - since: float | None = None # wall time it last left running: older records are another incarnation's - rejoined: str | None = None # a flagged island joined again as a new generation: why its stretch ends - away: bool = False # not running now (recovering, draining, ended): its count restarts at its next join + away: bool = False # not running now (recovering, draining, ended): its count restarts was_joined: bool = False # whether it was in the pool when it left running + joined_away: bool = False # a pool_join read while it was away (its next incarnation's, or a reconnect) def _time(record: Mapping[str, Any]) -> float | None: @@ -135,7 +138,8 @@ def _time(record: Mapping[str, Any]) -> float | None: @dataclass class StragglerTracker: """Folds syncer tape records (:meth:`feed`) and answers :meth:`check` (module doc). - ``since``: the watch's start (wall time); a record stamped before it is ignored.""" + ``since``: the watch's start (wall time); a record stamped more than + :data:`CLOCK_SKEW_S` before it is an earlier launch's history and is ignored.""" cycles: int = DEFAULT_CYCLES since: float | None = None @@ -151,27 +155,23 @@ def _island(self, k: int) -> _Island: def per_cycle(self) -> int: return max(1, len(self.fragments)) - @staticmethod - def _before(t: float | None, since: float | None) -> bool: - return t is not None and since is not None and t < since + def _history(self, t: float | None) -> bool: + """Stamped before the watch started, beyond the clock skew allowed between hosts.""" + return t is not None and self.since is not None and t < self.since - CLOCK_SKEW_S def feed(self, record: Mapping[str, Any]) -> None: kind = record.get("kind") - t = _time(record) - if kind not in ("pool_join", "outer_step") or self._before(t, self.since): + if kind not in ("pool_join", "outer_step") or self._history(_time(record)): return if kind == "pool_join": island = _int(record.get("island_id")) if island is None: return + # in the pool; a reconnect (a new connection generation) or a new syncer term keeps + # its count and its mark: only its controller's relaunch or stop restarts them state = self._island(island) - if self._before(t, state.since): - return # an earlier incarnation's join, read late - generation = (record.get("syncer_epoch"), record.get("generation")) - if not state.joined or generation != state.generation: - if state.joined and state.flagged: - state.rejoined = f"rejoined (generation {generation[1]}, syncer term {generation[0]})" - state.joined, state.misses, state.absent, state.generation = True, 0, False, generation + state.joined = True + state.joined_away = state.joined_away or state.away return step, fragment = _int(record.get("step")), _int(record.get("fragment")) if fragment is not None: @@ -180,18 +180,19 @@ def feed(self, record: Mapping[str, Any]) -> None: self.newest_step = step if self.newest_step is None else max(self.newest_step, step) merged = {_int(entry[0]) for entry in _entries(record.get("weights")) + _entries(record.get("raw_weights"))} absent = {_int(i) for i in record.get("absent") or () if _int(i) is not None} + for k in (merged | absent) - set(self.islands) - {None}: + self.islands[k] = _Island() for k, state in self.islands.items(): - if self._before(t, state.since): - continue # merged before its relaunch: not this incarnation's if k in merged: state.misses, state.absent = 0, False state.last_merged_step = step if step is not None else state.last_merged_step - state.joined = True # a merged push: it is in the pool (an adopted island's join came earlier) - elif state.joined: + state.joined = True # a merged push: it is in the pool + elif state.joined or k in absent: + # listed absent: the syncer expects it, so it is in the pool even when its join + # came before this watch (an island adopted by a restarted launcher) + state.joined = True state.misses += 1 state.absent = k in absent - for k in merged - set(self.islands) - {None}: - self.islands[k] = _Island(joined=True, last_merged_step=step) def check(self, running: Mapping[int, Any]) -> list[Straggler]: """The signals for the islands held running (learner id -> incarnation token), and @@ -201,27 +202,25 @@ def check(self, running: Mapping[int, Any]) -> list[Straggler]: for k, state in self.islands.items(): if k in running or state.token is None or state.away: continue - # it left running: what the syncer records from now on is its next incarnation's (a - # join of it may come before its controller holds it running again) + # it left running: its count restarts when it is running again if state.flagged: out.append(self._signal(k, state, cleared=True, reason="not running")) was_joined = state.joined self._restart(state) - state.away, state.was_joined = True, was_joined + state.away, state.was_joined, state.joined_away = True, was_joined, False for k, token in running.items(): state = self._island(int(k)) - if state.away and state.token == token: # the same incarnation back: counted from now - state.joined = state.joined or state.was_joined - elif state.token != token and state.token is not None and not state.away: + if state.away: + # back: the same incarnation keeps its place in the pool; a new one (relaunched) + # is in it once it joined, which may come before its controller holds it running + state.joined = state.joined_away or (state.token == token and state.was_joined) + state.misses, state.absent = 0, False + elif state.token is not None and state.token != token: # relaunched between two checks: its count starts at its next join if state.flagged: out.append(self._signal(int(k), state, cleared=True, reason="relaunched")) self._restart(state) - state.token, state.away = token, False - if state.rejoined is not None: - if state.flagged: - out.append(self._signal(int(k), state, cleared=True, reason=state.rejoined)) - state.flagged, state.rejoined = False, None + state.token, state.away, state.joined_away = token, False, False if self.cycles <= 0 or not state.joined: continue if not state.flagged and state.misses >= threshold: @@ -238,9 +237,9 @@ def check(self, running: Mapping[int, Any]) -> list[Straggler]: out.append(self._signal(k, state, cleared=True, reason="not running")) return out - def _restart(self, state: _Island) -> None: + @staticmethod + def _restart(state: _Island) -> None: state.joined, state.misses, state.absent, state.flagged = False, 0, False, False - state.generation, state.rejoined, state.since = None, None, self.clock() def _signal(self, k: int, state: _Island, *, cleared: bool, reason: str) -> Straggler: return Straggler(island=k, cleared=cleared, missed_cycles=state.misses // self.per_cycle, @@ -293,25 +292,29 @@ def read(self) -> list[dict[str, Any]]: return _records(data[: end + 1]) -def _incarnation_order(incarnation: str) -> tuple: - from yeto.dashboard.store_tapes import launch_started - - started = launch_started(incarnation) - return (0 if started is None else 1, started or 0.0, incarnation) +def _progress(records: list[dict[str, Any]]) -> tuple[int, int]: + """How far a syncer got in ``records``: its newest term (``syncer_epoch``) and step. A + restarted syncer resumes at its checkpoint's step or takes over in a new term, so the + newest incarnation is the furthest one; no clock is read.""" + epochs = [e for e in (_int(r.get("syncer_epoch")) for r in records) if e is not None] + steps = [s for s in (_int(r.get("step")) for r in records) if s is not None] + return (max(epochs, default=-1), max(steps, default=-1)) class StoreTape: """The syncer's tape in the run store (``tapes/syncer//.jsonl``). - The first read finds the newest syncer incarnation and starts at its tail: what the - syncer wrote before this watch is not read. From then on each read lists that - incarnation's prefix after its last chunk read (``start_after``) and reads its new chunks - in order, at most :data:`STORE_GETS_PER_POLL` (the rest at the next read). A newer - incarnation (a restarted syncer, found by a full listing every - :data:`STORE_DISCOVER_POLLS` reads) is read from its start once the current one has no - chunk left. A chunk read moves the cursor past it, so a request that fails keeps what was - read before it and is tried again at the next read (``error`` says why); no chunk is - read twice or skipped.""" + The first read establishes the tail: it lists every syncer incarnation, reads each one's + last chunk, and starts at the tail of the furthest one (the newest term, then the newest + step; :func:`_progress`): what the syncer wrote before this watch is not read. Until that + worked (a listing or a read failed) every read tries it again and reads nothing else. From + then on each read lists the current incarnation's prefix after its last chunk read + (``start_after``) and reads its new chunks in order, at most :data:`STORE_GETS_PER_POLL` + (the rest at the next read). An incarnation found later (a restarted syncer, by a full + listing every :data:`STORE_DISCOVER_POLLS` reads) did not exist at the first read: it is + read from its start once the current one has no chunk left. A chunk read moves the cursor + past it, so a request that fails keeps what was read before it and is tried again at the + next read (``error`` says why); no chunk is read twice or skipped.""" def __init__(self, objects: Any, *, interval_s: float = STORE_POLL_S, clock: Callable[[], float] | None = None, gets_per_poll: int = STORE_GETS_PER_POLL, @@ -326,6 +329,7 @@ def __init__(self, objects: Any, *, interval_s: float = STORE_POLL_S, self.label = f"{getattr(objects, 'uri', 'store')}/{SYNCER_TAPES}" self.error: str | None = None self.polled = False # whether the last read() asked the store (False within the interval) + self.tailed = False # the first read's tail is established self.reads = 0 self.requests = 0 # listings and chunk reads so far self._next: float | None = None @@ -349,19 +353,29 @@ def _incarnations(self) -> set[str]: return found cursor = f"{SYNCER_TAPES}{str(last)[len(SYNCER_TAPES):].split('/')[0]}/~" # past its chunks - def _discover(self, *, first: bool) -> None: - new = sorted((inc for inc in self._incarnations() if inc not in self.known), key=_incarnation_order) - if first and new: - newest = new[-1] - self.known.update(new) - self.queue = [newest] + def _tail(self) -> None: + """The first read: every incarnation's tail, and the furthest one to read from. + Committed only when every request worked (else tried again at the next read).""" + cursors, progress = {}, {} + for inc in sorted(self._incarnations()): self.requests += 1 - chunks = [str(k) for k in self.objects.list(f"{SYNCER_TAPES}{newest}/") if str(k).endswith(".jsonl")] - self.cursors[newest] = max(chunks, default="") # its tail: what it wrote before the watch is not read - return - newer = [inc for inc in new if not self.queue or _incarnation_order(inc) > _incarnation_order(self.queue[-1])] - self.known.update(new) # an older one found late (its syncer ran before this watch): not read - self.queue += newer + chunks = sorted(str(k) for k in self.objects.list(f"{SYNCER_TAPES}{inc}/") if str(k).endswith(".jsonl")) + cursors[inc] = chunks[-1] if chunks else "" + data = None + if chunks: + self.requests += 1 + data = self.objects.read(chunks[-1]) + records = _records(data if isinstance(data, bytes) else str(data or "").encode()) + progress[inc] = (*_progress(records), inc) + self.cursors.update(cursors) + self.known.update(cursors) + self.queue = [max(progress, key=progress.__getitem__)] if progress else [] + self.tailed = True + + def _discover(self) -> None: + new = sorted(inc for inc in self._incarnations() if inc not in self.known) + self.known.update(new) # not there at the first read: newer than every one that was + self.queue += new def read(self) -> list[dict[str, Any]]: now = self.clock() @@ -371,13 +385,13 @@ def read(self) -> list[dict[str, Any]]: self._next = now + self.interval_s self.polled, self.error = True, None started, out, gets, lists = self.clock(), [], 0, 0 - first = self.reads == 0 self.reads += 1 try: - if first or not self.queue or self.reads % self.discover_polls == 0: - self._discover(first=first) - if first: - return [] + if not self.tailed: + self._tail() + return [] + if not self.queue or self.reads % self.discover_polls == 0: + self._discover() while self.queue and gets < self.gets_per_poll and lists < STORE_LISTS_PER_POLL \ and self.clock() - started < self.budget_s: inc = self.queue[0] @@ -423,8 +437,12 @@ def _records(data: bytes) -> list[dict[str, Any]]: class StragglerWatch: """A tracker fed from one source: :meth:`poll` reads what the syncer added and returns the signals for the islands held running. A read that fails is logged once per stretch - of failures and tried again at the next poll. :meth:`notices` hands the controller, once, - why nothing is reported (the source stayed silent for :data:`QUIET_POLLS` reads).""" + of failures and tried again at the next poll. :meth:`notices` hands the controller + ``(event, reason)`` pairs to write: once the syncer recorded something about this launch's + islands (a join, or a merge that merged or expected one), :data:`QUIET_POLLS` reads in a + row without any record are said once (:data:`UNAVAILABLE_EVENT`), and the next record read + takes it back (:data:`AVAILABLE_EVENT`). A fleet whose trainers start slowly is never said + to be unavailable: nothing is counted before that first record.""" def __init__(self, source: Any, *, cycles: int = DEFAULT_CYCLES, since: float | None = None, log: Callable[[str], None] | None = None, clock: Callable[[], float] = time.time) -> None: @@ -434,8 +452,20 @@ def __init__(self, source: Any, *, cycles: int = DEFAULT_CYCLES, since: float | self.tracker = StragglerTracker(cycles=int(cycles), since=since, clock=clock) self.log = log or (lambda m: print(m, file=sys.stderr, flush=True)) self._failing = False - self._quiet = 0 # reads with islands running and no syncer record yet; -1 once one was read - self._notices: list[str] = [] + self._seen = False # a record about one of this launch's islands was read + self._quiet = 0 # reads in a row without a record since then + self._said = False # the silence was said (UNAVAILABLE_EVENT) and not taken back yet + self._notices: list[tuple[str, str]] = [] + + @staticmethod + def _about(record: Mapping[str, Any], islands: Any) -> bool: + if record.get("kind") == "pool_join": + return _int(record.get("island_id")) in islands + if record.get("kind") == "outer_step": + named = {_int(e[0]) for e in _entries(record.get("weights")) + _entries(record.get("raw_weights"))} + named |= {_int(i) for i in record.get("absent") or ()} + return bool(named & set(islands)) + return False def poll(self, running: Mapping[int, Any]) -> list[Straggler]: try: @@ -452,18 +482,24 @@ def poll(self, running: Mapping[int, Any]) -> list[Straggler]: self._failing = False for record in records: self.tracker.feed(record) + islands = {int(k) for k in running} | {k for k, s in self.tracker.islands.items() if s.token is not None} + self._seen = self._seen or any(self._about(r, islands) for r in records) if records: - self._quiet = -1 - elif running and self._quiet >= 0 and getattr(self.source, "polled", True): + self._quiet = 0 + if self._said: + self._said = False + self._notices.append((AVAILABLE_EVENT, f"syncer records read again from {self.source.label}")) + elif self._seen and running and getattr(self.source, "polled", True): self._quiet += 1 - if self._quiet == QUIET_POLLS: + if self._quiet == QUIET_POLLS and not self._said: + self._said = True why = (f"no syncer record read from {self.source.label} in {QUIET_POLLS} reads; no straggler is " - "reported until the syncer's tape is there") + "reported until the syncer's tape is read again") self.log(f"[launcher] WARNING: island straggler watch: {why}") - self._notices.append(why) + self._notices.append((UNAVAILABLE_EVENT, why)) return self.tracker.check(running) - def notices(self) -> list[str]: + def notices(self) -> list[tuple[str, str]]: out, self._notices = self._notices, [] return out @@ -474,12 +510,12 @@ class UnavailableWatch: def __init__(self, reason: str) -> None: self.reason = reason - self._notices = [reason] + self._notices = [(UNAVAILABLE_EVENT, reason)] def poll(self, running: Mapping[int, Any]) -> list[Straggler]: return [] - def notices(self) -> list[str]: + def notices(self) -> list[tuple[str, str]]: out, self._notices = self._notices, [] return out From f6f6546ec99c2a886ba17b39a7fe452712f4be95 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 23:19:48 +0800 Subject: [PATCH 06/13] Test the Islands now row's visible text, not its markup Co-Authored-By: Claude Opus 5.5 --- tests/test_dashboard_island_straggler.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_dashboard_island_straggler.py b/tests/test_dashboard_island_straggler.py index d73f98556..0c8a9a713 100644 --- a/tests/test_dashboard_island_straggler.py +++ b/tests/test_dashboard_island_straggler.py @@ -6,6 +6,7 @@ from __future__ import annotations import json +import re import shutil import subprocess from pathlib import Path @@ -80,7 +81,9 @@ def test_the_trainer_card_draws_a_straggler_badge_until_cleared(tmp_path): assert "straggler" in flagged["texts"] # the topology's trainer card # Islands now: trainer 1's row says straggler in warn colour in place of "ok", once assert flagged["nodes"].count('straggler') == 1 - assert "ok · straggler" not in flagged["nodes"] and "straggler" not in flagged["matrix"] # not in Fragments + shown = re.sub(r"<[^>]+>", "", flagged["nodes"]) # the row's visible text + assert "H100 × 2 · straggler" in shown and "ok · straggler" not in shown + assert "straggler" not in flagged["matrix"] # not in the Fragments rows for r in (_reducer(), _reducer(_flagged(), _cleared())): out = _smoke(tmp_path / str(len(r.fleet_records)), r) assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] From 1719d074782d2f19520bebed1442df3c322efe63 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 23:43:49 +0800 Subject: [PATCH 07/13] dashboard: read the straggler mark from the island's record _trainer_records dropped the record's straggler, so island_now.straggler was always None on the production path and the card never showed it. Test the path end to end: the controller writes the mark, read_fleet_state reads the run store, the card and its Islands now row show it. Co-Authored-By: Claude Opus 5.5 --- tests/test_dashboard_island_straggler.py | 32 ++++++++++++++++++++++++ yeto/dashboard/fleet_islands.py | 14 ++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/tests/test_dashboard_island_straggler.py b/tests/test_dashboard_island_straggler.py index 0c8a9a713..480b85549 100644 --- a/tests/test_dashboard_island_straggler.py +++ b/tests/test_dashboard_island_straggler.py @@ -106,6 +106,38 @@ def test_the_island_record_s_mark_wins_over_the_events(tmp_path): assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] +def test_the_controller_s_mark_reaches_the_card_through_the_island_records(tmp_path): + """The production path: the controller writes the mark to the island's record in the run + store, ``read_fleet_state`` reads it back (``_trainer_records``) and the card shows it.""" + from test_island_straggler import _controller, _join, _step + + from yeto.dashboard import fleet_islands + from yeto.rl.engine.object_store import DirectoryObjectStore + + ctl, _ops, _store, tape, _log = _controller(tmp_path) + tape.pending += [_join(0), _join(1), _step(1, [0, 1], fragments=1), _step(2, [0], fragments=1, absent=[1])] + ctl._poll_stragglers() # island 1 missed one cycle: reported, its record carries the mark + + def card_of(): # a fresh read of the run store, as the dashboard's poll does + r = _reducer() # no island_straggler event: only the record can tell + assert r.load_fleet_state(fleet_islands.read_fleet_state(DirectoryObjectStore(str(tmp_path / "store")))) + return r, _cards(r)["1"] + + r, card = card_of() + mark = card["island_now"]["straggler"] + assert mark["action"] == st.WAIT and mark["missed_cycles"] == 1 and mark["last_merged_step"] == 1 + assert mark["newest_step"] == 2 and mark["absent"] is True and isinstance(mark["at"], float) + assert (_cards(r)["0"]["island_now"] or {}).get("straggler") is None # island 0: no mark + out = _smoke(tmp_path / "flagged", r) + assert out["nodes"].count('straggler') == 1 + tape.pending.append(_step(3, [0, 1], fragments=1)) + ctl._poll_stragglers() # a push of it is merged again: cleared in its record + r, card = card_of() + assert card["island_now"]["straggler"] is None + out = _smoke(tmp_path / "cleared", r) + assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] + + def test_the_event_stream_shows_the_straggler_events(tmp_path): end = fleet_reducer().max_ts # the newest events: the stream shows the latest 15 events = _smoke(tmp_path, _reducer(_flagged(at=end + 10), _cleared(at=end + 20)))["events"] diff --git a/yeto/dashboard/fleet_islands.py b/yeto/dashboard/fleet_islands.py index 81568fe25..278d4ba54 100644 --- a/yeto/dashboard/fleet_islands.py +++ b/yeto/dashboard/fleet_islands.py @@ -323,10 +323,22 @@ def _trainer_records(objects: Any, learners: Any = None) -> dict[int, dict]: "started_at": _f(launch.get("started_at")), "closed_at": _f(launch.get("closed_at")), "down_at": _f(launch.get("down_at")), "name": _str(launch.get("name")), "moving_to": _str(launch.get("moving_to")), - "last_exit": {"code": _int(ended.get("exit_code")), "detail": _str(ended.get("detail"))} if ended else None} + "last_exit": {"code": _int(ended.get("exit_code")), "detail": _str(ended.get("detail"))} if ended else None, + "straggler": _straggler(life.get("straggler"))} return out +def _straggler(mark: Any) -> dict | None: + """The controller's straggler mark in an island's record (``yeto.launch.island_straggler``, + written by ``FleetController._island_straggler``; None once cleared).""" + if not isinstance(mark, dict): + return None + return {**{k: _int(mark.get(k)) for k in ("missed_cycles", "merges", "fragments", "cycles", "newest_step", + "last_merged_step")}, + "action": _str(mark.get("action")), "reason": _str(mark.get("reason")), + "absent": mark.get("absent") is True, "at": _f(mark.get("at"))} + + 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)", From 9491e247205a14eb7d5a773bc357aa078d677af7 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 15:58:29 +0800 Subject: [PATCH 08/13] fleet island add: an ssh: island's own inventory, its nodes checked before it joins yeto fleet island add --inventory PATH gives an ssh: island its node inventory (its launch's --rl-node-inventory). Before anything is written, and in the dry run, the inventory's trainer nodes must be as many as --gpu says, none of them a trainer node of another ssh: island of the fleet (name or SSH target), healthy by the node health checker of their device family (one SSH call per node; a multi-node island also checks its NCCL_IB_HCA ports), placed in one fabric group (fabric_groups.check_placement), and not leased to another run (NodeLeases of the inventory's lease_store). Any of them failing refuses the add with exit 2, naming each problem, and claims no learner id. A device family without a checker, an inventory without fabric groups or without a lease store is noted, not refused. A check whose module is not there refuses. The health checker, the placement check and the leases are called through the own-cluster contract's signatures; the tests use stand-ins with those signatures. Co-Authored-By: Claude Opus 5.5 --- docs/OWN_CLUSTERS.md | 35 +++- tests/test_island_join.py | 253 +++++++++++++++++++++++++ tests/test_own_clusters_islands_doc.py | 42 ++-- yeto/launch/island_join.py | 223 ++++++++++++++++++++++ yeto/rl/fleet_islands.py | 32 +++- 5 files changed, 568 insertions(+), 17 deletions(-) create mode 100644 tests/test_island_join.py create mode 100644 yeto/launch/island_join.py diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index c335241d9..f8bcc62c3 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -483,7 +483,7 @@ To drop the rule, delete the `fabric_group` lines. A fleet of `ssh:` trainer islands on your own machines uses the same fleet mechanisms as any other island fleet ([FLEET_TRAINER_ISLANDS.md](FLEET_TRAINER_ISLANDS.md)). This section covers what is specific to `ssh:` islands: how a slow or stuck island is reported, and what -happens when one leaves. +is checked before an island joins. ### An island that lags @@ -583,6 +583,39 @@ reported then, and training is not affected. This happens: fleet whose trainers are still starting is not reported. Once records are read again, the launch writes `island_straggler_available`. +### Adding an island + +With `fleet.launch: per_island`, add an `ssh:` island with its own node inventory. Its +inventory lists the island's trainer nodes, in the format of `--rl-node-inventory`: + +```bash +yeto fleet island add --config run.json --name north --gpu ssh:2x8xb300@bm --usd-per-h 0 \ + --samplers north.samplers.json --inventory north.inventory.yaml --dry-run +yeto fleet island add --config run.json --name north --gpu ssh:2x8xb300@bm --usd-per-h 0 \ + --samplers north.samplers.json --inventory north.inventory.yaml +``` + +The island's launch gets `--rl-node-inventory north.inventory.yaml`. Before anything is +written, and in the dry run too, the command checks the inventory's trainer nodes: + +| Check | Refused when | +|---|---| +| Count | The inventory does not list as many trainer nodes as `--gpu` says. | +| In this fleet | A node (by name or SSH target) is a trainer node of another `ssh:` island of the fleet. | +| Health | The node health check (one SSH call per node) finds a fault: GPU count or memory, an Xid, uncorrectable ECC, Fabric Manager. A multi-node island also needs the `NCCL_IB_HCA` ports active and at rate. A node that does not answer is refused. A device family without a health check is noted, not refused. | +| Fabric group | The inventory declares `fabric_group` and no one group holds the island's nodes. An inventory without any `fabric_group` only gets a note. | +| Lease | The inventory's `lease_store` shows a node leased to another run. Without `lease_store` this is not checked, and a note says so. | + +A refusal exits 2, names every problem, and writes nothing. No learner id is claimed: + +```text +fleet island: refused: island north's nodes cannot join: node b300-5 is not healthy: Xid 79 since the last check; node b300-4 is leased to run other-run +``` + +Once the island is written, the trainer worker starts its launch. The island joins the +running syncer session, catches up to the newest merged weights, and then answers rounds +like the other islands. The other islands' processes keep running; they are not restarted. + ### Removing an island ```bash diff --git a/tests/test_island_join.py b/tests/test_island_join.py new file mode 100644 index 000000000..c53761d88 --- /dev/null +++ b/tests/test_island_join.py @@ -0,0 +1,253 @@ +"""The join checks of an ssh: trainer island added at run time (own-cluster-fleet-stability +9.3): its inventory's trainer nodes must be free in this fleet, healthy (node health), in one +fabric group (fabric_groups.check_placement) and not leased to another run (NodeLeases); +any one of them failing refuses ``yeto fleet island add`` with its reason, writing nothing. + +The node health checker, the placement check and the leases are stand-ins with the +signatures of the own-cluster contract (``checker_for(family).script(hcas) / .parse(text, +hcas, prev) -> HealthResult``, ``check_placement(nodes, need) -> (ok, message, hint_only)``, +``NodeLeases(store_uri, run_id).holder(node)``).""" + +from __future__ import annotations + +import json +import subprocess +from dataclasses import dataclass, field + +import pytest + +from test_fleet_island_changes import fleet_store # noqa: F401 - fixture +from yeto.launch import island_join as ij +from yeto.launch.learner_ids import claim_key +from yeto.launch.node_inventory import load_inventory +from yeto.rl import fleet_islands + +GPU = "ssh:2x8xb300@bm" + + +@dataclass +class HealthResult: # the contract's yeto.hw.node_health.HealthResult + checked: bool + ok_single: bool | None + ok_multi: bool | None + reasons: list[str] = field(default_factory=list) + facts: dict = field(default_factory=dict) + + +class Checker: + """Answers per node (the script prints the node's name here): ``bad`` nodes fail with + their reason; ``ib_down`` nodes are healthy alone but not for a multi-node island.""" + + def __init__(self, bad=None, ib_down=(), checked=True): + self.bad, self.ib_down, self.checked = dict(bad or {}), set(ib_down), checked + self.scripts: list[list[str]] = [] + + def script(self, hcas): + self.scripts.append(list(hcas)) + return "health-probe" + + def parse(self, text, hcas, prev): + name = text.strip() + if not self.checked: + return HealthResult(False, None, None, ["not checked"]) + if name in self.bad: + return HealthResult(True, False, False, [self.bad[name]]) + if name in self.ib_down: + return HealthResult(True, True, False, ["mlx5_3 DOWN"]) + return HealthResult(True, True, True) + + +class Ssh: + def __init__(self, unreachable=()): + self.unreachable = set(unreachable) + self.calls: list[str] = [] + + def run(self, node, script, *, timeout): + self.calls.append(node.name) + if node.name in self.unreachable: + return subprocess.CompletedProcess([], 255, stdout="", stderr="ssh: connect to host: timed out\n") + return subprocess.CompletedProcess([], 0, stdout=node.name + "\n", stderr="") + + +class Leases: + made: list[tuple[str, str]] = [] + + def __init__(self, store_uri, run_id, holders=None): + Leases.made.append((store_uri, run_id)) + self.holders = dict(holders or {}) + + def holder(self, node): + return self.holders.get(getattr(node, "name", node)) + + +@pytest.fixture +def stand_ins(monkeypatch): + """The three checks' modules, as the contract has them; returns their knobs.""" + knobs = {"checker": Checker(), "placement": (True, "", False), "holders": {}, "placed": []} + monkeypatch.setattr(ij, "_checker_for", lambda family: knobs["checker"]) + + def placement(nodes, need): + knobs["placed"].append(([n.name for n in nodes], need)) + return knobs["placement"] + + monkeypatch.setattr(ij, "_check_placement", placement) + monkeypatch.setattr(ij, "_node_leases", lambda uri, run: Leases(uri, run, knobs["holders"])) + return knobs + + +def _inventory(path, names, *, env=None): + path.write_text("nodes:\n" + "".join( + f" - {{name: {name}, host: ops@{name}.example, address: 198.51.100.{10 + i}, interface: bond0, " + "device_family: cuda, cpu_arch: x86_64, card: B300, cards_per_node: 8, hbm_gib: 288, " + "host_memory_gib: 2048, fabric: ib, runtime: docker, docker_args: [--gpus, all]" + + (f", env: {{NCCL_IB_HCA: '{env}'}}" if env else "") + "}\n" for i, name in enumerate(names))) + return path + + +def _nodes(tmp_path, names=("b300-4", "b300-5"), **kw): + return load_inventory(_inventory(tmp_path / "inv.yaml", names, **kw)) + + +def test_healthy_free_nodes_of_one_group_join(tmp_path, stand_ins): + nodes = _nodes(tmp_path, env="mlx5_0,mlx5_1") + out = ij.check(nodes, need=2, run_id="r", lease_store="s3://b/leases", ssh=Ssh()) + assert out.ok and out.refusals == [] and out.notes == [] + assert stand_ins["checker"].scripts == [["mlx5_0", "mlx5_1"]] * 2 # a multi-node island checks its HCAs + assert stand_ins["placed"] == [(["b300-4", "b300-5"], 2)] and Leases.made[-1] == ("s3://b/leases", "r") + + +def test_an_unhealthy_node_refuses_the_island_naming_why(tmp_path, stand_ins): + stand_ins["checker"] = Checker(bad={"b300-5": "Xid 79 since the last check"}) + out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) + assert out.refusals == ["node b300-5 is not healthy: Xid 79 since the last check"] + + +def test_a_port_down_refuses_a_multi_node_island_only(tmp_path, stand_ins): + stand_ins["checker"] = Checker(ib_down={"b300-4"}) + assert ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()).refusals == [ + "node b300-4 is not healthy: mlx5_3 DOWN"] + one = _nodes(tmp_path, names=("b300-4",)) + assert ij.check(one, need=1, run_id="r", ssh=Ssh()).ok + assert stand_ins["checker"].scripts[-1] == [] # alone: the GPU checks only + + +def test_a_node_that_does_not_answer_is_refused(tmp_path, stand_ins): + out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh(unreachable={"b300-4"})) + assert out.refusals == ["node b300-4: its health check did not answer (ssh exit 255: ssh: connect to host: " + "timed out)"] + + +def test_a_family_without_a_checker_is_noted_not_refused(tmp_path, stand_ins): + stand_ins["checker"] = Checker(checked=False) + out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) + assert out.ok and any("no health check for device family cuda" in n for n in out.notes) + + +def test_nodes_across_fabric_groups_refuse_the_island(tmp_path, stand_ins): + stand_ins["placement"] = (False, "the island needs 2 healthy nodes of one fabric group; group a has only 1, " + "group b has only 1", False) + out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) + assert out.refusals == ["fabric: the island needs 2 healthy nodes of one fabric group; group a has only 1, " + "group b has only 1"] + + +def test_an_inventory_without_groups_is_only_a_note(tmp_path, stand_ins): + stand_ins["placement"] = (True, "no fabric_group in the inventory: run yeto cluster probe --write", True) + out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) + assert out.ok and out.notes[0].startswith("fabric: no fabric_group") + + +def test_a_node_leased_to_another_run_is_refused_and_this_run_s_own_is_free(tmp_path, stand_ins): + stand_ins["holders"] = {"b300-4": "other-run", "b300-5": "r"} + out = ij.check(_nodes(tmp_path), need=2, run_id="r", lease_store="s3://b/leases", ssh=Ssh()) + assert out.refusals == ["node b300-4 is leased to run other-run"] + out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) # no lease_store: noted + assert out.ok and any("no lease_store" in n for n in out.notes) + + +def test_a_node_of_another_island_or_the_wrong_count_is_refused(tmp_path, stand_ins): + nodes = _nodes(tmp_path) + out = ij.check(nodes, need=2, run_id="r", taken={"ops@b300-5.example": "sglang"}, ssh=Ssh()) + assert out.refusals == ["node b300-5 is island sglang's"] + out = ij.check(nodes, need=3, run_id="r", ssh=Ssh()) + assert out.refusals == ["the island needs 3 trainer node(s); its inventory lists 2 ['b300-4', 'b300-5']"] + + +def test_checks_whose_modules_are_missing_refuse(tmp_path, monkeypatch): + def missing(*a, **kw): + raise ImportError("No module named 'yeto.hw.node_health'") + + for name in ("_checker_for", "_check_placement", "_node_leases"): + monkeypatch.setattr(ij, name, missing) + out = ij.check(_nodes(tmp_path), need=2, run_id="r", lease_store="s3://b/l", ssh=Ssh()) + assert len(out.refusals) == 4 and all("ImportError" in r for r in out.refusals) + + +# -- yeto fleet island add -------------------------------------------------------------------------- + +def _add(run_cli, samplers, inventory, *extra): + return run_cli("add", "--name", "north", "--gpu", GPU, "--usd-per-h", "0", "--samplers", str(samplers), + "--inventory", str(inventory), *extra) + + +@pytest.mark.parametrize("problem", ["health", "fabric", "lease"]) +def test_add_refuses_an_ssh_island_failing_one_check_and_writes_nothing(fleet_store, stand_ins, tmp_path, # noqa: F811 + monkeypatch, capsys, problem): + cfg, objects, store, run_cli, samplers = fleet_store + inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) + monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", Ssh) + if problem == "health": + stand_ins["checker"] = Checker(bad={"b300-4": "GPU count 7, expected 8"}) + why = "node b300-4 is not healthy: GPU count 7, expected 8" + elif problem == "fabric": + stand_ins["placement"] = (False, "group a has only 1, group b has only 1", False) + why = "fabric: group a has only 1, group b has only 1" + else: + monkeypatch.setattr(ij, "lease_store_of", lambda path: "s3://b/leases") + stand_ins["holders"] = {"b300-5": "another-run"} + why = "node b300-5 is leased to run another-run" + monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda *a, **kw: pytest.fail("checked before the dry run")) + for dry in ((), ("--dry-run",)): + assert _add(run_cli, samplers, inventory, *dry) == 2 + err = capsys.readouterr().err + assert "refused: island north's nodes cannot join: " + why in err + assert store.read()["generation"] == 1 and objects.read(claim_key(2)) is None + + +def test_add_takes_an_ssh_island_whose_nodes_pass(fleet_store, stand_ins, tmp_path, monkeypatch, capsys): # noqa: F811 + cfg, objects, store, run_cli, samplers = fleet_store + inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) + monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", Ssh) + dry_runs = [] + monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda member, **kw: dry_runs.append(member)) + monkeypatch.setattr(fleet_islands, "session_check", lambda *a, **kw: None) + assert _add(run_cli, samplers, inventory) == 0 + out = capsys.readouterr() + assert "island north's nodes pass the join checks" in out.out + assert "note: island north: no lease_store" in out.err + (member,) = dry_runs + assert member["argv"][-2:] == ["--rl-node-inventory", str(inventory)] and member["gpu"] == GPU + assert store.read()["generation"] == 2 and objects.read(claim_key(2)) is not None + + +def test_a_second_ssh_island_on_the_nodes_of_the_first_is_refused(fleet_store, stand_ins, tmp_path, # noqa: F811 + monkeypatch, capsys): + cfg, objects, store, run_cli, samplers = fleet_store + monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", Ssh) + monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda member, **kw: None) + monkeypatch.setattr(fleet_islands, "session_check", lambda *a, **kw: None) + assert _add(run_cli, samplers, _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"])) == 0 + other = samplers.parent / "south.samplers.json" + other.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) + south = _inventory(tmp_path / "south.yaml", ["b300-5", "b300-6"]) + assert run_cli("add", "--name", "south", "--gpu", GPU, "--usd-per-h", "0", "--samplers", str(other), + "--inventory", str(south)) == 2 + assert "node b300-5 is island north's" in capsys.readouterr().err + + +def test_an_inventory_is_for_an_ssh_island_only(fleet_store, tmp_path, capsys): # noqa: F811 + cfg, objects, store, run_cli, samplers = fleet_store + inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) + assert run_cli("add", "--name", "north", "--gpu", "modal:1x2xh100", "--usd-per-h", "8", "--samplers", + str(samplers), "--inventory", str(inventory)) == 2 + assert "--inventory is the node inventory of an ssh: island" in capsys.readouterr().err diff --git a/tests/test_own_clusters_islands_doc.py b/tests/test_own_clusters_islands_doc.py index 4821886e7..5d69f7fb5 100644 --- a/tests/test_own_clusters_islands_doc.py +++ b/tests/test_own_clusters_islands_doc.py @@ -1,7 +1,7 @@ """docs/OWN_CLUSTERS.md, "Islands that lag, join or leave": every command of the section parses, the ``yeto fleet island`` ones run in the doc's order on a seeded per-island fleet -(local store), each dry run writes nothing, and the flags and events the section names are -the code's.""" +(local store; the join checks' node health, placement and leases stand-ins), each dry run +writes nothing, and the flags, events and refusal the section shows are the code's.""" from __future__ import annotations @@ -10,9 +10,10 @@ from pathlib import Path from test_fleet_island_changes import fleet_store # noqa: F401 - fixture - +from test_island_join import Leases, Ssh, _inventory, stand_ins # noqa: F401 - fixture +from yeto.launch import island_join as ij from yeto.launch import island_straggler as st -from yeto.rl import fleet, fleet_islands +from yeto.rl import fleet_islands DOC = Path(__file__).resolve().parents[1] / "docs" / "OWN_CLUSTERS.md" SECTION = "## Islands that lag, join or leave" @@ -47,23 +48,40 @@ def test_the_section_names_the_code_s_flags_and_events(): assert f"`{field}`" in text, field -def test_the_section_commands_run_in_order(fleet_store, capsys): # noqa: F811 +def test_the_section_commands_run_in_order(fleet_store, stand_ins, tmp_path, monkeypatch, capsys): # noqa: F811 from yeto.cli import build_parser - cfg, _objects, store, run_cli, _samplers = fleet_store + _cfg, _objects, store, run_cli, samplers = fleet_store argvs = commands() assert {a[1] for a in argvs} == {"fleet", "island"} for argv in argvs: build_parser().parse_args(argv[1:]) - plan = fleet.plan_of(cfg) # the island the section removes - entry = dict(cfg["islands"][1]["samplers"][0], name="sglang-north") - member, pools = fleet_islands.compile_island(cfg, plan, k=2, name="north", gpu="modal:1x2xh100", usd_per_h=8.0, - samplers=[entry]) - store.update(lambda d: fleet_islands.add(d, member, pools), note="add north") + monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", Ssh) + monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda member, **kw: None) + monkeypatch.setattr(fleet_islands, "session_check", lambda *a, **kw: None) + inventory = _inventory(tmp_path / "north.inventory.yaml", ["b300-4", "b300-5"]) for argv in (a for a in argvs if a[:3] == ["yeto", "fleet", "island"]): - rest = argv[3:] + rest = [str(samplers) if a == "north.samplers.json" else str(inventory) if a == "north.inventory.yaml" + else a for a in argv[3:]] config = rest.index("--config") del rest[config:config + 2] before = store.read()["generation"] assert run_cli(*rest) == 0, (argv, capsys.readouterr().err) + out = capsys.readouterr().out assert store.read()["generation"] == before + (0 if "--dry-run" in argv else 1) + if argv[3] == "add": + assert "nodes pass the join checks" in out + + +def test_the_refusal_the_section_shows_is_the_command_s(tmp_path, stand_ins, monkeypatch): # noqa: F811 + from test_island_join import Checker + + stand_ins["checker"] = Checker(bad={"b300-5": "Xid 79 since the last check"}) + stand_ins["holders"] = {"b300-4": "other-run"} + from yeto.launch.node_inventory import load_inventory + + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["b300-4", "b300-5"])) + out = ij.check(nodes, need=2, run_id="r", lease_store="s3://b/leases", ssh=Ssh()) + line = "fleet island: refused: island north's nodes cannot join: " + "; ".join(out.refusals) + assert line in section() + assert Leases.made diff --git a/yeto/launch/island_join.py b/yeto/launch/island_join.py new file mode 100644 index 000000000..bc1ac7118 --- /dev/null +++ b/yeto/launch/island_join.py @@ -0,0 +1,223 @@ +"""The checks a new ``ssh:`` trainer island's nodes pass before ``yeto fleet island add`` +writes it into a running fleet (own-cluster-fleet-stability 9.3). + +An island added at run time takes the trainer nodes of its own inventory (the inventory +option of ``yeto fleet island add``: its launch's ``--rl-node-inventory``). Before anything is written +(and in the dry run), those nodes must: + +* be as many as the island's ``--gpu`` says, with no node another ``ssh:`` island of the + fleet already trains on (same name or SSH target); +* be healthy: the node health checker of their device family (``yeto.hw.node_health``), + one SSH call per node; a multi-node island also needs its ``NCCL_IB_HCA`` ports up at + rate. A device family without a checker is noted, not refused; a node that does not + answer is refused; +* fit one fabric group (``yeto.launch.fabric_groups.check_placement``): an inventory that + declares groups refuses a multi-node island across groups; one without any group only + notes it; +* be free in the inventory's ``lease_store`` (``yeto.launch.node_lease.NodeLeases``): a node + another run holds is refused, naming that run. Without a ``lease_store`` nothing is + checked (noted once). + +:func:`check` returns what was refused and noted; ``yeto fleet island add`` prints the notes +and refuses the change (exit 2, nothing written) on any refusal, naming each. +""" + +from __future__ import annotations + +import sys +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +INVENTORY_FLAG = "--rl-node-inventory" +HEALTH_TIMEOUT_S = 120.0 + + +@dataclass +class JoinCheck: + refusals: list[str] = field(default_factory=list) + notes: list[str] = field(default_factory=list) + + @property + def ok(self) -> bool: + return not self.refusals + + +def inventory_of(argv: Sequence[str]) -> str | None: + """The last ``--rl-node-inventory`` of a launch argv (the island's own wins over the fleet's).""" + found = None + for i, arg in enumerate(argv): + if arg == INVENTORY_FLAG and i + 1 < len(argv): + found = str(argv[i + 1]) + elif str(arg).startswith(INVENTORY_FLAG + "="): + found = str(arg).split("=", 1)[1] + return found + + +def lease_store_of(path: str | Path) -> str | None: + """The inventory's top-level ``lease_store`` (None when it declares none).""" + import yaml # noqa: PLC0415 - as node_inventory + + doc = yaml.safe_load(Path(path).expanduser().read_text()) + value = doc.get("lease_store") if isinstance(doc, dict) else None + return str(value) if value else None + + +def island_nodes(argv: Sequence[str], gpu: str) -> tuple[list[Any], int, str | None]: + """``(trainer nodes, nodes the island needs, inventory path)`` of an ``ssh:`` island's + launch argv; raises ValueError naming what is wrong.""" + from ..gpu_spec import parse_gpu_spec # noqa: PLC0415 + from .node_inventory import island_nodes as role_nodes # noqa: PLC0415 + from .node_inventory import load_inventory # noqa: PLC0415 + + (spec, *rest) = parse_gpu_spec(gpu) + if rest or spec.cloud != "ssh": + raise ValueError(f"--gpu {gpu}: one ssh: cluster expected") + path = inventory_of(argv) + if path is None: + raise ValueError(f"an ssh: island needs its node inventory ({INVENTORY_FLAG}; the inventory option " + "of yeto fleet island add)") + return role_nodes(load_inventory(path), "trainer"), int(spec.num_nodes), path + + +# -- the three checks (their modules: yeto.hw.node_health, fabric_groups, node_lease) ------------ + +def _checker_for(family: str) -> Any: + from yeto.hw.node_health import checker_for # noqa: PLC0415 + + return checker_for(family) + + +def _check_placement(nodes: Sequence[Any], need: int) -> tuple[bool, str, bool]: + from .fabric_groups import check_placement # noqa: PLC0415 + + return check_placement(nodes, need) + + +def _node_leases(store_uri: str, run_id: str) -> Any: + from .node_lease import NodeLeases # noqa: PLC0415 + + return NodeLeases(store_uri, run_id) + + +def _hcas(node: Any) -> list[str]: + spec = str((getattr(node, "env", None) or {}).get("NCCL_IB_HCA") or "") + return [part for part in spec.split(",") if part] + + +def check_health(nodes: Sequence[Any], *, multi: bool, ssh: Any, out: JoinCheck) -> None: + for node in nodes: + try: + checker = _checker_for(node.device_family) + hcas = _hcas(node) if multi else [] + done = ssh.run(node, checker.script(hcas), timeout=HEALTH_TIMEOUT_S) + except Exception as error: # noqa: BLE001 - named in the refusal + out.refusals.append(f"node {node.name}: its health check could not run ({type(error).__name__}: " + f"{error})"[:300]) + continue + if done.returncode != 0: + last = [line for line in str(done.stderr or "").splitlines() if line.strip()][-1:] + out.refusals.append(f"node {node.name}: its health check did not answer (ssh exit {done.returncode}" + + (f": {last[0].strip()}" if last else "") + ")") + continue + result = checker.parse(str(done.stdout or ""), hcas, None) + if not result.checked: + out.notes.append(f"node {node.name}: no health check for device family {node.device_family}") + continue + ok = result.ok_multi if multi else result.ok_single + if ok is False: + out.refusals.append(f"node {node.name} is not healthy: {'; '.join(result.reasons) or 'no reason given'}") + elif ok is None: + out.notes.append(f"node {node.name}: its health could not be judged ({'; '.join(result.reasons)})") + + +def check_fabric(nodes: Sequence[Any], need: int, out: JoinCheck) -> None: + ok, message, hint_only = _check_placement(nodes, need) + if not ok and not hint_only: + out.refusals.append(f"fabric: {message}") + elif message and (hint_only or not ok): + out.notes.append(f"fabric: {message}") + + +def check_leases(nodes: Sequence[Any], *, lease_store: str | None, run_id: str, out: JoinCheck) -> None: + if not lease_store: + out.notes.append("no lease_store in the inventory: whether another run uses these nodes is not checked") + return + try: + leases = _node_leases(lease_store, run_id) + except Exception as error: # noqa: BLE001 + out.refusals.append(f"lease store {lease_store}: {type(error).__name__}: {error}"[:300]) + return + for node in nodes: + try: + holder = leases.holder(node) + except Exception as error: # noqa: BLE001 - unknown is not free + out.refusals.append(f"node {node.name}: its lease does not read ({type(error).__name__}: {error})"[:300]) + continue + if holder is not None and holder != run_id: + out.refusals.append(f"node {node.name} is leased to run {holder}") + + +def check(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str | None = None, + taken: Mapping[str, str] | None = None, ssh: Any = None) -> JoinCheck: + """The checks of a new island's trainer ``nodes`` (module doc). ``taken``: node name or SSH + target -> the fleet island that trains on it.""" + out = JoinCheck() + if len(nodes) != need: + out.refusals.append(f"the island needs {need} trainer node(s); its inventory lists {len(nodes)} " + f"{[n.name for n in nodes]}") + return out + for node in nodes: + owner = (taken or {}).get(node.name) or (taken or {}).get(getattr(node, "host", None) or "") + if owner: + out.refusals.append(f"node {node.name} is island {owner}'s") + if ssh is None: + from .ssh_trainer_island import SshOps # noqa: PLC0415 + + ssh = SshOps() + check_health(nodes, multi=need > 1, ssh=ssh, out=out) + try: + check_fabric(nodes, need, out) + except Exception as error: # noqa: BLE001 - the check that cannot run refuses + out.refusals.append(f"fabric: the placement check could not run ({type(error).__name__}: {error})"[:300]) + check_leases(nodes, lease_store=lease_store, run_id=run_id, out=out) + return out + + +def taken_nodes(doc: Mapping[str, Any], *, other_than: str, fleet_argv: Sequence[str]) -> dict[str, str]: + """Node name and SSH target -> island, for the ``ssh:`` trainer islands of the desired + state other than ``other_than`` (their inventories' trainer nodes).""" + from yeto.launch.pool import desired as dz # noqa: PLC0415 + + from .node_inventory import island_nodes as role_nodes # noqa: PLC0415 + from .node_inventory import load_inventory # noqa: PLC0415 + + out: dict[str, str] = {} + for name, member in dz.trainers(dict(doc)).items(): + if name == other_than or not str(member.get("gpu") or "").startswith("ssh:"): + continue + path = inventory_of([*fleet_argv, *(member.get("argv") or ())]) + if path is None: + continue + try: + nodes = role_nodes(load_inventory(path), "trainer") + except Exception as error: # noqa: BLE001 - its nodes unknown: said, not taken as free + raise ValueError(f"island {name}'s inventory {path} does not read ({error})") from None + for node in nodes: + out.setdefault(node.name, name) + out.setdefault(node.host, name) + return out + + +def check_member(member: Mapping[str, Any], doc: Mapping[str, Any], *, fleet_argv: Sequence[str], run_id: str, + ssh: Any = None, log: Callable[[str], None] | None = None) -> JoinCheck: + """:func:`check` of an added island's trainer member (``yeto fleet island add``).""" + say = log or (lambda m: print(m, file=sys.stderr)) + argv = [*fleet_argv, *(member.get("argv") or ())] + nodes, need, path = island_nodes(argv, str(member["gpu"])) + result = check(nodes, need=need, run_id=run_id, lease_store=lease_store_of(path), + taken=taken_nodes(doc, other_than=str(member["name"]), fleet_argv=fleet_argv), ssh=ssh) + for note in result.notes: + say(f"fleet island: note: island {member['name']}: {note}") + return result diff --git a/yeto/rl/fleet_islands.py b/yeto/rl/fleet_islands.py index e54764c4c..5ff8e92b3 100644 --- a/yeto/rl/fleet_islands.py +++ b/yeto/rl/fleet_islands.py @@ -106,9 +106,11 @@ def next_learner_id(objects: Any, plan: Any, doc: dict[str, Any], name: str | No def compile_island(cfg: dict[str, Any], plan: Any, *, k: int, name: str, gpu: str, usd_per_h: float | None, - samplers: list[Any], island_argv: list[str] | None = None) -> tuple[dict[str, Any], list[dict]]: + samplers: list[Any], island_argv: list[str] | None = None, + inventory: str | None = None) -> tuple[dict[str, Any], list[dict]]: """The trainer member and the sampler pool members of a new island k, compiled as - :func:`yeto.rl.fleet.compile_fleet` compiles island k of the run config.""" + :func:`yeto.rl.fleet.compile_fleet` compiles island k of the run config. ``inventory``: + the node inventory of an ``ssh:`` island (its launch's ``--rl-node-inventory``).""" if not fleet_mod.NAME.fullmatch(str(name)): raise IslandChangeError(f"island name must be a word of letters, digits, '.', '_' or '-' (got {name!r})") where = f"island {name}" @@ -142,6 +144,10 @@ def compile_island(cfg: dict[str, Any], plan: Any, *, k: int, name: str, gpu: st argv = il.island_argv(trainer_argv, island, plan, learners=len(plan.islands), section_argv=il.island_section_argv(cfg, trainer_argv)) argv += il.member_table_flags(k) + if inventory is not None: + if not str(gpu).startswith("ssh:"): + raise IslandChangeError(f"{where}: --inventory is the node inventory of an ssh: island (--gpu {gpu})") + argv += ["--rl-node-inventory", str(inventory)] member = il.trainer_member(island, plan, argv, prefix=f"{il.fleet_prefix(trainer_argv)}-i{k}", fleet_shape=il.fleet_shape(trainer_argv)) return member, members @@ -210,6 +216,19 @@ def move(doc: dict[str, Any], cfg: dict[str, Any], name: str, *, gpu: str, usd_p return member +def join_check(cfg: dict[str, Any], doc: dict[str, Any], member: dict[str, Any], *, ssh: Any = None) -> None: + """An added ``ssh:`` island's nodes (``yeto.launch.island_join``): free in this fleet, + healthy, in one fabric group and not leased to another run; refused naming each problem.""" + from yeto.launch import island_join # noqa: PLC0415 + + fleet_argv = [str(a) for a in cfg["fleet"]["trainer_argv"]] + result = island_join.check_member(member, doc, fleet_argv=fleet_argv, run_id=il.fleet_prefix(fleet_argv), + ssh=ssh) + if not result.ok: + raise IslandChangeError(f"island {member['name']}'s nodes cannot join: " + "; ".join(result.refusals)) + print(f"fleet island: island {member['name']}'s nodes pass the join checks (health, fabric group, lease)") + + # -- the launch's own dry run ------------------------------------------------------------------- def _prepare(args: Any) -> None: @@ -295,6 +314,9 @@ def add_parser(fsub: Any) -> None: a.add_argument("--gpu", required=True, help="its trainer cluster (yeto launch --gpu, one cluster)") a.add_argument("--usd-per-h", type=float, default=None, help="its trainer's price (spend view)") a.add_argument("--samplers", required=True, help="a JSON file: the island's samplers list (pool entries)") + a.add_argument("--inventory", default=None, metavar="PATH", + help="an ssh: island's node inventory (its trainer nodes); they are checked first: free in " + "this fleet, healthy, one fabric group, not leased to another run") a.add_argument("--trainer-arg", action="append", default=None, metavar="ARG", help="its own trainer flag (--rl-release-every / --rl-max-policy-age / --rl-sample-wait-s), " "repeatable: --trainer-arg=--rl-release-every --trainer-arg=2") @@ -331,9 +353,11 @@ def main(args: Any, *, prepare: Callable[[Any], None] | None = None) -> int: k = next_learner_id(objects, plan, doc, args.name) member, pools = compile_island(run.cfg, plan, k=k, name=args.name, gpu=args.gpu, usd_per_h=args.usd_per_h, samplers=samplers, - island_argv=args.trainer_arg) + island_argv=args.trainer_arg, inventory=args.inventory) add(doc, member, pools) launch_member = member + if str(member["gpu"]).startswith("ssh:"): + join_check(run.cfg, current, member) elif args.island_command == "remove": remove(doc, args.name) else: @@ -368,7 +392,7 @@ def main(args: Any, *, prepare: Callable[[Any], None] | None = None) -> int: if claimed != int(launch_member["learner_id"]): # another add claimed it meanwhile: compile again launch_member, pools = compile_island(run.cfg, plan, k=claimed, name=args.name, gpu=args.gpu, usd_per_h=args.usd_per_h, samplers=samplers, - island_argv=args.trainer_arg) + island_argv=args.trainer_arg, inventory=args.inventory) member_now = launch_member def change(fresh: dict[str, Any]) -> None: From 7686feede137fe07302b6733a5ec7e433055274f Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 21:10:27 +0800 Subject: [PATCH 09/13] fleet island add: the join checks over the merged node health and leases - health: the checker built as the island's launch builds it (card count, RDMA fabric), a single-node island judged on its GPU reasons only, a node with node_health off noted and not called - leases: the inventory's lease_store (node_inventory.lease_store_of), and a holder judged by its run: the island's own launch (its member prefix, -m after a move) is its own, any other run or island is refused - tests on the real HealthResult / Checker and on NodeLeases over a directory store; the fabric placement check stays a stand-in until its module merges Co-Authored-By: Claude Opus 5.5 --- docs/OWN_CLUSTERS.md | 4 +- tests/test_island_join.py | 118 ++++++++++++++++++------- tests/test_own_clusters_islands_doc.py | 1 + yeto/launch/island_join.py | 70 +++++++++------ yeto/rl/fleet_islands.py | 4 +- 5 files changed, 131 insertions(+), 66 deletions(-) diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index f8bcc62c3..5dc62bd7d 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -602,9 +602,9 @@ written, and in the dry run too, the command checks the inventory's trainer node |---|---| | Count | The inventory does not list as many trainer nodes as `--gpu` says. | | In this fleet | A node (by name or SSH target) is a trainer node of another `ssh:` island of the fleet. | -| Health | The node health check (one SSH call per node) finds a fault: GPU count or memory, an Xid, uncorrectable ECC, Fabric Manager. A multi-node island also needs the `NCCL_IB_HCA` ports active and at rate. A node that does not answer is refused. A device family without a health check is noted, not refused. | +| Health | The node health check (one SSH call per node, the check the island's launch runs while it trains) finds a fault: GPU count or memory, an Xid, uncorrectable ECC, Fabric Manager. A multi-node island also needs the `NCCL_IB_HCA` ports active and at rate. A node that does not answer is refused. A device family without a health check, or a node with `node_health: off`, is noted, not refused. | | Fabric group | The inventory declares `fabric_group` and no one group holds the island's nodes. An inventory without any `fabric_group` only gets a note. | -| Lease | The inventory's `lease_store` shows a node leased to another run. Without `lease_store` this is not checked, and a note says so. | +| Lease | The inventory's `lease_store` shows a node leased to another run, or to another island of this fleet. A lease of the island's own launch (an earlier launch of the same island) is not a refusal. Without `lease_store` this is not checked, and a note says so. | A refusal exits 2, names every problem, and writes nothing. No learner id is claimed: diff --git a/tests/test_island_join.py b/tests/test_island_join.py index c53761d88..b8d3f4c92 100644 --- a/tests/test_island_join.py +++ b/tests/test_island_join.py @@ -3,40 +3,37 @@ fabric group (fabric_groups.check_placement) and not leased to another run (NodeLeases); any one of them failing refuses ``yeto fleet island add`` with its reason, writing nothing. -The node health checker, the placement check and the leases are stand-ins with the -signatures of the own-cluster contract (``checker_for(family).script(hcas) / .parse(text, -hcas, prev) -> HealthResult``, ``check_placement(nodes, need) -> (ok, message, hint_only)``, -``NodeLeases(store_uri, run_id).holder(node)``).""" +Node health and leases are the real modules (``yeto.hw.node_health``, ``yeto.launch.node_lease``): +most tests answer through a stand-in checker (a real :class:`~yeto.hw.node_health.Checker` whose +script prints the node's name) and stand-in holders in the real holder format, and some use the +real checker of a family without one and real :class:`~yeto.launch.node_lease.NodeLeases` on a +directory store. The fabric placement check (``fabric_groups.check_placement(nodes, need) -> +(ok, message, hint_only)``) is a stand-in until its module is merged.""" from __future__ import annotations import json import subprocess -from dataclasses import dataclass, field import pytest - from test_fleet_island_changes import fleet_store # noqa: F401 - fixture + +from yeto.hw import node_health +from yeto.hw.node_health import HealthResult from yeto.launch import island_join as ij from yeto.launch.learner_ids import claim_key from yeto.launch.node_inventory import load_inventory +from yeto.launch.node_lease import NodeLeases from yeto.rl import fleet_islands GPU = "ssh:2x8xb300@bm" -@dataclass -class HealthResult: # the contract's yeto.hw.node_health.HealthResult - checked: bool - ok_single: bool | None - ok_multi: bool | None - reasons: list[str] = field(default_factory=list) - facts: dict = field(default_factory=dict) - - -class Checker: +class Checker(node_health.Checker): """Answers per node (the script prints the node's name here): ``bad`` nodes fail with - their reason; ``ib_down`` nodes are healthy alone but not for a multi-node island.""" + their (GPU) reason; ``ib_down`` nodes are healthy alone but not for a multi-node island.""" + + family = "cuda" def __init__(self, bad=None, ib_down=(), checked=True): self.bad, self.ib_down, self.checked = dict(bad or {}), set(ib_down), checked @@ -51,10 +48,10 @@ def parse(self, text, hcas, prev): if not self.checked: return HealthResult(False, None, None, ["not checked"]) if name in self.bad: - return HealthResult(True, False, False, [self.bad[name]]) + return HealthResult(True, False, False, [self.bad[name]], {"gpu_reasons": [self.bad[name]]}) if name in self.ib_down: - return HealthResult(True, True, False, ["mlx5_3 DOWN"]) - return HealthResult(True, True, True) + return HealthResult(True, True, False, ["mlx5_3 DOWN"], {"gpu_reasons": [], "ib_reasons": ["mlx5_3 DOWN"]}) + return HealthResult(True, True, True, [], {"gpu_reasons": []}) class Ssh: @@ -70,6 +67,8 @@ def run(self, node, script, *, timeout): class Leases: + """Who holds each node, as NodeLeases.holder answers: a holder id ``/trainer@``.""" + made: list[tuple[str, str]] = [] def __init__(self, store_uri, run_id, holders=None): @@ -77,14 +76,15 @@ def __init__(self, store_uri, run_id, holders=None): self.holders = dict(holders or {}) def holder(self, node): - return self.holders.get(getattr(node, "name", node)) + run = self.holders.get(getattr(node, "name", node)) + return None if run is None else f"{run}/trainer@host-{run}" @pytest.fixture def stand_ins(monkeypatch): """The three checks' modules, as the contract has them; returns their knobs.""" knobs = {"checker": Checker(), "placement": (True, "", False), "holders": {}, "placed": []} - monkeypatch.setattr(ij, "_checker_for", lambda family: knobs["checker"]) + monkeypatch.setattr(ij, "_checker_for", lambda node: knobs["checker"]) def placement(nodes, need): knobs["placed"].append(([n.name for n in nodes], need)) @@ -131,10 +131,34 @@ def test_a_port_down_refuses_a_multi_node_island_only(tmp_path, stand_ins): assert stand_ins["checker"].scripts[-1] == [] # alone: the GPU checks only +def test_a_single_node_island_is_refused_for_its_gpus_only(tmp_path, stand_ins): + class Both(Checker): + def parse(self, text, hcas, prev): + return HealthResult(True, False, False, ["GPU count 7, expected 8", "mlx5_3 DOWN"], + {"gpu_reasons": ["GPU count 7, expected 8"], "ib_reasons": ["mlx5_3 DOWN"]}) + + stand_ins["checker"] = Both() + one = _nodes(tmp_path, names=("b300-4",)) + assert ij.check(one, need=1, run_id="r", ssh=Ssh()).refusals == [ + "node b300-4 is not healthy: GPU count 7, expected 8"] + assert ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()).refusals[0] == ( + "node b300-4 is not healthy: GPU count 7, expected 8; mlx5_3 DOWN") + + +def test_a_node_with_its_health_check_off_is_noted_and_not_called(tmp_path, stand_ins): + import dataclasses + + stand_ins["checker"] = Checker(bad={"b300-4": "Xid 79"}) + first, second = _nodes(tmp_path) + ssh = Ssh() + out = ij.check([dataclasses.replace(first, node_health="off"), second], need=2, run_id="r", ssh=ssh) + assert out.ok and ssh.calls == ["b300-5"] + assert "node b300-4: node_health off in the inventory: its health is not checked" in out.notes + def test_a_node_that_does_not_answer_is_refused(tmp_path, stand_ins): out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh(unreachable={"b300-4"})) - assert out.refusals == ["node b300-4: its health check did not answer (ssh exit 255: ssh: connect to host: " - "timed out)"] + assert out.refusals == [("node b300-4: its health check did not answer (ssh exit 255: ssh: connect to host: " + "timed out)")] def test_a_family_without_a_checker_is_noted_not_refused(tmp_path, stand_ins): @@ -144,11 +168,11 @@ def test_a_family_without_a_checker_is_noted_not_refused(tmp_path, stand_ins): def test_nodes_across_fabric_groups_refuse_the_island(tmp_path, stand_ins): - stand_ins["placement"] = (False, "the island needs 2 healthy nodes of one fabric group; group a has only 1, " - "group b has only 1", False) + stand_ins["placement"] = (False, ("the island needs 2 healthy nodes of one fabric group; group a has only 1, " + "group b has only 1"), False) out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) - assert out.refusals == ["fabric: the island needs 2 healthy nodes of one fabric group; group a has only 1, " - "group b has only 1"] + assert out.refusals == [("fabric: the island needs 2 healthy nodes of one fabric group; group a has only 1, " + "group b has only 1")] def test_an_inventory_without_groups_is_only_a_note(tmp_path, stand_ins): @@ -157,14 +181,40 @@ def test_an_inventory_without_groups_is_only_a_note(tmp_path, stand_ins): assert out.ok and out.notes[0].startswith("fabric: no fabric_group") -def test_a_node_leased_to_another_run_is_refused_and_this_run_s_own_is_free(tmp_path, stand_ins): +def test_a_node_leased_to_another_run_is_refused_and_this_island_s_own_is_free(tmp_path, stand_ins): stand_ins["holders"] = {"b300-4": "other-run", "b300-5": "r"} out = ij.check(_nodes(tmp_path), need=2, run_id="r", lease_store="s3://b/leases", ssh=Ssh()) assert out.refusals == ["node b300-4 is leased to run other-run"] + stand_ins["holders"] = {"b300-4": "r-m1", "b300-5": "r-i0"} # its own moved launch; another island + out = ij.check(_nodes(tmp_path), need=2, run_id="r", lease_store="s3://b/leases", ssh=Ssh()) + assert out.refusals == ["node b300-5 is leased to run r-i0"] out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) # no lease_store: noted assert out.ok and any("no lease_store" in n for n in out.notes) +def test_the_real_leases_refuse_a_node_another_run_holds(tmp_path): + """NodeLeases itself on a directory lease store: another run's live lease refuses the node, + the island's own launch's lease does not.""" + store = str(tmp_path / "leases") + nodes = _nodes(tmp_path) + assert NodeLeases(store, "other-run/trainer", identity="a").acquire(nodes[0]).ok + assert NodeLeases(store, "r-i2/trainer", identity="b").acquire(nodes[1]).ok + out = ij.JoinCheck() + ij.check_leases(nodes, lease_store=store, run_id="r-i2", out=out) + assert out.refusals == ["node b300-4 is leased to run other-run"] + + +def test_the_real_checker_of_a_family_without_one_runs_nothing(tmp_path): + import dataclasses + + (node,) = _nodes(tmp_path, names=("b300-4",)) + checker = ij._checker_for(node) # cuda: the real checker, built with the node's card count + assert checker.enabled and checker.expect_gpus == 8 + other = dataclasses.replace(node, device_family="no-such-family") + ssh, out = Ssh(), ij.JoinCheck() + ij.check_health([other], multi=False, ssh=ssh, out=out) + assert ssh.calls == [] and out.ok and out.notes == ["node b300-4: no health check for device family no-such-family"] + def test_a_node_of_another_island_or_the_wrong_count_is_refused(tmp_path, stand_ins): nodes = _nodes(tmp_path) out = ij.check(nodes, need=2, run_id="r", taken={"ops@b300-5.example": "sglang"}, ssh=Ssh()) @@ -193,7 +243,7 @@ def _add(run_cli, samplers, inventory, *extra): @pytest.mark.parametrize("problem", ["health", "fabric", "lease"]) def test_add_refuses_an_ssh_island_failing_one_check_and_writes_nothing(fleet_store, stand_ins, tmp_path, # noqa: F811 monkeypatch, capsys, problem): - cfg, objects, store, run_cli, samplers = fleet_store + _cfg, objects, store, run_cli, samplers = fleet_store inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", Ssh) if problem == "health": @@ -203,7 +253,7 @@ def test_add_refuses_an_ssh_island_failing_one_check_and_writes_nothing(fleet_st stand_ins["placement"] = (False, "group a has only 1, group b has only 1", False) why = "fabric: group a has only 1, group b has only 1" else: - monkeypatch.setattr(ij, "lease_store_of", lambda path: "s3://b/leases") + inventory.write_text("lease_store: s3://b/leases\n" + inventory.read_text()) stand_ins["holders"] = {"b300-5": "another-run"} why = "node b300-5 is leased to run another-run" monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda *a, **kw: pytest.fail("checked before the dry run")) @@ -215,7 +265,7 @@ def test_add_refuses_an_ssh_island_failing_one_check_and_writes_nothing(fleet_st def test_add_takes_an_ssh_island_whose_nodes_pass(fleet_store, stand_ins, tmp_path, monkeypatch, capsys): # noqa: F811 - cfg, objects, store, run_cli, samplers = fleet_store + _cfg, objects, store, run_cli, samplers = fleet_store inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", Ssh) dry_runs = [] @@ -232,7 +282,7 @@ def test_add_takes_an_ssh_island_whose_nodes_pass(fleet_store, stand_ins, tmp_pa def test_a_second_ssh_island_on_the_nodes_of_the_first_is_refused(fleet_store, stand_ins, tmp_path, # noqa: F811 monkeypatch, capsys): - cfg, objects, store, run_cli, samplers = fleet_store + cfg, _objects, _store, run_cli, samplers = fleet_store monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", Ssh) monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda member, **kw: None) monkeypatch.setattr(fleet_islands, "session_check", lambda *a, **kw: None) @@ -246,7 +296,7 @@ def test_a_second_ssh_island_on_the_nodes_of_the_first_is_refused(fleet_store, s def test_an_inventory_is_for_an_ssh_island_only(fleet_store, tmp_path, capsys): # noqa: F811 - cfg, objects, store, run_cli, samplers = fleet_store + _cfg, _objects, _store, run_cli, samplers = fleet_store inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) assert run_cli("add", "--name", "north", "--gpu", "modal:1x2xh100", "--usd-per-h", "8", "--samplers", str(samplers), "--inventory", str(inventory)) == 2 diff --git a/tests/test_own_clusters_islands_doc.py b/tests/test_own_clusters_islands_doc.py index 5d69f7fb5..4d777c839 100644 --- a/tests/test_own_clusters_islands_doc.py +++ b/tests/test_own_clusters_islands_doc.py @@ -11,6 +11,7 @@ from test_fleet_island_changes import fleet_store # noqa: F401 - fixture from test_island_join import Leases, Ssh, _inventory, stand_ins # noqa: F401 - fixture + from yeto.launch import island_join as ij from yeto.launch import island_straggler as st from yeto.rl import fleet_islands diff --git a/yeto/launch/island_join.py b/yeto/launch/island_join.py index bc1ac7118..2c87fa6b3 100644 --- a/yeto/launch/island_join.py +++ b/yeto/launch/island_join.py @@ -7,16 +7,18 @@ * be as many as the island's ``--gpu`` says, with no node another ``ssh:`` island of the fleet already trains on (same name or SSH target); -* be healthy: the node health checker of their device family (``yeto.hw.node_health``), - one SSH call per node; a multi-node island also needs its ``NCCL_IB_HCA`` ports up at - rate. A device family without a checker is noted, not refused; a node that does not - answer is refused; +* be healthy: the node health checker of their device family (``yeto.hw.node_health``, + built as the island's launch builds it), one SSH call per node; a multi-node island also + needs its ``NCCL_IB_HCA`` ports up at rate, a single-node one only its GPUs. A device + family without a checker, or a node with ``node_health: off``, is noted, not refused; a + node that does not answer is refused; * fit one fabric group (``yeto.launch.fabric_groups.check_placement``): an inventory that declares groups refuses a multi-node island across groups; one without any group only notes it; * be free in the inventory's ``lease_store`` (``yeto.launch.node_lease.NodeLeases``): a node - another run holds is refused, naming that run. Without a ``lease_store`` nothing is - checked (noted once). + another run holds (another island of the fleet included) is refused, naming that run; a + lease of the island's own launch (its member prefix, ``-m`` after a move) is its own. + Without a ``lease_store`` nothing is checked (noted once). :func:`check` returns what was refused and noted; ``yeto fleet island add`` prints the notes and refuses the change (exit 2, nothing written) on any refusal, naming each. @@ -27,7 +29,6 @@ import sys from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass, field -from pathlib import Path from typing import Any INVENTORY_FLAG = "--rl-node-inventory" @@ -55,16 +56,7 @@ def inventory_of(argv: Sequence[str]) -> str | None: return found -def lease_store_of(path: str | Path) -> str | None: - """The inventory's top-level ``lease_store`` (None when it declares none).""" - import yaml # noqa: PLC0415 - as node_inventory - - doc = yaml.safe_load(Path(path).expanduser().read_text()) - value = doc.get("lease_store") if isinstance(doc, dict) else None - return str(value) if value else None - - -def island_nodes(argv: Sequence[str], gpu: str) -> tuple[list[Any], int, str | None]: +def island_nodes(argv: Sequence[str], gpu: str) -> tuple[Any, int, str | None]: """``(trainer nodes, nodes the island needs, inventory path)`` of an ``ssh:`` island's launch argv; raises ValueError naming what is wrong.""" from ..gpu_spec import parse_gpu_spec # noqa: PLC0415 @@ -83,10 +75,15 @@ def island_nodes(argv: Sequence[str], gpu: str) -> tuple[list[Any], int, str | N # -- the three checks (their modules: yeto.hw.node_health, fabric_groups, node_lease) ------------ -def _checker_for(family: str) -> Any: +def _checker_for(node: Any) -> Any: + """The node's health checker, built as the island's own launch builds it (ssh_resident).""" from yeto.hw.node_health import checker_for # noqa: PLC0415 - return checker_for(family) + from .ssh_resident import RDMA_FABRICS # noqa: PLC0415 + + fabric = getattr(node, "fabric", None) + return checker_for(node.device_family, expect_gpus=getattr(node, "cards_per_node", None), + fabric=fabric if fabric in RDMA_FABRICS else None) def _check_placement(nodes: Sequence[Any], need: int) -> tuple[bool, str, bool]: @@ -98,18 +95,31 @@ def _check_placement(nodes: Sequence[Any], need: int) -> tuple[bool, str, bool]: def _node_leases(store_uri: str, run_id: str) -> Any: from .node_lease import NodeLeases # noqa: PLC0415 - return NodeLeases(store_uri, run_id) + return NodeLeases(store_uri, f"{run_id}/trainer") # read only: who holds each node def _hcas(node: Any) -> list[str]: - spec = str((getattr(node, "env", None) or {}).get("NCCL_IB_HCA") or "") - return [part for part in spec.split(",") if part] + from yeto.hw.node_health import hcas_of # noqa: PLC0415 + + return list(hcas_of((getattr(node, "env", None) or {}).get("NCCL_IB_HCA"))) + + +def _lease_run(holder: str) -> str: + from .node_lease import run_of # noqa: PLC0415 + + return run_of(holder) or str(holder) def check_health(nodes: Sequence[Any], *, multi: bool, ssh: Any, out: JoinCheck) -> None: for node in nodes: + if getattr(node, "node_health", None) == "off": + out.notes.append(f"node {node.name}: node_health off in the inventory: its health is not checked") + continue try: - checker = _checker_for(node.device_family) + checker = _checker_for(node) + if not getattr(checker, "enabled", True): + out.notes.append(f"node {node.name}: no health check for device family {node.device_family}") + continue hcas = _hcas(node) if multi else [] done = ssh.run(node, checker.script(hcas), timeout=HEALTH_TIMEOUT_S) except Exception as error: # noqa: BLE001 - named in the refusal @@ -125,9 +135,9 @@ def check_health(nodes: Sequence[Any], *, multi: bool, ssh: Any, out: JoinCheck) if not result.checked: out.notes.append(f"node {node.name}: no health check for device family {node.device_family}") continue - ok = result.ok_multi if multi else result.ok_single + ok, reasons = result.ok(multi), result.job_reasons(multi) # a single-node island: its GPU reasons if ok is False: - out.refusals.append(f"node {node.name} is not healthy: {'; '.join(result.reasons) or 'no reason given'}") + out.refusals.append(f"node {node.name} is not healthy: {'; '.join(reasons) or 'no reason given'}") elif ok is None: out.notes.append(f"node {node.name}: its health could not be judged ({'; '.join(result.reasons)})") @@ -155,8 +165,10 @@ def check_leases(nodes: Sequence[Any], *, lease_store: str | None, run_id: str, except Exception as error: # noqa: BLE001 - unknown is not free out.refusals.append(f"node {node.name}: its lease does not read ({type(error).__name__}: {error})"[:300]) continue - if holder is not None and holder != run_id: - out.refusals.append(f"node {node.name} is leased to run {holder}") + run = None if holder is None else _lease_run(holder) + # the island's own launch leases as [-m]/trainer: a lease of it is its own + if run is not None and run != run_id and not run.startswith(f"{run_id}-m"): + out.refusals.append(f"node {node.name} is leased to run {run}") def check(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str | None = None, @@ -215,8 +227,10 @@ def check_member(member: Mapping[str, Any], doc: Mapping[str, Any], *, fleet_arg """:func:`check` of an added island's trainer member (``yeto fleet island add``).""" say = log or (lambda m: print(m, file=sys.stderr)) argv = [*fleet_argv, *(member.get("argv") or ())] + from .node_inventory import lease_store_of, load_inventory # noqa: PLC0415 + nodes, need, path = island_nodes(argv, str(member["gpu"])) - result = check(nodes, need=need, run_id=run_id, lease_store=lease_store_of(path), + result = check(nodes, need=need, run_id=run_id, lease_store=lease_store_of(load_inventory(path)), taken=taken_nodes(doc, other_than=str(member["name"]), fleet_argv=fleet_argv), ssh=ssh) for note in result.notes: say(f"fleet island: note: island {member['name']}: {note}") diff --git a/yeto/rl/fleet_islands.py b/yeto/rl/fleet_islands.py index 5ff8e92b3..d848c3287 100644 --- a/yeto/rl/fleet_islands.py +++ b/yeto/rl/fleet_islands.py @@ -222,8 +222,8 @@ def join_check(cfg: dict[str, Any], doc: dict[str, Any], member: dict[str, Any], from yeto.launch import island_join # noqa: PLC0415 fleet_argv = [str(a) for a in cfg["fleet"]["trainer_argv"]] - result = island_join.check_member(member, doc, fleet_argv=fleet_argv, run_id=il.fleet_prefix(fleet_argv), - ssh=ssh) + # a node leased by the island's own launch (its member prefix) is its own + result = island_join.check_member(member, doc, fleet_argv=fleet_argv, run_id=str(member["prefix"]), ssh=ssh) if not result.ok: raise IslandChangeError(f"island {member['name']}'s nodes cannot join: " + "; ".join(result.refusals)) print(f"fleet island: island {member['name']}'s nodes pass the join checks (health, fabric group, lease)") From 1fe8a6086ad40aca33b1afa5c4b16da5f896adb7 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 21:59:14 +0800 Subject: [PATCH 10/13] fleet island add: the fabric check over the merged fabric_groups check_placement gets the island's whole inventory, so an inventory that declares fabric groups refuses an island whose nodes carry none or two. Co-Authored-By: Claude Opus 5.5 --- tests/test_island_join.py | 33 +++++++++++++++++++++++++++------ yeto/launch/island_join.py | 23 ++++++++++++++--------- 2 files changed, 41 insertions(+), 15 deletions(-) diff --git a/tests/test_island_join.py b/tests/test_island_join.py index b8d3f4c92..6efc187d2 100644 --- a/tests/test_island_join.py +++ b/tests/test_island_join.py @@ -7,8 +7,8 @@ most tests answer through a stand-in checker (a real :class:`~yeto.hw.node_health.Checker` whose script prints the node's name) and stand-in holders in the real holder format, and some use the real checker of a family without one and real :class:`~yeto.launch.node_lease.NodeLeases` on a -directory store. The fabric placement check (``fabric_groups.check_placement(nodes, need) -> -(ok, message, hint_only)``) is a stand-in until its module is merged.""" +directory store. The fabric placement check is a stand-in knob in most tests and the real +``fabric_groups.check_placement`` in one.""" from __future__ import annotations @@ -83,11 +83,12 @@ def holder(self, node): @pytest.fixture def stand_ins(monkeypatch): """The three checks' modules, as the contract has them; returns their knobs.""" - knobs = {"checker": Checker(), "placement": (True, "", False), "holders": {}, "placed": []} + knobs = {"checker": Checker(), "placement": (True, "", False), "holders": {}, "placed": [], "inventories": []} monkeypatch.setattr(ij, "_checker_for", lambda node: knobs["checker"]) - def placement(nodes, need): + def placement(nodes, need, inventory): knobs["placed"].append(([n.name for n in nodes], need)) + knobs["inventories"].append(None if inventory is None else [n.name for n in inventory]) return knobs["placement"] monkeypatch.setattr(ij, "_check_placement", placement) @@ -95,12 +96,14 @@ def placement(nodes, need): return knobs -def _inventory(path, names, *, env=None): +def _inventory(path, names, *, env=None, groups=None): path.write_text("nodes:\n" + "".join( f" - {{name: {name}, host: ops@{name}.example, address: 198.51.100.{10 + i}, interface: bond0, " "device_family: cuda, cpu_arch: x86_64, card: B300, cards_per_node: 8, hbm_gib: 288, " "host_memory_gib: 2048, fabric: ib, runtime: docker, docker_args: [--gpus, all]" - + (f", env: {{NCCL_IB_HCA: '{env}'}}" if env else "") + "}\n" for i, name in enumerate(names))) + + (f", env: {{NCCL_IB_HCA: '{env}'}}" if env else "") + + (f", fabric_group: {groups[name]}" if groups and name in groups else "") + "}\n" + for i, name in enumerate(names))) return path @@ -175,6 +178,23 @@ def test_nodes_across_fabric_groups_refuse_the_island(tmp_path, stand_ins): "group b has only 1")] +def test_the_real_placement_check_refuses_nodes_of_two_fabric_groups(tmp_path, monkeypatch): + """fabric_groups.check_placement itself, on the island's nodes and its whole inventory.""" + monkeypatch.setattr(ij, "_checker_for", lambda node: Checker()) + + def run(groups, names=("b300-4", "b300-5")): + inventory = load_inventory(_inventory(tmp_path / "g.yaml", ["b300-3", *names], groups=groups)) + nodes = [n for n in inventory if n.name in names] + return ij.check(nodes, need=2, run_id="r", ssh=Ssh(), inventory=inventory) + + split = run({"b300-3": "a", "b300-4": "a", "b300-5": "b"}) + assert len(split.refusals) == 1 and split.refusals[0].startswith("fabric: ") + assert run({"b300-3": "a", "b300-4": "b", "b300-5": "b"}).ok + plain = run(None) # no group anywhere: placed as before, with the hint as a note + assert plain.ok and any(n.startswith("fabric: ") and "fabric_group" in n for n in plain.notes) + other = run({"b300-3": "a"}) # groups in the inventory, none on the island's nodes + assert not other.ok and other.refusals[0].startswith("fabric: ") + def test_an_inventory_without_groups_is_only_a_note(tmp_path, stand_ins): stand_ins["placement"] = (True, "no fabric_group in the inventory: run yeto cluster probe --write", True) out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) @@ -274,6 +294,7 @@ def test_add_takes_an_ssh_island_whose_nodes_pass(fleet_store, stand_ins, tmp_pa assert _add(run_cli, samplers, inventory) == 0 out = capsys.readouterr() assert "island north's nodes pass the join checks" in out.out + assert stand_ins["inventories"] == [["b300-4", "b300-5"]] # placed against its whole inventory assert "note: island north: no lease_store" in out.err (member,) = dry_runs assert member["argv"][-2:] == ["--rl-node-inventory", str(inventory)] and member["gpu"] == GPU diff --git a/yeto/launch/island_join.py b/yeto/launch/island_join.py index 2c87fa6b3..4b8a5694b 100644 --- a/yeto/launch/island_join.py +++ b/yeto/launch/island_join.py @@ -86,10 +86,10 @@ def _checker_for(node: Any) -> Any: fabric=fabric if fabric in RDMA_FABRICS else None) -def _check_placement(nodes: Sequence[Any], need: int) -> tuple[bool, str, bool]: +def _check_placement(nodes: Sequence[Any], need: int, inventory: Sequence[Any] | None) -> tuple[bool, str, bool]: from .fabric_groups import check_placement # noqa: PLC0415 - return check_placement(nodes, need) + return check_placement(nodes, need, inventory=inventory) def _node_leases(store_uri: str, run_id: str) -> Any: @@ -142,8 +142,9 @@ def check_health(nodes: Sequence[Any], *, multi: bool, ssh: Any, out: JoinCheck) out.notes.append(f"node {node.name}: its health could not be judged ({'; '.join(result.reasons)})") -def check_fabric(nodes: Sequence[Any], need: int, out: JoinCheck) -> None: - ok, message, hint_only = _check_placement(nodes, need) +def check_fabric(nodes: Sequence[Any], need: int, out: JoinCheck, *, inventory: Sequence[Any] | None = None) -> None: + """``inventory``: the whole inventory (whether it declares fabric groups at all).""" + ok, message, hint_only = _check_placement(nodes, need, inventory) if not ok and not hint_only: out.refusals.append(f"fabric: {message}") elif message and (hint_only or not ok): @@ -172,9 +173,11 @@ def check_leases(nodes: Sequence[Any], *, lease_store: str | None, run_id: str, def check(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str | None = None, - taken: Mapping[str, str] | None = None, ssh: Any = None) -> JoinCheck: + taken: Mapping[str, str] | None = None, ssh: Any = None, + inventory: Sequence[Any] | None = None) -> JoinCheck: """The checks of a new island's trainer ``nodes`` (module doc). ``taken``: node name or SSH - target -> the fleet island that trains on it.""" + target -> the fleet island that trains on it; ``inventory``: the whole inventory (default + ``nodes``).""" out = JoinCheck() if len(nodes) != need: out.refusals.append(f"the island needs {need} trainer node(s); its inventory lists {len(nodes)} " @@ -190,7 +193,7 @@ def check(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str | No ssh = SshOps() check_health(nodes, multi=need > 1, ssh=ssh, out=out) try: - check_fabric(nodes, need, out) + check_fabric(nodes, need, out, inventory=inventory) except Exception as error: # noqa: BLE001 - the check that cannot run refuses out.refusals.append(f"fabric: the placement check could not run ({type(error).__name__}: {error})"[:300]) check_leases(nodes, lease_store=lease_store, run_id=run_id, out=out) @@ -230,8 +233,10 @@ def check_member(member: Mapping[str, Any], doc: Mapping[str, Any], *, fleet_arg from .node_inventory import lease_store_of, load_inventory # noqa: PLC0415 nodes, need, path = island_nodes(argv, str(member["gpu"])) - result = check(nodes, need=need, run_id=run_id, lease_store=lease_store_of(load_inventory(path)), - taken=taken_nodes(doc, other_than=str(member["name"]), fleet_argv=fleet_argv), ssh=ssh) + inventory = load_inventory(path) + result = check(nodes, need=need, run_id=run_id, lease_store=lease_store_of(inventory), + taken=taken_nodes(doc, other_than=str(member["name"]), fleet_argv=fleet_argv), ssh=ssh, + inventory=inventory) for note in result.notes: say(f"fleet island: note: island {member['name']}: {note}") return result From bc5c1e848029210d494f693692a42a1c4b0b302c Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 23:27:05 +0800 Subject: [PATCH 11/13] fleet island add/move: join checks on absolute health rules, leased pick, rechecked at the write - health: the real checker's read failures refuse (result.reasons), --force makes them a WARNING; a first check judges absolute faults (any hardware Xid of this boot, volatile uncorrectable ECC > 0, NVSwitch with the fabric manager not active); job ports at the inventory's new min_ib_gbps, else at half the island's fastest; HCAs from {node env, island env} - with lease_store: more candidates than needed, held and unhealthy nodes left out, pick_placement chooses; another island is judged by its lease holder; the dry run prints the chosen nodes - own lease: (-m)?/trainer by fullmatch; overlap by name, SSH target without user@ and address, case-insensitive - the inventory path is stored absolute; the write rechecks on the fresh desired state and under a newly claimed prefix - yeto fleet island move --gpu ssh: runs the same checks (--inventory, --force) Co-Authored-By: Claude Opus 5.5 --- docs/NODE_RUNTIME.md | 6 +- docs/OWN_CLUSTERS.md | 30 +- tests/test_island_join.py | 636 +++++++++++++++++-------- tests/test_node_health_wiring.py | 11 + tests/test_own_clusters_islands_doc.py | 36 +- yeto/launch/island_join.py | 491 +++++++++++++++---- yeto/launch/node_inventory.py | 11 +- yeto/launch/ssh_resident.py | 1 + yeto/rl/fleet_islands.py | 82 +++- 9 files changed, 974 insertions(+), 330 deletions(-) diff --git a/docs/NODE_RUNTIME.md b/docs/NODE_RUNTIME.md index fba8f595d..860aa8ace 100644 --- a/docs/NODE_RUNTIME.md +++ b/docs/NODE_RUNTIME.md @@ -278,10 +278,12 @@ One shell call reads, in this order: | ECC | the same query | the volatile uncorrectable ECC count grew since the previous check (a count that went down is the new baseline) | | NVLink fabric | the `Fabric` blocks of `nvidia-smi -q` | a GPU that has a fabric state is not `Completed/Success` (a PCIe card's `N/A` passes) | | fabric manager | `systemctl is-active nvidia-fabricmanager` | it was active and is now `inactive` or `failed` (a node without NVSwitch, never active, passes) | -| IB / RoCE ports | `ibstat` (`ibv_devinfo -v` only when ibstat fails) | a port named by `NCCL_IB_HCA` is missing, not `Active`, or slower than at the first check | +| IB / RoCE ports | `ibstat` (`ibv_devinfo -v` only when ibstat fails) | a port named by `NCCL_IB_HCA` is missing, not `Active`, or slower than the node's `min_ib_gbps` in the inventory (without it: than at the first check) | The XIDs and the ECC count only count from the second check on. What the kernel log -holds at the first check is history: the preflight judged the node then. +holds at the first check is history: the preflight judged the node then. The nodes of +an island added at run time are judged on their first check by absolute rules instead +([OWN_CLUSTERS.md](OWN_CLUSTERS.md), "Adding an island"). A kernel log without timestamps (dmesg's default has them) is followed by its last line, how often that line ends the log, and the line before it, so lines that rotate diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 5dc62bd7d..0347debe9 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -595,23 +595,39 @@ yeto fleet island add --config run.json --name north --gpu ssh:2x8xb300@bm --usd --samplers north.samplers.json --inventory north.inventory.yaml ``` -The island's launch gets `--rl-node-inventory north.inventory.yaml`. Before anything is -written, and in the dry run too, the command checks the inventory's trainer nodes: +The island's launch gets `--rl-node-inventory` with the inventory's absolute path. Before +anything is written, and in the dry run too, the command checks the inventory's trainer +nodes and prints the nodes the island takes: | Check | Refused when | |---|---| -| Count | The inventory does not list as many trainer nodes as `--gpu` says. | -| In this fleet | A node (by name or SSH target) is a trainer node of another `ssh:` island of the fleet. | -| Health | The node health check (one SSH call per node, the check the island's launch runs while it trains) finds a fault: GPU count or memory, an Xid, uncorrectable ECC, Fabric Manager. A multi-node island also needs the `NCCL_IB_HCA` ports active and at rate. A node that does not answer is refused. A device family without a health check, or a node with `node_health: off`, is noted, not refused. | +| Count | Without `lease_store`: the inventory does not list as many trainer nodes as `--gpu` says. With `lease_store` it may list more, as for a launch: the island takes as many as it needs of the free, healthy ones (below). | +| In this fleet | Without `lease_store`: a node is a trainer node of another `ssh:` island of the fleet: the same name, or the same machine (its SSH target without `user@`, or its `address`, in any case). With `lease_store`: another island's launch holds the node's lease. | +| Health | One SSH call per node runs the node health check of its device family, the check the island's launch runs while it trains. A node joining has no earlier check to compare with, so it is judged on absolute rules: a hardware Xid in the kernel log of this boot, a volatile uncorrectable ECC count above 0, NVSwitch GPUs whose `nvidia-fabricmanager` is not `active`, fewer GPUs than `cards_per_node`, an NVLink fabric not `Completed`. A multi-node island also needs every `NCCL_IB_HCA` port `Active` (the island's own `--island-env` value wins over the node's `env`), at no less than the node's `min_ib_gbps` when the inventory sets it, else at no less than half the fastest of these ports on the island's nodes. A check that does not read (no answer, `nvidia-smi` timed out, a check still stuck on the node, an output cut off, the IB tools unread) is refused; with `--force` it is a WARNING and the node joins. A node found unhealthy is refused with `--force` too. A device family without a health check, or a node with `node_health: off`, is a note. | | Fabric group | The inventory declares `fabric_group` and no one group holds the island's nodes. An inventory without any `fabric_group` only gets a note. | -| Lease | The inventory's `lease_store` shows a node leased to another run, or to another island of this fleet. A lease of the island's own launch (an earlier launch of the same island) is not a refusal. Without `lease_store` this is not checked, and a note says so. | +| Lease | The inventory's `lease_store` shows a node leased to another run, or to another island of this fleet. A lease of the island's own launch (`/trainer`, or `-m/trainer` after a move) is not a refusal. A lease that does not read is refused. Without `lease_store` this is not checked, and a note says so. | + +With `lease_store`, the nodes held by another run or island and the unhealthy ones are +left out, and the island's nodes are placed in the rest as its launch places them (one +fabric group in a grouped inventory, else in the inventory's order). When too few are +left, the refusal names each node left out and why. The launch itself picks by leases +only, so a pick of the launch that would take a node found unhealthy is refused too: +take that node out of the trainer nodes (`roles`) or clear its fault. A refusal exits 2, names every problem, and writes nothing. No learner id is claimed: ```text -fleet island: refused: island north's nodes cannot join: node b300-5 is not healthy: Xid 79 since the last check; node b300-4 is leased to run other-run +fleet island: refused: island north's nodes cannot join: node b300-4 is leased to run other-run; node b300-5 is not healthy: GPU 5 XID 79; 0 of 2 trainer node(s) are free and healthy, 2 needed ``` +The checks run again when the island is written, on the desired state then: another +island added since the dry run, or one that took the learner id this add checked under, +refuses the write (exit 3), naming its nodes. + +`yeto fleet island move --gpu ssh:...` runs the same checks on the nodes the island moves +onto (`--inventory` replaces the island's inventory; without it the island keeps its own), +with the same `--force`. + Once the island is written, the trainer worker starts its launch. The island joins the running syncer session, catches up to the newest merged weights, and then answers rounds like the other islands. The other islands' processes keep running; they are not restarted. diff --git a/tests/test_island_join.py b/tests/test_island_join.py index 6efc187d2..3b6ea4bbc 100644 --- a/tests/test_island_join.py +++ b/tests/test_island_join.py @@ -1,25 +1,27 @@ -"""The join checks of an ssh: trainer island added at run time (own-cluster-fleet-stability -9.3): its inventory's trainer nodes must be free in this fleet, healthy (node health), in one -fabric group (fabric_groups.check_placement) and not leased to another run (NodeLeases); -any one of them failing refuses ``yeto fleet island add`` with its reason, writing nothing. - -Node health and leases are the real modules (``yeto.hw.node_health``, ``yeto.launch.node_lease``): -most tests answer through a stand-in checker (a real :class:`~yeto.hw.node_health.Checker` whose -script prints the node's name) and stand-in holders in the real holder format, and some use the -real checker of a family without one and real :class:`~yeto.launch.node_lease.NodeLeases` on a -directory store. The fabric placement check is a stand-in knob in most tests and the real -``fabric_groups.check_placement`` in one.""" +"""The join checks of an ssh: trainer island added (or moved) at run time +(own-cluster-fleet-stability 9.3): its inventory's trainer nodes must be free in this fleet, +healthy (node health, absolute rules: a node's first check), in one fabric group and not +leased to another run; any one of them failing refuses ``yeto fleet island add`` / ``move`` +with its reason, writing nothing. + +The checks run on the real modules: the real :class:`~yeto.hw.node_health.CudaChecker` over +the recorded tool outputs of the node health tests (``node_text``: what its script prints on +an 8 x B300 IB node), the real :class:`~yeto.hw.node_health.NullChecker`, the real +``fabric_groups`` placement and real :class:`~yeto.launch.node_lease.NodeLeases` on a directory +lease store. Only SSH is a stand-in (it answers each node with its recorded output).""" from __future__ import annotations +import dataclasses import json import subprocess import pytest +from test_cluster_preflight import ibstat_text # tests/ is on sys.path from test_fleet_island_changes import fleet_store # noqa: F401 - fixture +from test_node_health import FABRIC_OK, gpus_text, node_text, xid_line, xid_text from yeto.hw import node_health -from yeto.hw.node_health import HealthResult from yeto.launch import island_join as ij from yeto.launch.learner_ids import claim_key from yeto.launch.node_inventory import load_inventory @@ -27,82 +29,50 @@ from yeto.rl import fleet_islands GPU = "ssh:2x8xb300@bm" - - -class Checker(node_health.Checker): - """Answers per node (the script prints the node's name here): ``bad`` nodes fail with - their (GPU) reason; ``ib_down`` nodes are healthy alone but not for a multi-node island.""" - - family = "cuda" - - def __init__(self, bad=None, ib_down=(), checked=True): - self.bad, self.ib_down, self.checked = dict(bad or {}), set(ib_down), checked - self.scripts: list[list[str]] = [] - - def script(self, hcas): - self.scripts.append(list(hcas)) - return "health-probe" - - def parse(self, text, hcas, prev): - name = text.strip() - if not self.checked: - return HealthResult(False, None, None, ["not checked"]) - if name in self.bad: - return HealthResult(True, False, False, [self.bad[name]], {"gpu_reasons": [self.bad[name]]}) - if name in self.ib_down: - return HealthResult(True, True, False, ["mlx5_3 DOWN"], {"gpu_reasons": [], "ib_reasons": ["mlx5_3 DOWN"]}) - return HealthResult(True, True, True, [], {"gpu_reasons": []}) +HCA = "=mlx5_0,mlx5_1,mlx5_2,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_7" +XID_79 = node_text(xid=(0, xid_text(xid_line(812.5, 5, 79)))) # in the kernel log of this boot already +ECC_5 = node_text(gpus=(0, gpus_text(ecc={2: 5}))) +FM_DOWN = node_text(fabricmanager=(3, "inactive")) # NVSwitch GPUs (fabric Completed), its fabric manager down +PCIE = node_text(fabricmanager=(3, "inactive"), fabric=(0, " Fabric\n State : N/A\n Status : N/A\n" * 8)) +SLOW = node_text(ibstat=(0, ibstat_text(rate=100))) +PORT_DOWN = node_text(ibstat=(0, ibstat_text(down=(3,)))) +NVSMI_TIMEOUT = node_text(gpus=(124, "")) +BUSY = f"{node_health.BUSY_MARK} 4242\n" +CUT = node_text()[:node_text().index("@@yeto-section ibstat")] +IB_UNREAD = node_text(ibstat=(1, "ibstat: not found"), ibv_devinfo=(1, "ibv_devinfo: not found")) class Ssh: - def __init__(self, unreachable=()): - self.unreachable = set(unreachable) + """Answers each node's check with its recorded output (default: a healthy node).""" + + def __init__(self, out=None, unreachable=()): + self.out, self.unreachable = dict(out or {}), set(unreachable) self.calls: list[str] = [] + self.timeouts: list[float | None] = [] - def run(self, node, script, *, timeout): + def run(self, node, script, *, timeout=None): self.calls.append(node.name) + self.timeouts.append(timeout) if node.name in self.unreachable: return subprocess.CompletedProcess([], 255, stdout="", stderr="ssh: connect to host: timed out\n") - return subprocess.CompletedProcess([], 0, stdout=node.name + "\n", stderr="") + return subprocess.CompletedProcess([], 0, stdout=self.out.get(node.name, node_text()), stderr="") -class Leases: - """Who holds each node, as NodeLeases.holder answers: a holder id ``/trainer@``.""" +def _entry(name, i, *, env=None, group=None, host=None, address=None, min_ib=None, family="cuda"): + number = int(name.rsplit("-", 1)[1]) if name.rsplit("-", 1)[-1].isdigit() else 100 + i + return (f" - {{name: {name}, host: {host or f'ops@{name}.example'}, " # one machine: one address + f"address: {address or f'198.51.100.{10 + number}'}, interface: bond0, " + f"device_family: {family}, cpu_arch: x86_64, card: B300, cards_per_node: 8, hbm_gib: 288, " + "host_memory_gib: 2048, fabric: ib, runtime: docker, docker_args: [--gpus, all]" + + (f", env: {{NCCL_IB_HCA: '{env}'}}" if env else "") + + (f", fabric_group: {group}" if group else "") + + (f", min_ib_gbps: {min_ib}" if min_ib else "") + "}\n") - made: list[tuple[str, str]] = [] - def __init__(self, store_uri, run_id, holders=None): - Leases.made.append((store_uri, run_id)) - self.holders = dict(holders or {}) - - def holder(self, node): - run = self.holders.get(getattr(node, "name", node)) - return None if run is None else f"{run}/trainer@host-{run}" - - -@pytest.fixture -def stand_ins(monkeypatch): - """The three checks' modules, as the contract has them; returns their knobs.""" - knobs = {"checker": Checker(), "placement": (True, "", False), "holders": {}, "placed": [], "inventories": []} - monkeypatch.setattr(ij, "_checker_for", lambda node: knobs["checker"]) - - def placement(nodes, need, inventory): - knobs["placed"].append(([n.name for n in nodes], need)) - knobs["inventories"].append(None if inventory is None else [n.name for n in inventory]) - return knobs["placement"] - - monkeypatch.setattr(ij, "_check_placement", placement) - monkeypatch.setattr(ij, "_node_leases", lambda uri, run: Leases(uri, run, knobs["holders"])) - return knobs - - -def _inventory(path, names, *, env=None, groups=None): - path.write_text("nodes:\n" + "".join( - f" - {{name: {name}, host: ops@{name}.example, address: 198.51.100.{10 + i}, interface: bond0, " - "device_family: cuda, cpu_arch: x86_64, card: B300, cards_per_node: 8, hbm_gib: 288, " - "host_memory_gib: 2048, fabric: ib, runtime: docker, docker_args: [--gpus, all]" - + (f", env: {{NCCL_IB_HCA: '{env}'}}" if env else "") - + (f", fabric_group: {groups[name]}" if groups and name in groups else "") + "}\n" +def _inventory(path, names, *, env=HCA, groups=None, lease_store=None, hosts=None, addresses=None, min_ib=None): + path.write_text((f"lease_store: {lease_store}\n" if lease_store else "") + "nodes:\n" + "".join( + _entry(name, i, env=env, group=(groups or {}).get(name), host=(hosts or {}).get(name), + address=(addresses or {}).get(name), min_ib=min_ib) for i, name in enumerate(names))) return path @@ -111,77 +81,150 @@ def _nodes(tmp_path, names=("b300-4", "b300-5"), **kw): return load_inventory(_inventory(tmp_path / "inv.yaml", names, **kw)) -def test_healthy_free_nodes_of_one_group_join(tmp_path, stand_ins): - nodes = _nodes(tmp_path, env="mlx5_0,mlx5_1") - out = ij.check(nodes, need=2, run_id="r", lease_store="s3://b/leases", ssh=Ssh()) - assert out.ok and out.refusals == [] and out.notes == [] - assert stand_ins["checker"].scripts == [["mlx5_0", "mlx5_1"]] * 2 # a multi-node island checks its HCAs - assert stand_ins["placed"] == [(["b300-4", "b300-5"], 2)] and Leases.made[-1] == ("s3://b/leases", "r") +def _check(nodes, ssh, need=2, **kw): + return ij.check(nodes, need=need, run_id="r-i2", ssh=ssh, inventory=nodes, **kw) -def test_an_unhealthy_node_refuses_the_island_naming_why(tmp_path, stand_ins): - stand_ins["checker"] = Checker(bad={"b300-5": "Xid 79 since the last check"}) - out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) - assert out.refusals == ["node b300-5 is not healthy: Xid 79 since the last check"] +# -- health: the real checker, absolute rules ------------------------------------------------------ +def test_healthy_nodes_join_with_one_bounded_check_each(tmp_path): + ssh = Ssh() + out = _check(_nodes(tmp_path), ssh) + assert out.ok and out.nodes == ["b300-4", "b300-5"] and out.warnings == [] + assert ssh.calls == ["b300-4", "b300-5"] + assert all(t is not None and 0 < t <= ij.HEALTH_TIMEOUT_S for t in ssh.timeouts) # never unbounded + + +@pytest.mark.parametrize(("text", "why"), [ + (XID_79, "GPU 5 XID 79"), + (ECC_5, "GPU 2 uncorrectable ECC 5 (volatile)"), + (FM_DOWN, "nvidia-fabricmanager inactive on an NVSwitch node"), + (node_text(gpus=(0, gpus_text(n=7))), "7 of 8 GPUs visible"), +]) +def test_a_fault_a_first_check_cannot_see_as_a_change_refuses(tmp_path, text, why): + """The checker's rules compare with the previous check; a joining node has none: a + hardware XID of this boot, a volatile uncorrectable ECC count, a stopped fabric manager + on NVSwitch GPUs refuse it.""" + out = _check(_nodes(tmp_path), Ssh({"b300-5": text})) + assert out.refusals == [f"node b300-5 is not healthy: {why}"] and out.nodes == [] + + +def test_a_pcie_node_without_nvswitch_joins_with_its_fabric_manager_inactive(tmp_path): + assert _check(_nodes(tmp_path), Ssh({"b300-4": PCIE, "b300-5": PCIE})).ok + + +def test_a_port_down_refuses_a_multi_node_island_only(tmp_path): + assert _check(_nodes(tmp_path), Ssh({"b300-4": PORT_DOWN})).refusals == [ + "node b300-4 is not healthy: mlx5_3 port DOWN"] + (one,) = _nodes(tmp_path, names=("b300-4",)) + assert _check([one], Ssh({"b300-4": PORT_DOWN}), need=1).ok + + +def test_a_slow_port_is_refused_against_the_island_s_fastest_or_min_ib_gbps(tmp_path): + out = _check(_nodes(tmp_path), Ssh({"b300-5": SLOW})) + assert len(out.refusals) == 1 and out.refusals[0].startswith( + "node b300-5 is not healthy: mlx5_0 rate 100 < 200 Gb/s (half the fastest job port of the island's nodes, " + "400 Gb/s)") + assert _check(_nodes(tmp_path), Ssh({"b300-4": SLOW, "b300-5": SLOW})).ok # all alike: no slower one + declared = _nodes(tmp_path, min_ib=400) # the inventory's min_ib_gbps: every node held to it + out = _check(declared, Ssh({"b300-4": SLOW, "b300-5": SLOW})) + assert [r.split(":")[0] for r in out.refusals] == ["node b300-4 is not healthy", "node b300-5 is not healthy"] + assert "mlx5_0 rate 100 < 400 Gb/s" in out.refusals[0] + + +@pytest.mark.parametrize(("text", "why"), [ + (NVSMI_TIMEOUT, f"nvidia-smi: timed out after {node_health.SECTION_TIMEOUT_S}s"), + (BUSY, "node health check skipped: the previous one still runs (a tool stuck on the node)"), + (CUT, "node health output incomplete (no ibstat, ibv_devinfo)"), +]) +def test_a_check_that_does_not_read_refuses_unless_forced(tmp_path, text, why): + nodes = _nodes(tmp_path) + out = _check(nodes, Ssh({"b300-4": text})) + assert out.refusals == [f"node b300-4: its health check did not read ({why})"] + forced = _check(nodes, Ssh({"b300-4": text}), force=True) + assert forced.ok and forced.warnings == [f"node b300-4: its health check did not read ({why}); --force: it " + "joins unchecked"] -def test_a_port_down_refuses_a_multi_node_island_only(tmp_path, stand_ins): - stand_ins["checker"] = Checker(ib_down={"b300-4"}) - assert ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()).refusals == [ - "node b300-4 is not healthy: mlx5_3 DOWN"] - one = _nodes(tmp_path, names=("b300-4",)) - assert ij.check(one, need=1, run_id="r", ssh=Ssh()).ok - assert stand_ins["checker"].scripts[-1] == [] # alone: the GPU checks only +def test_ib_tools_unread_refuse_a_multi_node_island_unless_forced(tmp_path): + """ok(multi) None: the GPUs pass, the job's ports did not read.""" + nodes = _nodes(tmp_path) + out = _check(nodes, Ssh({"b300-5": IB_UNREAD})) + assert out.refusals == [f"node b300-5: its health check did not read ({node_health.IB_UNREAD})"] + assert _check(nodes, Ssh({"b300-5": IB_UNREAD}), force=True).warnings + (one,) = _nodes(tmp_path, names=("b300-5",)) + assert _check([one], Ssh({"b300-5": IB_UNREAD}), need=1).ok # alone: its GPUs only -def test_a_single_node_island_is_refused_for_its_gpus_only(tmp_path, stand_ins): - class Both(Checker): - def parse(self, text, hcas, prev): - return HealthResult(True, False, False, ["GPU count 7, expected 8", "mlx5_3 DOWN"], - {"gpu_reasons": ["GPU count 7, expected 8"], "ib_reasons": ["mlx5_3 DOWN"]}) - stand_ins["checker"] = Both() - one = _nodes(tmp_path, names=("b300-4",)) - assert ij.check(one, need=1, run_id="r", ssh=Ssh()).refusals == [ - "node b300-4 is not healthy: GPU count 7, expected 8"] - assert ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()).refusals[0] == ( - "node b300-4 is not healthy: GPU count 7, expected 8; mlx5_3 DOWN") +def test_force_never_lets_an_unhealthy_node_join(tmp_path): + assert _check(_nodes(tmp_path), Ssh({"b300-5": XID_79}), force=True).refusals == [ + "node b300-5 is not healthy: GPU 5 XID 79"] -def test_a_node_with_its_health_check_off_is_noted_and_not_called(tmp_path, stand_ins): - import dataclasses +def test_a_node_that_does_not_answer_is_refused(tmp_path): + out = _check(_nodes(tmp_path), Ssh(unreachable={"b300-4"})) + assert out.refusals == ["node b300-4: its health check did not answer (ssh exit 255: ssh: connect to host: " + "timed out)"] - stand_ins["checker"] = Checker(bad={"b300-4": "Xid 79"}) - first, second = _nodes(tmp_path) + +def test_the_real_null_checker_is_a_note_with_no_ssh_call(tmp_path): + nodes = [dataclasses.replace(n, device_family="no-such-family") for n in _nodes(tmp_path)] + assert isinstance(ij._checker_for(nodes[0]), node_health.NullChecker) ssh = Ssh() - out = ij.check([dataclasses.replace(first, node_health="off"), second], need=2, run_id="r", ssh=ssh) + out = _check(nodes, ssh) + assert out.ok and ssh.calls == [] + assert out.notes[:2] == [f"node {n}: no health check for device family no-such-family" for n in ("b300-4", "b300-5")] + + +def test_a_node_with_its_health_check_off_is_noted_and_not_called(tmp_path): + first, second = _nodes(tmp_path) + ssh = Ssh({"b300-4": XID_79}) + out = _check([dataclasses.replace(first, node_health="off"), second], ssh) assert out.ok and ssh.calls == ["b300-5"] assert "node b300-4: node_health off in the inventory: its health is not checked" in out.notes -def test_a_node_that_does_not_answer_is_refused(tmp_path, stand_ins): - out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh(unreachable={"b300-4"})) - assert out.refusals == [("node b300-4: its health check did not answer (ssh exit 255: ssh: connect to host: " - "timed out)")] +def test_the_island_s_own_nccl_ib_hca_wins_over_the_node_s(tmp_path): + """The job's HCAs are {**node.env, **island env}, as the island's launch exports them.""" + nodes = _nodes(tmp_path, env="=mlx5_0,mlx5_1") + assert _check(nodes, Ssh({"b300-4": PORT_DOWN})).ok # mlx5_3 is not the node's job port + out = _check(nodes, Ssh({"b300-4": PORT_DOWN}), env={"NCCL_IB_HCA": "=mlx5_2,mlx5_3"}) + assert out.refusals == ["node b300-4 is not healthy: mlx5_3 port DOWN"] + assert ij.island_env_of(["--island-env", "A=1", "--island-env=NCCL_IB_HCA==mlx5_3"]) == { + "A": "1", "NCCL_IB_HCA": "=mlx5_3"} + # the member's launch argv: the fleet's --island-env, then the island's own + inventory = _inventory(tmp_path / "island.yaml", ["b300-4", "b300-5"], env="=mlx5_0,mlx5_1") + member = {"name": "north", "gpu": GPU, "argv": ["--rl-node-inventory", str(inventory), + "--island-env", "NCCL_IB_HCA==mlx5_2,mlx5_3"]} + out = ij.check_member(member, {"members": []}, fleet_argv=["--island-env", "NCCL_IB_HCA==mlx5_0"], + run_id="r-i2", ssh=Ssh({"b300-4": PORT_DOWN}), log=lambda m: None) + assert out.refusals == ["node b300-4 is not healthy: mlx5_3 port DOWN"] -def test_a_family_without_a_checker_is_noted_not_refused(tmp_path, stand_ins): - stand_ins["checker"] = Checker(checked=False) - out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) - assert out.ok and any("no health check for device family cuda" in n for n in out.notes) +# -- this fleet, without lease_store: exact count, overlap by machine ------------------------------- -def test_nodes_across_fabric_groups_refuse_the_island(tmp_path, stand_ins): - stand_ins["placement"] = (False, ("the island needs 2 healthy nodes of one fabric group; group a has only 1, " - "group b has only 1"), False) - out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) - assert out.refusals == [("fabric: the island needs 2 healthy nodes of one fabric group; group a has only 1, " - "group b has only 1")] +def test_the_wrong_count_and_a_node_of_another_island_are_refused(tmp_path): + nodes = _nodes(tmp_path) + assert _check(nodes, Ssh(), need=3).refusals == [ + "the island needs 3 trainer node(s); its inventory lists 2 ['b300-4', 'b300-5']"] + other = load_inventory(_inventory(tmp_path / "other.yaml", ["b300-5"], addresses={"b300-5": "203.0.113.5"})) + taken = {k: "sglang" for k in ij.node_keys(other[0])} # its name + assert _check(nodes, Ssh(), taken=taken).refusals == ["node b300-5 is island sglang's"] + + +@pytest.mark.parametrize(("host", "address"), [("root@B300-5.Example", "203.0.113.9"), # the same SSH target + ("b300-5-alias", "198.51.100.15")]) # the same address +def test_the_same_machine_under_another_name_or_user_is_another_island_s(tmp_path, host, address): + (theirs,) = load_inventory(_inventory(tmp_path / "theirs.yaml", ["their-node"], hosts={"their-node": host}, + addresses={"their-node": address})) + taken = {k: "south" for k in ij.node_keys(theirs)} + out = _check(_nodes(tmp_path), Ssh(), taken=taken) # b300-5: ops@b300-5.example, 198.51.100.15 + assert out.refusals == ["node b300-5 is island south's"] -def test_the_real_placement_check_refuses_nodes_of_two_fabric_groups(tmp_path, monkeypatch): - """fabric_groups.check_placement itself, on the island's nodes and its whole inventory.""" - monkeypatch.setattr(ij, "_checker_for", lambda node: Checker()) +# -- fabric groups ---------------------------------------------------------------------------------- +def test_the_real_placement_refuses_nodes_of_two_fabric_groups(tmp_path): def run(groups, names=("b300-4", "b300-5")): inventory = load_inventory(_inventory(tmp_path / "g.yaml", ["b300-3", *names], groups=groups)) nodes = [n for n in inventory if n.name in names] @@ -195,130 +238,321 @@ def run(groups, names=("b300-4", "b300-5")): other = run({"b300-3": "a"}) # groups in the inventory, none on the island's nodes assert not other.ok and other.refusals[0].startswith("fabric: ") -def test_an_inventory_without_groups_is_only_a_note(tmp_path, stand_ins): - stand_ins["placement"] = (True, "no fabric_group in the inventory: run yeto cluster probe --write", True) - out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) - assert out.ok and out.notes[0].startswith("fabric: no fabric_group") +# -- leases: the real NodeLeases on a directory store ---------------------------------------------- -def test_a_node_leased_to_another_run_is_refused_and_this_island_s_own_is_free(tmp_path, stand_ins): - stand_ins["holders"] = {"b300-4": "other-run", "b300-5": "r"} - out = ij.check(_nodes(tmp_path), need=2, run_id="r", lease_store="s3://b/leases", ssh=Ssh()) - assert out.refusals == ["node b300-4 is leased to run other-run"] - stand_ins["holders"] = {"b300-4": "r-m1", "b300-5": "r-i0"} # its own moved launch; another island - out = ij.check(_nodes(tmp_path), need=2, run_id="r", lease_store="s3://b/leases", ssh=Ssh()) - assert out.refusals == ["node b300-5 is leased to run r-i0"] - out = ij.check(_nodes(tmp_path), need=2, run_id="r", ssh=Ssh()) # no lease_store: noted - assert out.ok and any("no lease_store" in n for n in out.notes) +def _hold(store, node, run, identity="x"): + assert NodeLeases(store, run, identity=identity).acquire(node).ok -def test_the_real_leases_refuse_a_node_another_run_holds(tmp_path): - """NodeLeases itself on a directory lease store: another run's live lease refuses the node, - the island's own launch's lease does not.""" +def test_a_node_another_run_holds_is_refused_naming_that_run(tmp_path): store = str(tmp_path / "leases") - nodes = _nodes(tmp_path) - assert NodeLeases(store, "other-run/trainer", identity="a").acquire(nodes[0]).ok - assert NodeLeases(store, "r-i2/trainer", identity="b").acquire(nodes[1]).ok - out = ij.JoinCheck() - ij.check_leases(nodes, lease_store=store, run_id="r-i2", out=out) - assert out.refusals == ["node b300-4 is leased to run other-run"] + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["b300-4", "b300-5"], lease_store=store)) + _hold(store, nodes[0], "other-run/trainer") + out = _check(nodes, Ssh(), lease_store=store) + assert out.refusals == ["node b300-4 is leased to run other-run", + "1 of 2 trainer node(s) are free and healthy, 2 needed"] + + +@pytest.mark.parametrize(("holder", "own"), [ + ("r-i2/trainer", True), ("r-i2-m1/trainer", True), ("r-i2-m12/trainer", True), + ("r-i2-mtest/trainer", False), ("r-i2-m/pool", False), ("r-i2-m/trainer", False), ("r-i2/pool", False), + ("r-i20/trainer", False), ("xr-i2/trainer", False), ("r-i2-m1-m2/trainer", False)]) +def test_only_the_island_s_own_launch_owns_its_lease(tmp_path, holder, own): + store = str(tmp_path / "leases") + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["b300-4", "b300-5"], lease_store=store)) + _hold(store, nodes[0], holder) + out = _check(nodes, Ssh(), lease_store=store) + assert out.ok is own, out.refusals + assert ij.own_lease(f"{holder}@x", "r-i2") is own -def test_the_real_checker_of_a_family_without_one_runs_nothing(tmp_path): - import dataclasses +def test_a_lease_that_does_not_read_refuses(tmp_path, monkeypatch): + class Broken: + def holder(self, node): + raise OSError("store unreachable") - (node,) = _nodes(tmp_path, names=("b300-4",)) - checker = ij._checker_for(node) # cuda: the real checker, built with the node's card count - assert checker.enabled and checker.expect_gpus == 8 - other = dataclasses.replace(node, device_family="no-such-family") - ssh, out = Ssh(), ij.JoinCheck() - ij.check_health([other], multi=False, ssh=ssh, out=out) - assert ssh.calls == [] and out.ok and out.notes == ["node b300-4: no health check for device family no-such-family"] + monkeypatch.setattr(ij, "_node_leases", lambda uri, run: Broken()) + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["b300-4", "b300-5"], lease_store="s3://b/l")) + out = _check(nodes, Ssh(), lease_store="s3://b/l") + assert out.refusals == [f"node {n}: its lease does not read (OSError: store unreachable)" for n in ("b300-4", "b300-5")] + monkeypatch.setattr(ij, "_node_leases", lambda uri, run: (_ for _ in ()).throw(RuntimeError("no such bucket"))) + assert _check(nodes, Ssh(), lease_store="s3://b/l").refusals == ["lease store s3://b/l: RuntimeError: no such bucket"] -def test_a_node_of_another_island_or_the_wrong_count_is_refused(tmp_path, stand_ins): - nodes = _nodes(tmp_path) - out = ij.check(nodes, need=2, run_id="r", taken={"ops@b300-5.example": "sglang"}, ssh=Ssh()) - assert out.refusals == ["node b300-5 is island sglang's"] - out = ij.check(nodes, need=3, run_id="r", ssh=Ssh()) - assert out.refusals == ["the island needs 3 trainer node(s); its inventory lists 2 ['b300-4', 'b300-5']"] +# -- a shared inventory with lease_store: the island takes need of more nodes ----------------------- -def test_checks_whose_modules_are_missing_refuse(tmp_path, monkeypatch): - def missing(*a, **kw): - raise ImportError("No module named 'yeto.hw.node_health'") +FOUR = ("b300-0", "b300-1", "b300-2", "b300-3") - for name in ("_checker_for", "_check_placement", "_node_leases"): - monkeypatch.setattr(ij, name, missing) - out = ij.check(_nodes(tmp_path), need=2, run_id="r", lease_store="s3://b/l", ssh=Ssh()) - assert len(out.refusals) == 4 and all("ImportError" in r for r in out.refusals) +def _shared(tmp_path, **kw): + store = str(tmp_path / "leases") + return store, load_inventory(_inventory(tmp_path / "shared.yaml", FOUR, lease_store=store, **kw)) -# -- yeto fleet island add -------------------------------------------------------------------------- -def _add(run_cli, samplers, inventory, *extra): - return run_cli("add", "--name", "north", "--gpu", GPU, "--usd-per-h", "0", "--samplers", str(samplers), +def test_two_free_nodes_of_a_shared_inventory_make_the_island(tmp_path): + """The spec's scenario: the fleet's island north holds two nodes of the inventory; the + new island takes the other two free ones.""" + store, nodes = _shared(tmp_path) + for node in nodes[:2]: + _hold(store, node, "r-i0/trainer") + ssh = Ssh() + out = _check(nodes, ssh, lease_store=store, islands={"r-i0": "north"}) + assert out.ok and out.nodes == ["b300-2", "b300-3"] and ssh.calls == ["b300-2", "b300-3"] + assert "left out: node b300-0 is island north's (its launch holds the lease)" in out.notes + + +def test_a_shared_inventory_with_one_node_leased_and_one_unhealthy_is_refused(tmp_path): + store, nodes = _shared(tmp_path) + for node in nodes[:2]: + _hold(store, node, "r-i0/trainer") + _hold(store, nodes[2], "other-run/trainer") + out = _check(nodes, Ssh({"b300-3": XID_79}), lease_store=store, islands={"r-i0": "north"}) + assert out.refusals == ["node b300-0 is island north's (its launch holds the lease)", + "node b300-1 is island north's (its launch holds the lease)", + "node b300-2 is leased to run other-run", + "node b300-3 is not healthy: GPU 5 XID 79", + "0 of 4 trainer node(s) are free and healthy, 2 needed"] + + +def test_the_group_placement_picks_from_the_free_healthy_nodes(tmp_path): + store, nodes = _shared(tmp_path, groups={"b300-0": "a", "b300-1": "a", "b300-2": "b", "b300-3": "b"}) + _hold(store, nodes[0], "other-run/trainer") + out = _check(nodes, Ssh(), lease_store=store) + assert out.ok and out.nodes == ["b300-2", "b300-3"] # group a has one free node + out = _check(nodes, Ssh({"b300-3": ECC_5}), lease_store=store) + assert not out.ok and out.refusals[-1].startswith("fabric: the island needs 2 healthy nodes of one fabric group") + assert "node b300-3 is not healthy: GPU 2 uncorrectable ECC 5 (volatile)" in out.refusals + + +def test_an_unhealthy_node_the_launch_would_pick_by_its_leases_is_refused(tmp_path): + """The island's launch picks by leases only (in order): the check refuses a pick it + would make onto a node found unhealthy, rather than pass nodes the launch does not take.""" + store, nodes = _shared(tmp_path) + _hold(store, nodes[0], "other-run/trainer") + out = _check(nodes, Ssh({"b300-1": XID_79}), lease_store=store) + assert out.refusals[0] == "node b300-1 is not healthy: GPU 5 XID 79" + assert out.refusals[1].startswith("the island's launch picks its nodes by their leases and would take b300-1") + + +# -- yeto fleet island add / move ----------------------------------------------------------------- + +def _add(run_cli, samplers, inventory, *extra, name="north"): + return run_cli("add", "--name", name, "--gpu", GPU, "--usd-per-h", "0", "--samplers", str(samplers), "--inventory", str(inventory), *extra) -@pytest.mark.parametrize("problem", ["health", "fabric", "lease"]) -def test_add_refuses_an_ssh_island_failing_one_check_and_writes_nothing(fleet_store, stand_ins, tmp_path, # noqa: F811 +@pytest.fixture +def wired(monkeypatch): + """SSH answers healthy (``ssh.out``: per node); the launch dry run and session check pass.""" + ssh = Ssh() + monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", lambda: ssh) + monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda member, **kw: None) + monkeypatch.setattr(fleet_islands, "session_check", lambda *a, **kw: None) + return ssh + + +@pytest.mark.parametrize("problem", ["health", "fabric", "lease", "unread"]) +def test_add_refuses_an_ssh_island_failing_one_check_and_writes_nothing(fleet_store, tmp_path, # noqa: F811 monkeypatch, capsys, problem): _cfg, objects, store, run_cli, samplers = fleet_store + ssh = Ssh() + monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", lambda: ssh) inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) - monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", Ssh) if problem == "health": - stand_ins["checker"] = Checker(bad={"b300-4": "GPU count 7, expected 8"}) - why = "node b300-4 is not healthy: GPU count 7, expected 8" + ssh.out["b300-4"] = node_text(gpus=(0, gpus_text(n=7))) + why = "node b300-4 is not healthy: 7 of 8 GPUs visible" elif problem == "fabric": - stand_ins["placement"] = (False, "group a has only 1, group b has only 1", False) - why = "fabric: group a has only 1, group b has only 1" - else: - inventory.write_text("lease_store: s3://b/leases\n" + inventory.read_text()) - stand_ins["holders"] = {"b300-5": "another-run"} + inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"], groups={"b300-4": "a", "b300-5": "b"}) + why = "fabric: the island needs 2 healthy nodes of one fabric group" + elif problem == "lease": + leases = str(tmp_path / "leases") + inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"], lease_store=leases) + _hold(leases, load_inventory(inventory)[1], "another-run/trainer") why = "node b300-5 is leased to run another-run" + else: + ssh.out["b300-5"] = NVSMI_TIMEOUT + why = "node b300-5: its health check did not read (nvidia-smi: timed out after" monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda *a, **kw: pytest.fail("checked before the dry run")) for dry in ((), ("--dry-run",)): assert _add(run_cli, samplers, inventory, *dry) == 2 - err = capsys.readouterr().err - assert "refused: island north's nodes cannot join: " + why in err + assert "refused: island north's nodes cannot join: " + why in capsys.readouterr().err assert store.read()["generation"] == 1 and objects.read(claim_key(2)) is None -def test_add_takes_an_ssh_island_whose_nodes_pass(fleet_store, stand_ins, tmp_path, monkeypatch, capsys): # noqa: F811 +def test_add_with_force_takes_an_island_whose_check_does_not_read_with_a_warning(fleet_store, wired, tmp_path, # noqa: F811 + capsys): + _cfg, _objects, store, run_cli, samplers = fleet_store + wired.out["b300-5"] = BUSY + inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) + assert _add(run_cli, samplers, inventory, "--force") == 0 + assert "WARNING: island north: node b300-5: its health check did not read" in capsys.readouterr().err + assert store.read()["generation"] == 2 + wired.out["b300-6"] = XID_79 + south = _inventory(tmp_path / "south.yaml", ["b300-6", "b300-7"]) + assert _add(run_cli, samplers, south, "--force", name="south") == 2 # unhealthy: never forced + + +def test_add_takes_an_ssh_island_whose_nodes_pass(fleet_store, wired, tmp_path, monkeypatch, capsys): # noqa: F811 _cfg, objects, store, run_cli, samplers = fleet_store inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) - monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", Ssh) dry_runs = [] monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda member, **kw: dry_runs.append(member)) - monkeypatch.setattr(fleet_islands, "session_check", lambda *a, **kw: None) assert _add(run_cli, samplers, inventory) == 0 out = capsys.readouterr() - assert "island north's nodes pass the join checks" in out.out - assert stand_ins["inventories"] == [["b300-4", "b300-5"]] # placed against its whole inventory + assert "island north takes nodes b300-4, b300-5; its nodes pass the join checks" in out.out assert "note: island north: no lease_store" in out.err (member,) = dry_runs - assert member["argv"][-2:] == ["--rl-node-inventory", str(inventory)] and member["gpu"] == GPU + assert member["argv"][-2:] == ["--rl-node-inventory", str(inventory.resolve())] and member["gpu"] == GPU assert store.read()["generation"] == 2 and objects.read(claim_key(2)) is not None -def test_a_second_ssh_island_on_the_nodes_of_the_first_is_refused(fleet_store, stand_ins, tmp_path, # noqa: F811 - monkeypatch, capsys): - cfg, _objects, _store, run_cli, samplers = fleet_store - monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", Ssh) - monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda member, **kw: None) - monkeypatch.setattr(fleet_islands, "session_check", lambda *a, **kw: None) - assert _add(run_cli, samplers, _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"])) == 0 +def test_the_dry_run_of_a_shared_inventory_prints_the_nodes_the_island_takes(fleet_store, wired, tmp_path, # noqa: F811 + capsys): + _cfg, _objects, store, run_cli, samplers = fleet_store + leases = str(tmp_path / "leases") + inventory = _inventory(tmp_path / "shared.yaml", FOUR, lease_store=leases) + _hold(leases, load_inventory(inventory)[0], "r-i0/trainer") # island mixed's launch (prefix r-i0) + _hold(leases, load_inventory(inventory)[1], "other-run/trainer") + assert _add(run_cli, samplers, inventory, "--dry-run") == 0 + captured = capsys.readouterr() + assert "island north takes nodes b300-2, b300-3" in captured.out + assert "left out: node b300-0 is island mixed's (its launch holds the lease)" in captured.err + assert store.read()["generation"] == 1 + + +def test_an_inventory_path_is_kept_absolute_whatever_the_cwd(fleet_store, wired, tmp_path, monkeypatch, # noqa: F811 + capsys): + """A relative --inventory is resolved when the island is written: a later add from + another directory still reads the first island's nodes.""" + cfg, _objects, store, run_cli, samplers = fleet_store + (here := tmp_path / "a").mkdir() + (there := tmp_path / "b").mkdir() + _inventory(here / "north.yaml", ["b300-4", "b300-5"]) + _inventory(there / "south.yaml", ["b300-5", "b300-6"]) + monkeypatch.chdir(here) + assert _add(run_cli, samplers, "north.yaml") == 0 + north = next(m for m in store.read()["members"] if m.get("name") == "north") + assert ij.inventory_of(north["argv"]) == str((here / "north.yaml").resolve()) + monkeypatch.chdir(there) other = samplers.parent / "south.samplers.json" other.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) - south = _inventory(tmp_path / "south.yaml", ["b300-5", "b300-6"]) - assert run_cli("add", "--name", "south", "--gpu", GPU, "--usd-per-h", "0", "--samplers", str(other), - "--inventory", str(south)) == 2 + capsys.readouterr() + assert _add(run_cli, other, "south.yaml", name="south") == 2 assert "node b300-5 is island north's" in capsys.readouterr().err +def test_two_adds_at_once_on_overlapping_inventories_one_is_refused_at_its_write(fleet_store, wired, tmp_path, # noqa: F811 + monkeypatch, capsys): + """South checks against the desired state without north; north is written meanwhile and + takes south's learner id: south's write checks again on the new state (north's nodes) and + under its new prefix (north's lease, no longer south's own), and is refused.""" + cfg, _objects, store, run_cli, samplers = fleet_store + leases = str(tmp_path / "leases") + north_inv = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) + south_inv = _inventory(tmp_path / "south.yaml", ["b300-5", "b300-6"]) + south_samplers = samplers.parent / "south.samplers.json" + south_samplers.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) + from yeto.launch import learner_ids + + real = learner_ids.allocate_learner_id + meanwhile = [] + + def allocate(objects, **kw): + if kw.get("island") == "south" and not meanwhile: + meanwhile.append(_add(run_cli, samplers, north_inv)) # north's add runs between south's check and write + return real(objects, **kw) + + monkeypatch.setattr(learner_ids, "allocate_learner_id", allocate) + assert _add(run_cli, south_samplers, south_inv, name="south") == 3 and meanwhile == [0] + err = capsys.readouterr().err + assert "island south's nodes cannot join (checked again on the desired state now): node b300-5 is island north's" in err + trainers = {m["name"]: m for m in store.read()["members"] if m.get("kind") == "trainer"} + assert "south" not in trainers and trainers["north"]["learner_id"] == 2 # north took the id south checked under + + +def test_an_id_claimed_meanwhile_checks_the_leases_again_under_the_new_prefix(fleet_store, wired, tmp_path, # noqa: F811 + monkeypatch, capsys): + """South's check runs under prefix r-i2 (a lease of r-i2 is its own); north takes id 2 + meanwhile, so south is written as r-i3: that lease is north's now, and south is refused.""" + cfg, _objects, store, run_cli, samplers = fleet_store + leases = str(tmp_path / "leases") + shared = _inventory(tmp_path / "shared.yaml", ["b300-7", "b300-8"], lease_store=leases) + _hold(leases, load_inventory(shared)[0], "r-i2/trainer") + south_samplers = samplers.parent / "south.samplers.json" + south_samplers.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) + north = _inventory(tmp_path / "north.yaml", ["b300-9", "b300-10"]) + from yeto.launch import learner_ids + + real, meanwhile = learner_ids.allocate_learner_id, [] + + def allocate(objects, **kw): + if kw.get("island") == "south" and not meanwhile: + meanwhile.append(_add(run_cli, samplers, north)) + return real(objects, **kw) + + monkeypatch.setattr(learner_ids, "allocate_learner_id", allocate) + assert _add(run_cli, south_samplers, shared, name="south") == 3 and meanwhile == [0] + err = capsys.readouterr().err + assert ("island south's nodes cannot join (checked again on the desired state now): node b300-7 is island " + "north's (its launch holds the lease)") in err + assert "south" not in {m["name"] for m in store.read()["members"]} + + +def test_move_to_ssh_runs_the_same_join_checks(fleet_store, wired, tmp_path, capsys): # noqa: F811 + _cfg, _objects, store, run_cli, samplers = fleet_store + + def move(inventory, *extra): + return run_cli("move", "--name", "sglang", "--gpu", GPU, "--usd-per-h", "0", "--inventory", str(inventory), + *extra) + + three = _inventory(tmp_path / "three.yaml", ["b300-1", "b300-2", "b300-3"]) + assert move(three) == 2 and "the island needs 2 trainer node(s); its inventory lists 3" in capsys.readouterr().err + wired.out["b300-2"] = XID_79 + two = _inventory(tmp_path / "two.yaml", ["b300-1", "b300-2"]) + assert move(two) == 2 and "node b300-2 is not healthy: GPU 5 XID 79" in capsys.readouterr().err + split = _inventory(tmp_path / "split.yaml", ["b300-3", "b300-4"], groups={"b300-3": "a", "b300-4": "b"}) + assert move(split) == 2 and "fabric: the island needs 2 healthy nodes" in capsys.readouterr().err + leases = str(tmp_path / "leases") + held = _inventory(tmp_path / "held.yaml", ["b300-5", "b300-6"], lease_store=leases) + _hold(leases, load_inventory(held)[0], "other-run/trainer") + assert move(held) == 2 and "node b300-5 is leased to run other-run" in capsys.readouterr().err + assert store.read()["generation"] == 1 + assert _add(run_cli, samplers, _inventory(tmp_path / "north.yaml", ["b300-7", "b300-8"])) == 0 + onto = _inventory(tmp_path / "onto.yaml", ["b300-8", "b300-9"]) + assert move(onto) == 2 and "node b300-8 is island north's" in capsys.readouterr().err + ok = _inventory(tmp_path / "ok.yaml", ["b300-10", "b300-11"]) + assert move(ok, "--dry-run") == 0 and "island sglang takes nodes b300-10, b300-11" in capsys.readouterr().out + assert move(ok) == 0 + sglang = next(m for m in store.read()["members"] if m.get("name") == "sglang") + assert sglang["gpu"] == GPU and ij.inventory_of(sglang["argv"]) == str(ok.resolve()) + assert ij.without_inventory(sglang["argv"]) == [a for a in sglang["argv"][:-2]] + # its own nodes (its inventory now) are not another island's: a move onto them again passes + assert move(ok) == 0 + + def test_an_inventory_is_for_an_ssh_island_only(fleet_store, tmp_path, capsys): # noqa: F811 _cfg, _objects, _store, run_cli, samplers = fleet_store inventory = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]) assert run_cli("add", "--name", "north", "--gpu", "modal:1x2xh100", "--usd-per-h", "8", "--samplers", str(samplers), "--inventory", str(inventory)) == 2 assert "--inventory is the node inventory of an ssh: island" in capsys.readouterr().err + assert run_cli("move", "--name", "sglang", "--gpu", "modal:1x2xh100", "--inventory", str(inventory)) == 2 + assert "--inventory is the node inventory of an ssh: island" in capsys.readouterr().err + + +def test_min_ib_gbps_is_a_positive_number_of_the_inventory(tmp_path): + from yeto.launch.node_inventory import InventoryError + + assert {n.min_ib_gbps for n in _nodes(tmp_path, min_ib=400)} == {400.0} + assert {n.min_ib_gbps for n in _nodes(tmp_path)} == {None} + with pytest.raises(InventoryError, match="min_ib_gbps must be a positive number"): + _nodes(tmp_path, min_ib="fast") + + +def test_join_prev_counts_every_xid_of_this_boot(tmp_path): + """The previous check a joining node lacks: a cursor of no boot (every XID of this boot is new).""" + checker = node_health.checker_for("cuda", expect_gpus=8) + assert checker.parse(XID_79, [], None).ok_single is True # the checker alone: history + assert checker.parse(XID_79, [], dict(ij.JOIN_PREV)).ok_single is False + assert FABRIC_OK in node_text() diff --git a/tests/test_node_health_wiring.py b/tests/test_node_health_wiring.py index 20ad66b9b..8e6f70923 100644 --- a/tests/test_node_health_wiring.py +++ b/tests/test_node_health_wiring.py @@ -825,3 +825,14 @@ def ssh(self, node, command, **kw): monkeypatch.setattr(sp.SshSamplerPoolOps, "ssh", ssh) _, _, cmds, _, probe = _cuda_start(tmp_path, monkeypatch) assert any("-m yeto.node run" in c for c in cmds) and sp.HEALTH_MARK in probe + + +def test_a_node_s_min_ib_gbps_holds_its_trainer_island_s_ports(tmp_path): + """The inventory's ``min_ib_gbps`` is the least rate of the job's ports (a running island's + check, as the join check of an added island).""" + nodes = tuple(replace(b300(i, env={"NCCL_IB_HCA": HCA}), min_ib_gbps=400.0 if i == 1 else None) + for i in range(3)) + ops = make_ops(tmp_path, HealthCluster(NAMES), clock=IslandClock(), health_every_s=60.0) + ops.add("isl", SshTrainerSpec(nodes=nodes, run_id="run1", workdir="/opt/yeto", run_script="echo island")) + watches = ops.islands["isl"].health + assert watches[1].checker.min_ib_gbps == 400.0 and watches[0].checker.min_ib_gbps is None diff --git a/tests/test_own_clusters_islands_doc.py b/tests/test_own_clusters_islands_doc.py index 4d777c839..4f1fe5645 100644 --- a/tests/test_own_clusters_islands_doc.py +++ b/tests/test_own_clusters_islands_doc.py @@ -1,7 +1,8 @@ """docs/OWN_CLUSTERS.md, "Islands that lag, join or leave": every command of the section parses, the ``yeto fleet island`` ones run in the doc's order on a seeded per-island fleet -(local store; the join checks' node health, placement and leases stand-ins), each dry run -writes nothing, and the flags, events and refusal the section shows are the code's.""" +(local store; the join checks run on the real node health checker over recorded tool +outputs, the real placement and real leases on a directory store), each dry run writes +nothing, and the flags, events and refusal the section shows are the code's.""" from __future__ import annotations @@ -10,7 +11,7 @@ from pathlib import Path from test_fleet_island_changes import fleet_store # noqa: F401 - fixture -from test_island_join import Leases, Ssh, _inventory, stand_ins # noqa: F401 - fixture +from test_island_join import XID_79, Ssh, _hold, _inventory from yeto.launch import island_join as ij from yeto.launch import island_straggler as st @@ -49,7 +50,7 @@ def test_the_section_names_the_code_s_flags_and_events(): assert f"`{field}`" in text, field -def test_the_section_commands_run_in_order(fleet_store, stand_ins, tmp_path, monkeypatch, capsys): # noqa: F811 +def test_the_section_commands_run_in_order(fleet_store, tmp_path, monkeypatch, capsys): # noqa: F811 from yeto.cli import build_parser _cfg, _objects, store, run_cli, samplers = fleet_store @@ -57,7 +58,8 @@ def test_the_section_commands_run_in_order(fleet_store, stand_ins, tmp_path, mon assert {a[1] for a in argvs} == {"fleet", "island"} for argv in argvs: build_parser().parse_args(argv[1:]) - monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", Ssh) + ssh = Ssh() # every node answers healthy (the recorded 8 x B300 IB node) + monkeypatch.setattr("yeto.launch.ssh_trainer_island.SshOps", lambda: ssh) monkeypatch.setattr(fleet_islands, "launch_dry_run", lambda member, **kw: None) monkeypatch.setattr(fleet_islands, "session_check", lambda *a, **kw: None) inventory = _inventory(tmp_path / "north.inventory.yaml", ["b300-4", "b300-5"]) @@ -74,15 +76,23 @@ def test_the_section_commands_run_in_order(fleet_store, stand_ins, tmp_path, mon assert "nodes pass the join checks" in out -def test_the_refusal_the_section_shows_is_the_command_s(tmp_path, stand_ins, monkeypatch): # noqa: F811 - from test_island_join import Checker - - stand_ins["checker"] = Checker(bad={"b300-5": "Xid 79 since the last check"}) - stand_ins["holders"] = {"b300-4": "other-run"} +def test_the_refusal_the_section_shows_is_the_command_s(tmp_path): + """The real checker reads b300-5's recorded output with an Xid 79 of this boot, and the + real leases show b300-4 held by another run.""" from yeto.launch.node_inventory import load_inventory - nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["b300-4", "b300-5"])) - out = ij.check(nodes, need=2, run_id="r", lease_store="s3://b/leases", ssh=Ssh()) + store = str(tmp_path / "leases") + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["b300-4", "b300-5"], lease_store=store)) + _hold(store, nodes[0], "other-run/trainer") + out = ij.check(nodes, need=2, run_id="r-i2", lease_store=store, ssh=Ssh({"b300-5": XID_79}), + inventory=nodes) line = "fleet island: refused: island north's nodes cannot join: " + "; ".join(out.refusals) assert line in section() - assert Leases.made + + +def test_the_section_states_the_join_rules_of_the_code(): + text = section() + assert "half the fastest" in text and ij.RATE_FRACTION == 0.5 + for word in ("`min_ib_gbps`", "`--force`", "`--island-env`", "`-m/trainer`", "exit 3", + "yeto fleet island move --gpu ssh:"): + assert word in text, word diff --git a/yeto/launch/island_join.py b/yeto/launch/island_join.py index 4b8a5694b..c738fae26 100644 --- a/yeto/launch/island_join.py +++ b/yeto/launch/island_join.py @@ -1,44 +1,80 @@ """The checks a new ``ssh:`` trainer island's nodes pass before ``yeto fleet island add`` -writes it into a running fleet (own-cluster-fleet-stability 9.3). - -An island added at run time takes the trainer nodes of its own inventory (the inventory -option of ``yeto fleet island add``: its launch's ``--rl-node-inventory``). Before anything is written -(and in the dry run), those nodes must: - -* be as many as the island's ``--gpu`` says, with no node another ``ssh:`` island of the - fleet already trains on (same name or SSH target); -* be healthy: the node health checker of their device family (``yeto.hw.node_health``, - built as the island's launch builds it), one SSH call per node; a multi-node island also - needs its ``NCCL_IB_HCA`` ports up at rate, a single-node one only its GPUs. A device - family without a checker, or a node with ``node_health: off``, is noted, not refused; a - node that does not answer is refused; -* fit one fabric group (``yeto.launch.fabric_groups.check_placement``): an inventory that - declares groups refuses a multi-node island across groups; one without any group only - notes it; -* be free in the inventory's ``lease_store`` (``yeto.launch.node_lease.NodeLeases``): a node - another run holds (another island of the fleet included) is refused, naming that run; a - lease of the island's own launch (its member prefix, ``-m`` after a move) is its own. - Without a ``lease_store`` nothing is checked (noted once). - -:func:`check` returns what was refused and noted; ``yeto fleet island add`` prints the notes -and refuses the change (exit 2, nothing written) on any refusal, naming each. +writes it into a running fleet, or ``yeto fleet island move`` moves an island onto them +(own-cluster-fleet-stability 9.3). + +An island's nodes are the trainer nodes of its inventory (the command's inventory option: +its launch's ``--rl-node-inventory``). Before anything is written (and in the dry run): + +* count and this fleet: an inventory without ``lease_store`` lists exactly as many + trainer nodes as ``--gpu`` says, none of them a trainer node of another ``ssh:`` island + of the fleet (same name, or same machine: the SSH target without its ``user@`` or the + ``address``, in any case). An inventory with ``lease_store`` may list more (the launch's + rule): the island takes ``need`` of them, as its launch picks them (below), and a node + is another island's when that island's launch holds its lease; +* health: the node health checker of the device family (``yeto.hw.node_health``, built as + the island's launch builds it), one SSH call per node, judged with absolute rules (a + first check has no previous one to compare with): a hardware XID in this boot, a + volatile uncorrectable ECC count above 0, an NVSwitch node whose fabric manager is not + ``active``, a GPU missing; a multi-node island also needs its ``NCCL_IB_HCA`` ports + active, at ``min_ib_gbps`` of the node when the inventory sets it, else at no less than + half the fastest job port of the island's nodes. A family without a checker, or a node + with ``node_health: off``, is noted. A check that does not read (no answer, a timeout, a + check still stuck on the node, an output cut off) refuses, unless ``--force`` (a WARNING); +* fabric group (``yeto.launch.fabric_groups``): an inventory that declares groups places + a multi-node island in one group; one without any group only notes it; +* leases (``yeto.launch.node_lease.NodeLeases``): a node another run holds, or another + island of this fleet, is left out (without ``lease_store``: a note). A lease of the + island's own launch (```` or ``-m``, part ``trainer``) is its own. A + lease that does not read refuses. + +With ``lease_store`` the island's nodes are the ones its launch will take: the free nodes +(not held by another run) in the inventory's order, those this launch holds first, placed +by ``fabric_groups.pick_placement`` (``ssh_trainer_island.lease_trainer_nodes``). The +check leaves out the nodes held by others and the unhealthy ones, then places ``need`` +nodes; none fit: refused, naming every node left out and why. A placement of the launch's +own rule that would take a node the check found unhealthy is refused too (the launch +picks by leases only). + +:func:`check` returns what was refused, noted and warned, and the nodes the island takes; +``yeto fleet island add`` / ``move`` print the notes and refuse the change (exit 2, +nothing written) on any refusal, naming each. """ from __future__ import annotations +import re import sys -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass, field from typing import Any INVENTORY_FLAG = "--rl-node-inventory" -HEALTH_TIMEOUT_S = 120.0 +ISLAND_ENV_FLAG = "--island-env" +HEALTH_TIMEOUT_S = 120.0 # the SSH call of one check (the check bounds itself at node_health.HEALTH_LIMIT_S) +# the previous check of a node that has none: an XID cursor of no boot, so every hardware +# XID of this boot is new (``CudaChecker`` counts the XIDs after a reboot the same way) +JOIN_PREV: Mapping[str, Any] = {"xid": {"boot": None}} +RATE_FRACTION = 0.5 # a job port below this fraction of the island's fastest one is refused + + +@dataclass +class NodeHealth: + """One node's health for the join: ``state`` ``ok`` / ``bad`` / ``unread`` / + ``unchecked``; ``text``: what to say after ``node ``; ``rates``: its job ports' + rates (Gb/s; a multi-node island).""" + + state: str + text: str = "" + rates: dict[str, float] = field(default_factory=dict) @dataclass class JoinCheck: refusals: list[str] = field(default_factory=list) notes: list[str] = field(default_factory=list) + warnings: list[str] = field(default_factory=list) + nodes: list[str] = field(default_factory=list) # the nodes the island takes (passed) + health: dict[str, NodeHealth] = field(default_factory=dict) # by node name (a recheck reuses it) @property def ok(self) -> bool: @@ -56,6 +92,38 @@ def inventory_of(argv: Sequence[str]) -> str | None: return found +def without_inventory(argv: Sequence[str]) -> list[str]: + """``argv`` without its ``--rl-node-inventory`` flags.""" + out, skip = [], False + for arg in argv: + if skip: + skip = False + continue + if arg == INVENTORY_FLAG: + skip = True + continue + if str(arg).startswith(INVENTORY_FLAG + "="): + continue + out.append(arg) + return out + + +def island_env_of(argv: Sequence[str]) -> dict[str, str]: + """The ``--island-env KEY=VALUE`` items of a launch argv (the last of a key wins): the + island's own environment, which an ``ssh:`` island exports after the node's ``env``.""" + out: dict[str, str] = {} + for i, arg in enumerate(argv): + item = None + if arg == ISLAND_ENV_FLAG and i + 1 < len(argv): + item = str(argv[i + 1]) + elif str(arg).startswith(ISLAND_ENV_FLAG + "="): + item = str(arg).split("=", 1)[1] + if item and "=" in item: + key, value = item.split("=", 1) + out[key.strip()] = value + return out + + def island_nodes(argv: Sequence[str], gpu: str) -> tuple[Any, int, str | None]: """``(trainer nodes, nodes the island needs, inventory path)`` of an ``ssh:`` island's launch argv; raises ValueError naming what is wrong.""" @@ -69,11 +137,39 @@ def island_nodes(argv: Sequence[str], gpu: str) -> tuple[Any, int, str | None]: path = inventory_of(argv) if path is None: raise ValueError(f"an ssh: island needs its node inventory ({INVENTORY_FLAG}; the inventory option " - "of yeto fleet island add)") + "of yeto fleet island add / move)") return role_nodes(load_inventory(path), "trainer"), int(spec.num_nodes), path -# -- the three checks (their modules: yeto.hw.node_health, fabric_groups, node_lease) ------------ +def node_keys(node: Any) -> set[str]: + """What names the node's machine: its name, and its SSH target (without ``user@``) and + ``address`` in lower case.""" + keys = {f"name:{node.name}"} + for value in (str(getattr(node, "host", "") or "").rpartition("@")[2], getattr(node, "address", None)): + value = str(value or "").strip().lower() + if value: + keys.add(f"host:{value}") + return keys + + +def own_lease(holder: str | None, run_id: str) -> bool: + """``holder`` is the island's own launch (```` or ``-m`` after a + move), as a trainer.""" + if not holder: + return False + from .node_lease import run_of # noqa: PLC0415 + + run = run_of(holder) or "" + part = str(holder).split("@", 1)[0].rpartition("/")[2] + return part == "trainer" and re.fullmatch(rf"{re.escape(str(run_id))}(-m\d+)?", run) is not None + + +def island_of_lease(holder: str | None, islands: Mapping[str, str]) -> str | None: + """The fleet island (``islands``: launch prefix -> island) whose launch holds the lease.""" + return next((name for prefix, name in islands.items() if own_lease(holder, prefix)), None) + + +# -- the modules of the checks (yeto.hw.node_health, fabric_groups, node_lease) --------------------- def _checker_for(node: Any) -> Any: """The node's health checker, built as the island's own launch builds it (ssh_resident).""" @@ -83,6 +179,7 @@ def _checker_for(node: Any) -> Any: fabric = getattr(node, "fabric", None) return checker_for(node.device_family, expect_gpus=getattr(node, "cards_per_node", None), + min_ib_gbps=getattr(node, "min_ib_gbps", None), fabric=fabric if fabric in RDMA_FABRICS else None) @@ -92,55 +189,151 @@ def _check_placement(nodes: Sequence[Any], need: int, inventory: Sequence[Any] | return check_placement(nodes, need, inventory=inventory) +def _pick_placement(nodes: Sequence[Any], need: int, inventory: Sequence[Any] | None) -> list[Any]: + """``need`` of ``nodes`` as the launch's lease pick places them; raises PlacementError.""" + from .fabric_groups import pick_placement # noqa: PLC0415 + + return list(pick_placement(nodes, need, inventory=inventory).nodes) + + +def _grouped(inventory: Sequence[Any]) -> bool: + from .fabric_groups import grouped # noqa: PLC0415 + + return grouped(inventory) + + def _node_leases(store_uri: str, run_id: str) -> Any: from .node_lease import NodeLeases # noqa: PLC0415 return NodeLeases(store_uri, f"{run_id}/trainer") # read only: who holds each node -def _hcas(node: Any) -> list[str]: +def _hcas(node: Any, env: Mapping[str, str] | None = None) -> list[str]: + """The job's ``NCCL_IB_HCA`` on the node: the island's environment over the node's (as + the launch exports them, ``ssh_resident``).""" from yeto.hw.node_health import hcas_of # noqa: PLC0415 - return list(hcas_of((getattr(node, "env", None) or {}).get("NCCL_IB_HCA"))) + merged = {**dict(getattr(node, "env", None) or {}), **dict(env or {})} + return list(hcas_of(merged.get("NCCL_IB_HCA"))) -def _lease_run(holder: str) -> str: - from .node_lease import run_of # noqa: PLC0415 +# -- health --------------------------------------------------------------------------------------- - return run_of(holder) or str(holder) +def _absolute(result: Any) -> list[str]: + """What a first check cannot see as a change but a node joining must not have: a + volatile uncorrectable ECC count above 0, an NVSwitch node whose fabric manager is not + active (the checker's facts).""" + facts = result.facts or {} + bus = dict(facts.get("bus") or {}) + out = [f"GPU {bus.get(key, key)} uncorrectable ECC {count} (volatile)" + for key, count in sorted((facts.get("ecc") or {}).items(), key=lambda kv: str(bus.get(kv[0], kv[0]))) + if count is not None and int(count) > 0] + if facts.get("fabric") not in (None, "none") and facts.get("fm") != "active": # NVSwitch GPUs: the FM runs + out.append(f"nvidia-fabricmanager {facts.get('fm') or 'not running'} on an NVSwitch node") + return out -def check_health(nodes: Sequence[Any], *, multi: bool, ssh: Any, out: JoinCheck) -> None: +def _job_rates(text: str, hcas: Sequence[str], fabric: str | None) -> dict[str, float]: + """The rates of the job's active ports (``NCCL_IB_HCA``, else the fabric's link layer), + read by the preflight's parsers (``yeto.hw.host_probe``).""" + from yeto.hw.host_probe import ( # noqa: PLC0415 + hca_filter, + link_layer_ports, + natural_order, + parse_sections, + ports_of, + section_ok, + ) + + sections = parse_sections(text) + if not (section_ok(sections.get("ibstat")) or section_ok(sections.get("ibv_devinfo"))): + return {} + ports = natural_order(ports_of(sections)) + if hcas: + picked, _ = hca_filter(",".join(hcas), ports) + elif fabric: + picked = link_layer_ports(ports, fabric) + else: + picked = [] + return {(p.ca if p.port == 1 else f"{p.ca}:{p.port}"): float(p.rate_gbps) + for p in natural_order(picked) if p.active and p.rate_gbps} + + +def read_health(node: Any, *, multi: bool, ssh: Any, env: Mapping[str, str] | None = None) -> NodeHealth: + """One node's health check (module doc), as :class:`NodeHealth`.""" + if getattr(node, "node_health", None) == "off": + return NodeHealth("unchecked", "node_health off in the inventory: its health is not checked") + try: + checker = _checker_for(node) + if not getattr(checker, "enabled", True): + return NodeHealth("unchecked", f"no health check for device family {node.device_family}") + hcas = _hcas(node, env) if multi else [] + done = ssh.run(node, checker.script(hcas), timeout=HEALTH_TIMEOUT_S) + except Exception as error: # noqa: BLE001 - named in the refusal + return NodeHealth("unread", f"its health check could not run ({type(error).__name__}: {error})"[:300]) + if done.returncode != 0: + last = [line for line in str(done.stderr or "").splitlines() if line.strip()][-1:] + return NodeHealth("unread", f"its health check did not answer (ssh exit {done.returncode}" + + (f": {last[0].strip()}" if last else "") + ")") + text = str(done.stdout or "") + result = checker.parse(text, hcas, dict(JOIN_PREV)) + if not result.checked: + return NodeHealth("unread", "its health check did not read (" + + ("; ".join(result.reasons) or "no reason given") + ")") + ok = result.ok(multi) + reasons = (list(result.job_reasons(multi)) if ok is False else []) + _absolute(result) + if reasons: + return NodeHealth("bad", "is not healthy: " + "; ".join(dict.fromkeys(reasons))) + if ok is None: # the GPUs pass, the job's ports did not read (multi-node) + return NodeHealth("unread", "its health check did not read (" + ("; ".join(result.reasons) or "unknown") + + ")") + rates = _job_rates(text, hcas, getattr(checker, "fabric", None)) if multi else {} + return NodeHealth("ok", rates=rates) + + +def judge_rates(nodes: Sequence[Any], health: dict[str, NodeHealth]) -> None: + """A multi-node island's job port rates (in place): on a node without ``min_ib_gbps`` + (its checker holds the ports to that one), a port below half the fastest job port of + ``nodes`` makes the node bad.""" + fastest = max((r for n in nodes for r in (health.get(n.name) or NodeHealth("")).rates.values()), default=None) for node in nodes: - if getattr(node, "node_health", None) == "off": - out.notes.append(f"node {node.name}: node_health off in the inventory: its health is not checked") + h = health.get(node.name) + # a node with min_ib_gbps: its checker held its ports to it already (CudaChecker) + if h is None or h.state != "ok" or not h.rates or getattr(node, "min_ib_gbps", None) is not None: continue - try: - checker = _checker_for(node) - if not getattr(checker, "enabled", True): - out.notes.append(f"node {node.name}: no health check for device family {node.device_family}") - continue - hcas = _hcas(node) if multi else [] - done = ssh.run(node, checker.script(hcas), timeout=HEALTH_TIMEOUT_S) - except Exception as error: # noqa: BLE001 - named in the refusal - out.refusals.append(f"node {node.name}: its health check could not run ({type(error).__name__}: " - f"{error})"[:300]) + if fastest is None: continue - if done.returncode != 0: - last = [line for line in str(done.stderr or "").splitlines() if line.strip()][-1:] - out.refusals.append(f"node {node.name}: its health check did not answer (ssh exit {done.returncode}" - + (f": {last[0].strip()}" if last else "") + ")") - continue - result = checker.parse(str(done.stdout or ""), hcas, None) - if not result.checked: - out.notes.append(f"node {node.name}: no health check for device family {node.device_family}") + base = float(fastest) * RATE_FRACTION + slow = [f"{label} rate {rate:g} < {base:g} Gb/s (half the fastest job port of the island's nodes, " + f"{fastest:g} Gb/s)" for label, rate in h.rates.items() if rate < base * 0.999] + if slow: + health[node.name] = NodeHealth("bad", "is not healthy: " + "; ".join(slow), h.rates) + + +def check_health(nodes: Sequence[Any], *, multi: bool, ssh: Any, out: JoinCheck, + env: Mapping[str, str] | None = None, cache: Mapping[str, NodeHealth] | None = None) -> None: + """The health of ``nodes`` into ``out.health`` (a node in ``cache`` is not checked again).""" + for node in nodes: + if node.name in out.health: continue - ok, reasons = result.ok(multi), result.job_reasons(multi) # a single-node island: its GPU reasons - if ok is False: - out.refusals.append(f"node {node.name} is not healthy: {'; '.join(reasons) or 'no reason given'}") - elif ok is None: - out.notes.append(f"node {node.name}: its health could not be judged ({'; '.join(result.reasons)})") + cached = (cache or {}).get(node.name) + out.health[node.name] = cached if cached is not None else read_health(node, multi=multi, ssh=ssh, env=env) + if multi: + judge_rates(nodes, out.health) + +def _health_problem(name: str, h: NodeHealth, *, force: bool, out: JoinCheck) -> str | None: + """The problem a node's health makes (None: none); notes and warnings into ``out``.""" + if h.state == "unchecked": + out.notes.append(f"node {name}: {h.text}") + return None + if h.state == "unread" and force: + out.warnings.append(f"node {name}: {h.text}; --force: it joins unchecked") + return None + return None if h.state == "ok" else f"node {name} {h.text}" if h.state == "bad" else f"node {name}: {h.text}" + + +# -- fabric and leases ---------------------------------------------------------------------------- def check_fabric(nodes: Sequence[Any], need: int, out: JoinCheck, *, inventory: Sequence[Any] | None = None) -> None: """``inventory``: the whole inventory (whether it declares fabric groups at all).""" @@ -151,57 +344,152 @@ def check_fabric(nodes: Sequence[Any], need: int, out: JoinCheck, *, inventory: out.notes.append(f"fabric: {message}") -def check_leases(nodes: Sequence[Any], *, lease_store: str | None, run_id: str, out: JoinCheck) -> None: - if not lease_store: - out.notes.append("no lease_store in the inventory: whether another run uses these nodes is not checked") - return +def lease_holders(nodes: Sequence[Any], *, lease_store: str, run_id: str, + out: JoinCheck) -> dict[str, str | None] | None: + """Who holds each node's lease (None: the store did not read: refused into ``out``).""" try: leases = _node_leases(lease_store, run_id) except Exception as error: # noqa: BLE001 out.refusals.append(f"lease store {lease_store}: {type(error).__name__}: {error}"[:300]) - return + return None + holders: dict[str, str | None] = {} for node in nodes: try: - holder = leases.holder(node) + holders[node.name] = leases.holder(node) except Exception as error: # noqa: BLE001 - unknown is not free out.refusals.append(f"node {node.name}: its lease does not read ({type(error).__name__}: {error})"[:300]) - continue - run = None if holder is None else _lease_run(holder) - # the island's own launch leases as [-m]/trainer: a lease of it is its own - if run is not None and run != run_id and not run.startswith(f"{run_id}-m"): - out.refusals.append(f"node {node.name} is leased to run {run}") + return None if len(holders) < len(nodes) else holders + + +def lease_problem(holder: str | None, *, run_id: str, islands: Mapping[str, str]) -> str | None: + """Why a node held by ``holder`` is not the island's (None: free, or its own).""" + if holder is None or own_lease(holder, run_id): + return None + island = island_of_lease(holder, islands) + if island is not None: + return f"is island {island}'s (its launch holds the lease)" + from .node_lease import run_of # noqa: PLC0415 + + return f"is leased to run {run_of(holder) or holder}" + + +def check_leases(nodes: Sequence[Any], *, lease_store: str | None, run_id: str, out: JoinCheck, + islands: Mapping[str, str] | None = None) -> None: + """Every one of ``nodes`` free for the island (or its own) in ``lease_store``.""" + if not lease_store: + out.notes.append("no lease_store in the inventory: whether another run uses these nodes is not checked") + return + holders = lease_holders(nodes, lease_store=lease_store, run_id=run_id, out=out) + for node in nodes if holders is not None else (): + why = lease_problem(holders[node.name], run_id=run_id, islands=islands or {}) + if why: + out.refusals.append(f"node {node.name} {why}") +# -- the check ------------------------------------------------------------------------------------ + def check(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str | None = None, - taken: Mapping[str, str] | None = None, ssh: Any = None, - inventory: Sequence[Any] | None = None) -> JoinCheck: - """The checks of a new island's trainer ``nodes`` (module doc). ``taken``: node name or SSH - target -> the fleet island that trains on it; ``inventory``: the whole inventory (default - ``nodes``).""" + taken: Mapping[str, str] | None = None, islands: Mapping[str, str] | None = None, ssh: Any = None, + inventory: Sequence[Any] | None = None, env: Mapping[str, str] | None = None, force: bool = False, + health: Mapping[str, NodeHealth] | None = None) -> JoinCheck: + """The checks of a new island's trainer ``nodes`` (module doc). ``taken``: a node key + (:func:`node_keys`) -> the fleet island whose inventory lists it (an inventory without + ``lease_store``); ``islands``: the fleet's other islands' launch prefix -> island (whose + leases are theirs); ``inventory``: the whole inventory (default ``nodes``); ``env``: the + island's own environment; ``force``: a check that does not read is a warning; + ``health``: node health already read (a recheck).""" out = JoinCheck() + if ssh is None: + from .ssh_trainer_island import SshOps # noqa: PLC0415 + + ssh = SshOps() + every = list(nodes if inventory is None else inventory) + if not lease_store: + _check_listed(nodes, need=need, taken=taken or {}, ssh=ssh, env=env, force=force, health=health, out=out, + inventory=every) + else: + _check_leased(nodes, need=need, run_id=run_id, lease_store=lease_store, islands=islands or {}, ssh=ssh, + env=env, force=force, health=health, out=out, inventory=every) + if out.refusals: + out.nodes = [] + return out + + +def _check_listed(nodes: Sequence[Any], *, need: int, taken: Mapping[str, str], ssh: Any, env: Any, force: bool, + health: Any, out: JoinCheck, inventory: Sequence[Any]) -> None: + """An inventory without ``lease_store``: its trainer nodes are the island's.""" if len(nodes) != need: out.refusals.append(f"the island needs {need} trainer node(s); its inventory lists {len(nodes)} " f"{[n.name for n in nodes]}") - return out + return for node in nodes: - owner = (taken or {}).get(node.name) or (taken or {}).get(getattr(node, "host", None) or "") + owner = next((taken[k] for k in sorted(node_keys(node)) if k in taken), None) if owner: out.refusals.append(f"node {node.name} is island {owner}'s") - if ssh is None: - from .ssh_trainer_island import SshOps # noqa: PLC0415 - - ssh = SshOps() - check_health(nodes, multi=need > 1, ssh=ssh, out=out) + check_health(nodes, multi=need > 1, ssh=ssh, out=out, env=env, cache=health) + for node in nodes: + problem = _health_problem(node.name, out.health[node.name], force=force, out=out) + if problem: + out.refusals.append(problem) try: check_fabric(nodes, need, out, inventory=inventory) except Exception as error: # noqa: BLE001 - the check that cannot run refuses out.refusals.append(f"fabric: the placement check could not run ({type(error).__name__}: {error})"[:300]) - check_leases(nodes, lease_store=lease_store, run_id=run_id, out=out) - return out + check_leases(nodes, lease_store=None, run_id="", out=out) + out.nodes = [n.name for n in nodes] + + +def _check_leased(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str, islands: Mapping[str, str], + ssh: Any, env: Any, force: bool, health: Any, out: JoinCheck, inventory: Sequence[Any]) -> None: + """An inventory with ``lease_store``: ``need`` of its trainer nodes, as the launch picks them.""" + if len(nodes) < need: + out.refusals.append(f"the island needs {need} trainer node(s); its inventory lists {len(nodes)} " + f"{[n.name for n in nodes]}") + return + holders = lease_holders(nodes, lease_store=lease_store, run_id=run_id, out=out) + if holders is None: + return + held = {n.name: why for n in nodes if (why := lease_problem(holders[n.name], run_id=run_id, islands=islands))} + # the launch's order: the nodes its own launch holds, then the free ones (lease_trainer_nodes) + ours = [n for n in nodes if n.name not in held and holders[n.name] is not None] + usable = ours + [n for n in nodes if n.name not in held and n not in ours] + check_health(usable, multi=need > 1, ssh=ssh, out=out, env=env, cache=health) + sick = {} + for node in usable: + problem = _health_problem(node.name, out.health[node.name], force=force, out=out) + if problem: + sick[node.name] = problem + left_out = [f"node {n.name} {held[n.name]}" if n.name in held else sick[n.name] + for n in nodes if n.name in held or n.name in sick] + grouped = need > 1 and _grouped(inventory) + if need > 1 and not grouped: + from .fabric_groups import HINT # noqa: PLC0415 + + out.notes.append(f"fabric: {HINT}") + try: + chosen = _pick_placement([n for n in usable if n.name not in sick], need, inventory) + except Exception as error: # noqa: BLE001 - no fit (PlacementError), or the check that cannot run + fit = type(error).__name__ == "PlacementError" + out.refusals += left_out + [(f"fabric: {error}" if grouped else + f"{len(usable) - len(sick)} of {len(nodes)} trainer node(s) are free and " + f"healthy, {need} needed") if fit else + f"fabric: the placement check could not run ({type(error).__name__}: {error})"] + return + try: # the launch's own pick (leases only): must not take a node found unhealthy + launch = _pick_placement(usable, need, inventory) + except Exception: # noqa: BLE001 - it fits without the sick nodes, so it fits with them + launch = chosen + if bad := [n.name for n in launch if n.name in sick]: + out.refusals += [sick[name] for name in bad] + [ + f"the island's launch picks its nodes by their leases and would take {', '.join(bad)}; take " + "such a node out of the inventory's trainer nodes (roles) or clear its fault"] + return + out.notes += [f"left out: {why}" for why in left_out] + out.nodes = [n.name for n in launch] def taken_nodes(doc: Mapping[str, Any], *, other_than: str, fleet_argv: Sequence[str]) -> dict[str, str]: - """Node name and SSH target -> island, for the ``ssh:`` trainer islands of the desired + """Node key (:func:`node_keys`) -> island, for the ``ssh:`` trainer islands of the desired state other than ``other_than`` (their inventories' trainer nodes).""" from yeto.launch.pool import desired as dz # noqa: PLC0415 @@ -220,23 +508,42 @@ def taken_nodes(doc: Mapping[str, Any], *, other_than: str, fleet_argv: Sequence except Exception as error: # noqa: BLE001 - its nodes unknown: said, not taken as free raise ValueError(f"island {name}'s inventory {path} does not read ({error})") from None for node in nodes: - out.setdefault(node.name, name) - out.setdefault(node.host, name) + for key in node_keys(node): + out.setdefault(key, name) return out +def fleet_prefixes(doc: Mapping[str, Any], *, other_than: str) -> dict[str, str]: + """Launch prefix -> island, for the trainer islands of the desired state other than ``other_than``.""" + from yeto.launch.pool import desired as dz # noqa: PLC0415 + + return {str(m["prefix"]): name for name, m in dz.trainers(dict(doc)).items() + if name != other_than and m.get("prefix")} + + def check_member(member: Mapping[str, Any], doc: Mapping[str, Any], *, fleet_argv: Sequence[str], run_id: str, - ssh: Any = None, log: Callable[[str], None] | None = None) -> JoinCheck: - """:func:`check` of an added island's trainer member (``yeto fleet island add``).""" + ssh: Any = None, log: Callable[[str], None] | None = None, force: bool = False, + health: Mapping[str, NodeHealth] | None = None) -> JoinCheck: + """:func:`check` of an island's trainer member (added, or moved) against the desired + state ``doc`` (its other islands).""" say = log or (lambda m: print(m, file=sys.stderr)) argv = [*fleet_argv, *(member.get("argv") or ())] from .node_inventory import lease_store_of, load_inventory # noqa: PLC0415 nodes, need, path = island_nodes(argv, str(member["gpu"])) inventory = load_inventory(path) - result = check(nodes, need=need, run_id=run_id, lease_store=lease_store_of(inventory), - taken=taken_nodes(doc, other_than=str(member["name"]), fleet_argv=fleet_argv), ssh=ssh, - inventory=inventory) + store = lease_store_of(inventory) + name = str(member["name"]) + result = check(nodes, need=need, run_id=run_id, lease_store=store, + taken=None if store else taken_nodes(doc, other_than=name, fleet_argv=fleet_argv), + islands=fleet_prefixes(doc, other_than=name), ssh=ssh, inventory=inventory, + env=island_env_of(argv), force=force, health=health) for note in result.notes: - say(f"fleet island: note: island {member['name']}: {note}") + say(f"fleet island: note: island {name}: {note}") + for warning in result.warnings: + say(f"fleet island: WARNING: island {name}: {warning}") return result + + +def names(nodes: Iterable[str]) -> str: + return ", ".join(nodes) or "none" diff --git a/yeto/launch/node_inventory.py b/yeto/launch/node_inventory.py index 44f82ffd4..b1c849b9c 100644 --- a/yeto/launch/node_inventory.py +++ b/yeto/launch/node_inventory.py @@ -79,6 +79,10 @@ share one group; a file without any ``fabric_group`` key places islands as before. ``fabric_group: unavailable`` (reserved) marks a node the probe found without RDMA to the others: it never joins a multi-node island, a single-node one takes it. +``min_ib_gbps`` is the least rate (Gb/s) of each port the job's ``NCCL_IB_HCA`` names +on the node: the node health check of a multi-node trainer island (``yeto.hw.node_health``) +and the join check of an island added at run time (:mod:`.island_join`) hold the +ports to it. An NVIDIA (``cuda``) multi-node island over ``ib`` / ``roce``, e.g. 6 x 8 B300 (with ``--model-store local:///data/models --model-store-source s3://...`` the @@ -144,7 +148,7 @@ "host_memory_gib") _KNOWN = _REQUIRED + ("proxy_jump", "fabric", "interface", "address", "mounts", "image", "runtime", "docker_args", "env", "price_per_card_hour", "roles", "scratch", "scratch_min_free_gib", - "store_env_file", "node_health", "fabric_group") + "store_env_file", "node_health", "fabric_group", "min_ib_gbps") NODE_HEALTH_MODES = ("auto", "off") # node profile keys (unified-sampler-pool): parse_profile reads them, parse_node accepts and ignores them _PROFILE_KEYS = ("card_arch", "container", "paths", "model_source", "reach") @@ -240,6 +244,9 @@ class Node: # :mod:`.fabric_groups`); None: no fabric_group key; FABRIC_UNGROUPED (""): the key is # null; FABRIC_UNAVAILABLE: reserved, the node has no RDMA to the others fabric_group: str | None = None + # the least rate (Gb/s) of each port of the job's NCCL_IB_HCA on the node (the node health + # check of a multi-node trainer island, the join check); None: not declared + min_ib_gbps: float | None = None @property def hbm_gib_per_node(self) -> float: @@ -492,6 +499,8 @@ def parse_node(raw: Any, *, index: int, images: Mapping[str, str] | None = None, store_env_file=store_env_file, node_health=parse_node_health(raw["node_health"], f"node {name}") if "node_health" in raw else node_health, fabric_group=fabric_group, + min_ib_gbps=(_require_positive(raw["min_ib_gbps"], name, "min_ib_gbps") + if raw.get("min_ib_gbps") is not None else None), ) try: node.compat_group # noqa: B018 - an unknown HBM variant fails here, not at launch diff --git a/yeto/launch/ssh_resident.py b/yeto/launch/ssh_resident.py index 6b70b20b0..2d80e73b6 100644 --- a/yeto/launch/ssh_resident.py +++ b/yeto/launch/ssh_resident.py @@ -250,6 +250,7 @@ def _health_watches(self, spec: SshTrainerSpec) -> dict[int, Any]: env = {**dict(node.env), **dict(spec.env)} # the job's own order (node_env): the island's wins out[rank] = node_health.HealthWatch(node.device_family, hcas=node_health.hcas_of(env.get("NCCL_IB_HCA")), multi=len(spec.nodes) > 1, expect_gpus=node.cards_per_node, + min_ib_gbps=getattr(node, "min_ib_gbps", None), clock=time.time, every_s=self.health_every_s, fabric=node.fabric if node.fabric in RDMA_FABRICS else None) return out diff --git a/yeto/rl/fleet_islands.py b/yeto/rl/fleet_islands.py index d848c3287..eb66a347f 100644 --- a/yeto/rl/fleet_islands.py +++ b/yeto/rl/fleet_islands.py @@ -23,6 +23,10 @@ cluster); same learner id, same store sub-directory: the next launch continues from ``trainer/``. The syncer sees the island leave and come back (no RETIRE). +An ``ssh:`` island added, or moved onto ``ssh:`` nodes (``--inventory``: its node +inventory), passes the join checks of :mod:`yeto.launch.island_join` first (count, this +fleet, node health, fabric group, leases), and again on the desired state its write reads. + ``--dry-run`` writes nothing: it prints the change and runs the island launch's ``yeto launch --dry-run`` (an island whose layout differs from the fleet's is refused there, before anything is ordered). @@ -147,12 +151,20 @@ def compile_island(cfg: dict[str, Any], plan: Any, *, k: int, name: str, gpu: st if inventory is not None: if not str(gpu).startswith("ssh:"): raise IslandChangeError(f"{where}: --inventory is the node inventory of an ssh: island (--gpu {gpu})") - argv += ["--rl-node-inventory", str(inventory)] + argv += ["--rl-node-inventory", inventory_path(inventory)] member = il.trainer_member(island, plan, argv, prefix=f"{il.fleet_prefix(trainer_argv)}-i{k}", fleet_shape=il.fleet_shape(trainer_argv)) return member, members +def inventory_path(inventory: str) -> str: + """An island's node inventory as its launch reads it: an absolute path (the trainer + worker and a later ``yeto fleet island`` run in other directories).""" + from pathlib import Path # noqa: PLC0415 + + return str(Path(str(inventory)).expanduser().resolve()) + + def run_budget_usd(cfg: dict[str, Any]) -> float | None: """The run's ``run.budget`` in dollars, wherever the run config sets it (``budget.usd`` or the ``breakers`` section), resolved as ``yeto run up`` resolves it; None when off.""" @@ -201,32 +213,58 @@ def remove(doc: dict[str, Any], name: str) -> list[str]: return gone -def move(doc: dict[str, Any], cfg: dict[str, Any], name: str, *, gpu: str, usd_per_h: float | None = None) -> dict: +def move(doc: dict[str, Any], cfg: dict[str, Any], name: str, *, gpu: str, usd_per_h: float | None = None, + inventory: str | None = None) -> dict: """Move island ``name`` to other machines (in place); returns its member. Its price is ``usd_per_h`` when given, else none of its own: the new machines are billed at the unified price table's price for their ``--gpu`` (``trainer_worker.table_usd_per_h``), - never at the old machines' price.""" + never at the old machines' price. ``inventory``: the node inventory of an ``ssh:`` + ``gpu`` (its launch's ``--rl-node-inventory``, in place of the island's own).""" member = trainer_by_name(doc, name) member["gpu"] = fleet_mod._gpu(gpu, f"island {name} --gpu") # noqa: SLF001 member["usd_per_h"] = (None if usd_per_h is None else fleet_mod._price(usd_per_h, f"island {name} --usd-per-h")) # noqa: SLF001 + if inventory is not None: + from yeto.launch import island_join # noqa: PLC0415 + + if not str(member["gpu"]).startswith("ssh:"): + raise IslandChangeError(f"island {name}: --inventory is the node inventory of an ssh: island " + f"(--gpu {member['gpu']})") + member["argv"] = [*island_join.without_inventory([str(a) for a in member.get("argv") or ()]), + "--rl-node-inventory", inventory_path(inventory)] shape = il.fleet_shape([str(a) for a in cfg["fleet"]["trainer_argv"]]) if shape: member["fleet_shape"] = shape # the moved island's layout is checked against the fleet's return member -def join_check(cfg: dict[str, Any], doc: dict[str, Any], member: dict[str, Any], *, ssh: Any = None) -> None: - """An added ``ssh:`` island's nodes (``yeto.launch.island_join``): free in this fleet, - healthy, in one fabric group and not leased to another run; refused naming each problem.""" +def join_check(cfg: dict[str, Any], doc: dict[str, Any], member: dict[str, Any], *, ssh: Any = None, + force: bool = False, first: Any = None) -> Any: + """An ``ssh:`` island's nodes (added, or moved onto; ``yeto.launch.island_join``): + as many as it needs, free in this fleet, healthy, in one fabric group and not leased to + another run; refused naming each problem. Returns the check (its nodes, its health). + + ``first``: the check before the desired state was read again (the write's retry, + another ``add`` that claimed this island's learner id meanwhile): its node health is + kept, the rest (the other islands' nodes, the leases under the member's prefix now) is + checked again on ``doc``.""" from yeto.launch import island_join # noqa: PLC0415 fleet_argv = [str(a) for a in cfg["fleet"]["trainer_argv"]] - # a node leased by the island's own launch (its member prefix) is its own - result = island_join.check_member(member, doc, fleet_argv=fleet_argv, run_id=str(member["prefix"]), ssh=ssh) + # a node leased by the island's own launch (its member prefix, -m after a move) is its own + result = island_join.check_member(member, doc, fleet_argv=fleet_argv, run_id=str(member["prefix"]), ssh=ssh, + force=force, health=None if first is None else first.health, + log=None if first is None else (lambda m: None)) if not result.ok: - raise IslandChangeError(f"island {member['name']}'s nodes cannot join: " + "; ".join(result.refusals)) - print(f"fleet island: island {member['name']}'s nodes pass the join checks (health, fabric group, lease)") + again = "" if first is None else " (checked again on the desired state now)" + raise IslandChangeError(f"island {member['name']}'s nodes cannot join{again}: " + "; ".join(result.refusals)) + if first is None: + print(f"fleet island: island {member['name']} takes nodes {island_join.names(result.nodes)}; its nodes pass " + "the join checks (health, fabric group, lease)") + elif result.nodes != first.nodes: + print(f"fleet island: island {member['name']} takes nodes {island_join.names(result.nodes)} now (the " + "desired state changed since its check)") + return result # -- the launch's own dry run ------------------------------------------------------------------- @@ -326,6 +364,13 @@ def add_parser(fsub: Any) -> None: m.add_argument("--name", required=True) m.add_argument("--gpu", required=True) m.add_argument("--usd-per-h", type=float, default=None) + m.add_argument("--inventory", default=None, metavar="PATH", + help="an ssh: --gpu's node inventory (its trainer nodes), in place of the island's own; they are " + "checked first as for add") + for q in (a, m): + q.add_argument("--force", action="store_true", + help="an ssh: island whose node health check does not read joins anyway (a WARNING); " + "a node found unhealthy is still refused") for q in (a, r, m): q.add_argument("--config", required=True, help="the run config") q.add_argument("--dry-run", action="store_true", help="show the change and dry-run the launch; write nothing") @@ -344,7 +389,7 @@ def main(args: Any, *, prepare: Callable[[Any], None] | None = None) -> int: for m in doc.get("members") or (): for key in dz.ONE_SHOT: m.pop(key, None) - launch_member = previous = None + launch_member = previous = joined = None if args.island_command == "add": unpriced_under_budget(run.cfg, args.gpu, args.usd_per_h) with open(args.samplers) as fh: @@ -357,13 +402,16 @@ def main(args: Any, *, prepare: Callable[[Any], None] | None = None) -> int: add(doc, member, pools) launch_member = member if str(member["gpu"]).startswith("ssh:"): - join_check(run.cfg, current, member) + joined = join_check(run.cfg, current, member, force=args.force) elif args.island_command == "remove": remove(doc, args.name) else: unpriced_under_budget(run.cfg, args.gpu, args.usd_per_h) previous = copy.deepcopy(trainer_by_name(doc, args.name)) - launch_member = move(doc, run.cfg, args.name, gpu=args.gpu, usd_per_h=args.usd_per_h) + launch_member = move(doc, run.cfg, args.name, gpu=args.gpu, usd_per_h=args.usd_per_h, + inventory=args.inventory) + if str(launch_member["gpu"]).startswith("ssh:"): # the machines it moves onto: as for add + joined = join_check(run.cfg, current, launch_member, force=args.force) doc = dz.validate(doc) for line in changes(current, doc): print(f"fleet island: {line}") @@ -397,11 +445,17 @@ def main(args: Any, *, prepare: Callable[[Any], None] | None = None) -> int: def change(fresh: dict[str, Any]) -> None: if args.island_command == "add": + before = copy.deepcopy(fresh) add(fresh, member_now, pools) + moved = member_now elif args.island_command == "remove": remove(fresh, args.name) + return else: - move(fresh, run.cfg, args.name, gpu=args.gpu, usd_per_h=args.usd_per_h) + before = copy.deepcopy(fresh) + moved = move(fresh, run.cfg, args.name, gpu=args.gpu, usd_per_h=args.usd_per_h, inventory=args.inventory) + if joined is not None: # the other islands and the leases as they are now (an add may have run meanwhile) + join_check(run.cfg, before, moved, force=args.force, first=joined) try: written = store.update(change, note=f"fleet island {args.island_command} {args.name}", attempts=3) From 480d72bcd66d9d4085cfad867f02ec44e5de435f Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 00:12:17 +0800 Subject: [PATCH 12/13] island join: other lease stores by inventory, the launch's pick after a move, unread kernel log - with lease_store, islands whose inventory has no lease_store or another one still take their nodes out (by name, SSH target, address) - the launch's pick is predicted without own nodes (a new holder): the free nodes, then the free and the earlier incarnation's nodes in inventory order; either pick taking an unhealthy node refuses - min_ib_gbps without NCCL_IB_HCA holds every active port of the fabric (the cuda checker, so a running island too) - an unreadable kernel log (xid source none) and a timed-out NVLink fabric or fabric manager are read failures (refused, --force warns) - the relative rate rule compares nodes of one fabric group; a recheck at the write prints its new notes and warnings; an Xid refusal says what to do - docs: the window of two adds on one lease store, the NVL72 fabric manager limit Co-Authored-By: Claude Opus 5.5 --- docs/NODE_RUNTIME.md | 2 +- docs/OWN_CLUSTERS.md | 25 +++- tests/test_island_join.py | 166 ++++++++++++++++++++++++- tests/test_own_clusters_islands_doc.py | 6 +- yeto/hw/node_health.py | 8 +- yeto/launch/island_join.py | 159 ++++++++++++++++------- yeto/rl/fleet_islands.py | 2 +- 7 files changed, 311 insertions(+), 57 deletions(-) diff --git a/docs/NODE_RUNTIME.md b/docs/NODE_RUNTIME.md index 860aa8ace..d6fffe950 100644 --- a/docs/NODE_RUNTIME.md +++ b/docs/NODE_RUNTIME.md @@ -278,7 +278,7 @@ One shell call reads, in this order: | ECC | the same query | the volatile uncorrectable ECC count grew since the previous check (a count that went down is the new baseline) | | NVLink fabric | the `Fabric` blocks of `nvidia-smi -q` | a GPU that has a fabric state is not `Completed/Success` (a PCIe card's `N/A` passes) | | fabric manager | `systemctl is-active nvidia-fabricmanager` | it was active and is now `inactive` or `failed` (a node without NVSwitch, never active, passes) | -| IB / RoCE ports | `ibstat` (`ibv_devinfo -v` only when ibstat fails) | a port named by `NCCL_IB_HCA` is missing, not `Active`, or slower than the node's `min_ib_gbps` in the inventory (without it: than at the first check) | +| IB / RoCE ports | `ibstat` (`ibv_devinfo -v` only when ibstat fails) | a port named by `NCCL_IB_HCA` is missing, not `Active`, or slower than the node's `min_ib_gbps` in the inventory (without it: than at the first check); without `NCCL_IB_HCA`, no port of the fabric is active, or, with `min_ib_gbps`, an active one is slower | The XIDs and the ECC count only count from the second check on. What the kernel log holds at the first check is history: the preflight judged the node then. The nodes of diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 0347debe9..5353f619a 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -602,22 +602,35 @@ nodes and prints the nodes the island takes: | Check | Refused when | |---|---| | Count | Without `lease_store`: the inventory does not list as many trainer nodes as `--gpu` says. With `lease_store` it may list more, as for a launch: the island takes as many as it needs of the free, healthy ones (below). | -| In this fleet | Without `lease_store`: a node is a trainer node of another `ssh:` island of the fleet: the same name, or the same machine (its SSH target without `user@`, or its `address`, in any case). With `lease_store`: another island's launch holds the node's lease. | -| Health | One SSH call per node runs the node health check of its device family, the check the island's launch runs while it trains. A node joining has no earlier check to compare with, so it is judged on absolute rules: a hardware Xid in the kernel log of this boot, a volatile uncorrectable ECC count above 0, NVSwitch GPUs whose `nvidia-fabricmanager` is not `active`, fewer GPUs than `cards_per_node`, an NVLink fabric not `Completed`. A multi-node island also needs every `NCCL_IB_HCA` port `Active` (the island's own `--island-env` value wins over the node's `env`), at no less than the node's `min_ib_gbps` when the inventory sets it, else at no less than half the fastest of these ports on the island's nodes. A check that does not read (no answer, `nvidia-smi` timed out, a check still stuck on the node, an output cut off, the IB tools unread) is refused; with `--force` it is a WARNING and the node joins. A node found unhealthy is refused with `--force` too. A device family without a health check, or a node with `node_health: off`, is a note. | +| In this fleet | A node is a trainer node of another `ssh:` island whose inventory has no `lease_store`, or another one: the same name, or the same machine (its SSH target without `user@`, or its `address`, in any case). For an island on the same `lease_store`, its launch's lease says which nodes it holds. | +| Health | One SSH call per node runs the node health check of its device family, the check the island's launch runs while it trains. A node joining has no earlier check to compare with, so it is judged on absolute rules: a hardware Xid in the kernel log of this boot, a volatile uncorrectable ECC count above 0, NVSwitch GPUs whose `nvidia-fabricmanager` is not `active`, fewer GPUs than `cards_per_node`, an NVLink fabric not `Completed`. A multi-node island also needs its ports `Active`: those of `NCCL_IB_HCA` (the island's own `--island-env` value wins over the node's `env`), else the fabric's ports that NCCL takes. Each port runs at no less than the node's `min_ib_gbps` when the inventory sets it; else at no less than half the fastest of these ports on the island's nodes of the same fabric group. A check that does not read is refused: no answer, `nvidia-smi` or the fabric state timed out, a check still stuck on the node, an output cut off, the IB tools unread, or a kernel log the SSH user cannot read (`dmesg` restricted: add the user to the `adm` or `systemd-journal` group). With `--force` such a check is a WARNING and the node joins. A node found unhealthy is refused with `--force` too. A device family without a health check, or a node with `node_health: off`, is a note. | | Fabric group | The inventory declares `fabric_group` and no one group holds the island's nodes. An inventory without any `fabric_group` only gets a note. | | Lease | The inventory's `lease_store` shows a node leased to another run, or to another island of this fleet. A lease of the island's own launch (`/trainer`, or `-m/trainer` after a move) is not a refusal. A lease that does not read is refused. Without `lease_store` this is not checked, and a note says so. | With `lease_store`, the nodes held by another run or island and the unhealthy ones are left out, and the island's nodes are placed in the rest as its launch places them (one fabric group in a grouped inventory, else in the inventory's order). When too few are -left, the refusal names each node left out and why. The launch itself picks by leases -only, so a pick of the launch that would take a node found unhealthy is refused too: -take that node out of the trainer nodes (`roles`) or clear its fault. +left, the refusal names each node left out and why. The launch picks by leases only, under +a holder of its own: after a move, the nodes the island's earlier incarnation holds are not +its own. It takes the free nodes first, and waits for the earlier incarnation's nodes only +when there are too few. A pick of the launch, either way, that would take a node found +unhealthy is refused: take that node out of the trainer nodes (`roles`) or clear its fault. + +Limits: + +- Two adds on one `lease_store` that run before either island launches see no lease of + the other, so both may list the same nodes. Their launches then take the leases one + after the other: the later one waits for free nodes, up to `--rl-node-lease-wait-s` + (3600 s by default), and fails after that. Add the next island once the previous one + runs, or give the islands inventories without shared nodes. +- On GB200 / GB300 NVL72 racks the NVLink fabric is managed outside the compute tray (on + the NVSwitch trays), so `nvidia-fabricmanager` is not active on the node. The health + check refuses such a node; set `node_health: off` on it and rely on `yeto preflight`. A refusal exits 2, names every problem, and writes nothing. No learner id is claimed: ```text -fleet island: refused: island north's nodes cannot join: node b300-4 is leased to run other-run; node b300-5 is not healthy: GPU 5 XID 79; 0 of 2 trainer node(s) are free and healthy, 2 needed +fleet island: refused: island north's nodes cannot join: node b300-4 is leased to run other-run; node b300-5 is not healthy: GPU 5 XID 79 (a hardware Xid in the kernel log of this boot: fix the GPU and reboot the node, a new boot starts a new log, then add the island again); 0 of 2 trainer node(s) are free and healthy, 2 needed ``` The checks run again when the island is written, on the desired state then: another diff --git a/tests/test_island_join.py b/tests/test_island_join.py index 3b6ea4bbc..36130d8f0 100644 --- a/tests/test_island_join.py +++ b/tests/test_island_join.py @@ -96,7 +96,7 @@ def test_healthy_nodes_join_with_one_bounded_check_each(tmp_path): @pytest.mark.parametrize(("text", "why"), [ - (XID_79, "GPU 5 XID 79"), + (XID_79, "GPU 5 XID 79" + ij.XID_HINT), (ECC_5, "GPU 2 uncorrectable ECC 5 (volatile)"), (FM_DOWN, "nvidia-fabricmanager inactive on an NVSwitch node"), (node_text(gpus=(0, gpus_text(n=7))), "7 of 8 GPUs visible"), @@ -158,7 +158,7 @@ def test_ib_tools_unread_refuse_a_multi_node_island_unless_forced(tmp_path): def test_force_never_lets_an_unhealthy_node_join(tmp_path): assert _check(_nodes(tmp_path), Ssh({"b300-5": XID_79}), force=True).refusals == [ - "node b300-5 is not healthy: GPU 5 XID 79"] + "node b300-5 is not healthy: GPU 5 XID 79" + ij.XID_HINT] def test_a_node_that_does_not_answer_is_refused(tmp_path): @@ -311,7 +311,7 @@ def test_a_shared_inventory_with_one_node_leased_and_one_unhealthy_is_refused(tm assert out.refusals == ["node b300-0 is island north's (its launch holds the lease)", "node b300-1 is island north's (its launch holds the lease)", "node b300-2 is leased to run other-run", - "node b300-3 is not healthy: GPU 5 XID 79", + "node b300-3 is not healthy: GPU 5 XID 79" + ij.XID_HINT, "0 of 4 trainer node(s) are free and healthy, 2 needed"] @@ -331,10 +331,139 @@ def test_an_unhealthy_node_the_launch_would_pick_by_its_leases_is_refused(tmp_pa store, nodes = _shared(tmp_path) _hold(store, nodes[0], "other-run/trainer") out = _check(nodes, Ssh({"b300-1": XID_79}), lease_store=store) - assert out.refusals[0] == "node b300-1 is not healthy: GPU 5 XID 79" + assert out.refusals[0] == "node b300-1 is not healthy: GPU 5 XID 79" + ij.XID_HINT assert out.refusals[1].startswith("the island's launch picks its nodes by their leases and would take b300-1") +def test_the_launch_s_pick_after_a_move_takes_no_node_as_its_own(tmp_path): + """After a move the launch runs as ``r-i2-m1/trainer@``: the nodes the island's + earlier incarnation (``r-i2``) holds are not its own, so it takes the free ones in the + inventory's order, as the real ``pick_nodes`` does, and the check judges that pick.""" + from yeto.launch.node_lease import pick_nodes + + store = str(tmp_path / "leases") + names = ["c-1", "d-2", "a-3", "b-4"] + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", names, lease_store=store)) + for node in nodes[2:]: + _hold(store, node, "r-i2/trainer") + launch = NodeLeases(store, "r-i2-m1/trainer", identity="new") + picked = pick_nodes(list(nodes), 2, launch, wait_s=0, sleep=lambda s: None) + assert [n.name for n in picked] == ["c-1", "d-2"] + for node in picked: + launch.release(node) + out = _check(nodes, Ssh({"c-1": XID_79}), lease_store=store) + assert out.refusals[0] == "node c-1 is not healthy: GPU 5 XID 79" + ij.XID_HINT + assert "would take c-1" in out.refusals[-1] + ok = _check(nodes, Ssh({"a-3": XID_79}), lease_store=store) # neither pick takes a-3 + assert ok.ok and ok.nodes == ["c-1", "d-2"] + _hold(store, nodes[1], "other-run/trainer") # one free node: the launch waits for the earlier incarnation's + late = _check(nodes, Ssh({"a-3": XID_79}), lease_store=store) + assert late.refusals[0].startswith("node a-3 is not healthy") and "would take a-3" in late.refusals[-1] + fine = _check(nodes, Ssh(), lease_store=store) + assert fine.ok and fine.nodes == ["c-1", "a-3"] + + +def test_the_free_nodes_are_judged_even_when_the_earlier_incarnation_s_come_first(tmp_path): + """Inventory order [a-1, b-2 (the earlier incarnation's), c-3, d-4 (free)]: the launch takes + c-3 and d-4 while they are free; an unhealthy c-3 refuses although a-1 and b-2 are fine.""" + store = str(tmp_path / "leases") + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["a-1", "b-2", "c-3", "d-4"], lease_store=store)) + for node in nodes[:2]: + _hold(store, node, "r-i2/trainer") + out = _check(nodes, Ssh({"c-3": XID_79}), lease_store=store) + assert not out.ok and "would take c-3" in out.refusals[-1] + ok = _check(nodes, Ssh(), lease_store=store) + assert ok.nodes == ["c-3", "d-4"] + assert ("the island takes c-3, d-4 (free now); were they taken meanwhile, its launch waits for its earlier " + "incarnation's nodes and takes a-1, b-2 (checked too)") in ok.notes + + +def test_a_shared_inventory_also_leaves_out_the_nodes_of_islands_on_other_lease_stores(tmp_path): + store, nodes = _shared(tmp_path) + taken = {k: "north" for n in nodes[:2] for k in ij.node_keys(n)} # an island whose inventory has no store + out = _check(nodes, Ssh(), lease_store=store, taken=taken) + assert out.ok and out.nodes == ["b300-2", "b300-3"] + assert "left out: node b300-0 is island north's" in out.notes + out = _check(nodes, Ssh({"b300-3": XID_79}), lease_store=store, taken=taken) + assert out.refusals[:3] == ["node b300-0 is island north's", "node b300-1 is island north's", + "node b300-3 is not healthy: GPU 5 XID 79" + ij.XID_HINT] + + +def test_min_ib_gbps_without_nccl_ib_hca_holds_the_fabric_s_ports(tmp_path): + """No NCCL_IB_HCA on an ib fabric: NCCL takes the InfiniBand ports; min_ib_gbps holds each + active one (the checker's rule, the same on a running island).""" + nodes = _nodes(tmp_path, env=None, min_ib=400) + out = _check(nodes, Ssh({"b300-4": SLOW, "b300-5": SLOW})) + assert [r.split(": ", 1)[0] for r in out.refusals] == ["node b300-4 is not healthy", "node b300-5 is not healthy"] + assert "mlx5_0 rate 100 < 400 Gb/s" in out.refusals[0] + assert _check(nodes, Ssh()).ok + checker = node_health.checker_for("cuda", expect_gpus=8, min_ib_gbps=400, fabric="ib") + assert "mlx5_7 rate 100 < 400 Gb/s" in checker.parse(SLOW, [], None).reasons + assert checker.parse(SLOW, [], None).ok_single is True # a single-node job: its GPUs only + + +def test_a_rate_of_exactly_half_the_fastest_passes(tmp_path): + half = node_text(ibstat=(0, ibstat_text(rate=200))) + assert _check(_nodes(tmp_path), Ssh({"b300-5": half})).ok + below = node_text(ibstat=(0, ibstat_text(rate=199))) + assert not _check(_nodes(tmp_path), Ssh({"b300-5": below})).ok + + +def test_the_relative_rate_compares_nodes_of_one_fabric_group_only(tmp_path): + store, nodes = _shared(tmp_path, groups={"b300-0": "a", "b300-1": "a", "b300-2": "b", "b300-3": "b"}) + slow_b = {"b300-2": SLOW, "b300-3": SLOW} # group b runs at 100 Gb/s, group a at 400: not compared + out = _check(nodes, Ssh(slow_b), lease_store=store) + assert out.ok and out.nodes == ["b300-0", "b300-1"] + out = _check(nodes, Ssh({"b300-3": SLOW}), lease_store=store) + assert "left out: node b300-3 is not healthy: mlx5_0 rate 100 < 200 Gb/s (half the fastest job port of the " \ + "island's candidate nodes in fabric group b, 400 Gb/s)" in "; ".join(out.notes) + + +def test_one_uncorrectable_ecc_error_refuses(tmp_path): + out = _check(_nodes(tmp_path), Ssh({"b300-4": node_text(gpus=(0, gpus_text(ecc={0: 1})))})) + assert out.refusals == ["node b300-4 is not healthy: GPU 0 uncorrectable ECC 1 (volatile)"] + + +@pytest.mark.parametrize(("over", "why"), [ + ({"xid": (0, xid_text(source="none"))}, ij.XID_UNREAD), + ({"fabric": (124, "")}, "nvidia-smi -q (NVLink fabric) timed out"), + ({"fabricmanager": (124, "")}, "systemctl is-active nvidia-fabricmanager timed out"), +]) +def test_a_kernel_log_or_fabric_that_does_not_read_refuses_unless_forced(tmp_path, over, why): + nodes = _nodes(tmp_path) + out = _check(nodes, Ssh({"b300-4": node_text(**over)})) + assert out.refusals == [f"node b300-4: its health check did not read ({why})"] + assert _check(nodes, Ssh({"b300-4": node_text(**over)}), force=True).ok + + +def test_the_island_s_inventory_wins_over_the_fleet_s(tmp_path): + fleet_inv = _inventory(tmp_path / "fleet.yaml", ["b300-0", "b300-1"]) + island_inv = _inventory(tmp_path / "island.yaml", ["b300-4", "b300-5"]) + member = {"name": "north", "gpu": GPU, "argv": ["--rl-node-inventory", str(island_inv)]} + ssh = Ssh() + out = ij.check_member(member, {"members": []}, fleet_argv=["--rl-node-inventory", str(fleet_inv)], + run_id="r-i2", ssh=ssh, log=lambda m: None) + assert out.ok and out.nodes == ["b300-4", "b300-5"] and ssh.calls == ["b300-4", "b300-5"] + + +def test_a_recheck_prints_only_what_the_first_check_did_not(tmp_path): + inventory = _inventory(tmp_path / "island.yaml", ["b300-4", "b300-5"]) + member = {"name": "north", "gpu": GPU, "argv": ["--rl-node-inventory", str(inventory)]} + lines: list[str] = [] + first = ij.check_member(member, {"members": []}, fleet_argv=[], run_id="r-i2", ssh=Ssh({"b300-4": BUSY}), + force=True, log=lines.append) + assert any("WARNING" in line for line in lines) and any("note:" in line for line in lines) + lines.clear() + ij.check_member(member, {"members": []}, fleet_argv=[], run_id="r-i2", ssh=Ssh(), force=True, + log=lines.append, health=first.health, seen=[*first.notes, *first.warnings]) + assert lines == [] + ij.check_member(member, {"members": []}, fleet_argv=[], run_id="r-i2", ssh=Ssh({"b300-5": BUSY}), force=True, + log=lines.append, seen=[*first.notes, *first.warnings]) + assert lines == ["fleet island: WARNING: island north: node b300-5: its health check did not read (node health " + "check skipped: the previous one still runs (a tool stuck on the node)); --force: it joins " + "unchecked"] + + # -- yeto fleet island add / move ----------------------------------------------------------------- def _add(run_cli, samplers, inventory, *extra, name="north"): @@ -499,6 +628,35 @@ def allocate(objects, **kw): assert "south" not in {m["name"] for m in store.read()["members"]} +@pytest.mark.parametrize("north_store", [None, "l1"]) +def test_an_island_on_another_lease_store_or_none_keeps_its_nodes(fleet_store, wired, tmp_path, capsys, # noqa: F811 + north_store): + """North's inventory has no lease_store (or another one): its nodes are not in south's + lease store, so south's shared inventory leaves them out by the inventory, not by leases.""" + cfg, _objects, _store, run_cli, samplers = fleet_store + south_samplers = samplers.parent / "south.samplers.json" + south_samplers.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) + north = _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"], + lease_store=north_store and str(tmp_path / north_store)) + assert _add(run_cli, samplers, north) == 0 + south = _inventory(tmp_path / "south.yaml", ["b300-4", "b300-5", "b300-6"], lease_store=str(tmp_path / "l2")) + capsys.readouterr() + assert _add(run_cli, south_samplers, south, name="south") == 2 + assert "node b300-4 is island north's; node b300-5 is island north's" in capsys.readouterr().err + + +def test_islands_on_one_lease_store_are_judged_by_their_leases(fleet_store, wired, tmp_path): # noqa: F811 + """North (not launched yet) holds no lease: south may list its nodes; the launches then + wait for each other's leases (docs/OWN_CLUSTERS.md: the window of two adds).""" + cfg, _objects, _store, run_cli, samplers = fleet_store + south_samplers = samplers.parent / "south.samplers.json" + south_samplers.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) + store = str(tmp_path / "l2") + assert _add(run_cli, samplers, _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"], lease_store=store)) == 0 + south = _inventory(tmp_path / "south.yaml", ["b300-4", "b300-5", "b300-6"], lease_store=store) + assert _add(run_cli, south_samplers, south, name="south") == 0 + + def test_move_to_ssh_runs_the_same_join_checks(fleet_store, wired, tmp_path, capsys): # noqa: F811 _cfg, _objects, store, run_cli, samplers = fleet_store diff --git a/tests/test_own_clusters_islands_doc.py b/tests/test_own_clusters_islands_doc.py index 4f1fe5645..1fb133254 100644 --- a/tests/test_own_clusters_islands_doc.py +++ b/tests/test_own_clusters_islands_doc.py @@ -93,6 +93,10 @@ def test_the_refusal_the_section_shows_is_the_command_s(tmp_path): def test_the_section_states_the_join_rules_of_the_code(): text = section() assert "half the fastest" in text and ij.RATE_FRACTION == 0.5 + from yeto.launch.ssh_trainer_island import DEFAULT_NODE_LEASE_WAIT_S + + assert f"({DEFAULT_NODE_LEASE_WAIT_S:.0f} s by default)" in text for word in ("`min_ib_gbps`", "`--force`", "`--island-env`", "`-m/trainer`", "exit 3", - "yeto fleet island move --gpu ssh:"): + "yeto fleet island move --gpu ssh:", "`adm` or `systemd-journal`", "NVL72", "same fabric group", + "`--rl-node-lease-wait-s`"): assert word in text, word diff --git a/yeto/hw/node_health.py b/yeto/hw/node_health.py index f811e7dee..7e4502b4e 100644 --- a/yeto/hw/node_health.py +++ b/yeto/hw/node_health.py @@ -43,7 +43,9 @@ (:data:`HARDWARE_XIDS`) since the previous check, the NVLink fabric is ``Completed/Success`` on every GPU that has one, the fabric manager did not stop; * ``ok_multi``: also every port the job's ``NCCL_IB_HCA`` names exists, is ``Active`` - and runs at no less than its rate at the first check (or ``min_ib_gbps``). False + and runs at no less than its rate at the first check (or ``min_ib_gbps``); without + ``NCCL_IB_HCA``, one of the fabric's ports is active and, with ``min_ib_gbps``, every + active one runs at no less. False whenever ``ok_single`` is; None when the GPUs pass but the job names HCAs and the IB tools did not read (a read failure of the multi-node job: ``IB tools unread``). @@ -543,6 +545,10 @@ def _ports(self, sections: Mapping[str, Any], hcas: Sequence[str], prev: Mapping if not any(p.active for p in picked): down = ", ".join(f"{_port_label(p)} {(p.state or 'unknown').upper()}" for p in picked) or "none found" out.append(f"no active {self.fabric} port ({down})") + elif self.min_ib_gbps is not None: # the inventory's least rate: every active port NCCL may use + out += [f"{_port_label(p)} rate {p.rate_gbps:g} < {self.min_ib_gbps:g} Gb/s" + for p in natural_order(picked) + if p.active and p.rate_gbps is not None and p.rate_gbps < self.min_ib_gbps * 0.999] selected = [] else: selected = [] diff --git a/yeto/launch/island_join.py b/yeto/launch/island_join.py index c738fae26..306a28f00 100644 --- a/yeto/launch/island_join.py +++ b/yeto/launch/island_join.py @@ -55,6 +55,11 @@ # XID of this boot is new (``CudaChecker`` counts the XIDs after a reboot the same way) JOIN_PREV: Mapping[str, Any] = {"xid": {"boot": None}} RATE_FRACTION = 0.5 # a job port below this fraction of the island's fastest one is refused +XID_UNREAD = ("the kernel log does not read (dmesg restricted, no journalctl -k): add the SSH user to the adm or " + "systemd-journal group, or let it run dmesg with sudo") +XID_HINT = (" (a hardware Xid in the kernel log of this boot: fix the GPU and reboot the node, a new boot starts a " + "new log, then add the island again)") +_HARDWARE_XID = re.compile(r"\bXID (\d+)\b") @dataclass @@ -219,7 +224,7 @@ def _hcas(node: Any, env: Mapping[str, str] | None = None) -> list[str]: # -- health --------------------------------------------------------------------------------------- -def _absolute(result: Any) -> list[str]: +def _absolute(result: Any, *, fm_read: bool = True) -> list[str]: """What a first check cannot see as a change but a node joining must not have: a volatile uncorrectable ECC count above 0, an NVSwitch node whose fabric manager is not active (the checker's facts).""" @@ -228,11 +233,29 @@ def _absolute(result: Any) -> list[str]: out = [f"GPU {bus.get(key, key)} uncorrectable ECC {count} (volatile)" for key, count in sorted((facts.get("ecc") or {}).items(), key=lambda kv: str(bus.get(kv[0], kv[0]))) if count is not None and int(count) > 0] - if facts.get("fabric") not in (None, "none") and facts.get("fm") != "active": # NVSwitch GPUs: the FM runs + if fm_read and facts.get("fabric") not in (None, "none") and facts.get("fm") != "active": # NVSwitch: the FM runs out.append(f"nvidia-fabricmanager {facts.get('fm') or 'not running'} on an NVSwitch node") return out +def _unread_parts(text: str, result: Any) -> list[str]: + """The parts of a whole check that the join's absolute rules need and that did not read: + the kernel log (no XID source: ``dmesg`` restricted and no ``journalctl -k``), the NVLink + fabric or the fabric manager timed out.""" + from yeto.hw.host_probe import parse_sections # noqa: PLC0415 + + out = [] + if (result.facts or {}).get("xid_source") == "none": + out.append(XID_UNREAD) + sections = parse_sections(text) + for name in ("fabric", "fabricmanager"): + sec = sections.get(name) + if sec is not None and sec.rc in (124, 137): + tool = "nvidia-smi -q (NVLink fabric)" if name == "fabric" else "systemctl is-active nvidia-fabricmanager" + out.append(f"{tool} timed out") + return out + + def _job_rates(text: str, hcas: Sequence[str], fabric: str | None) -> dict[str, float]: """The rates of the job's active ports (``NCCL_IB_HCA``, else the fabric's link layer), read by the preflight's parsers (``yeto.hw.host_probe``).""" @@ -281,37 +304,53 @@ def read_health(node: Any, *, multi: bool, ssh: Any, env: Mapping[str, str] | No return NodeHealth("unread", "its health check did not read (" + ("; ".join(result.reasons) or "no reason given") + ")") ok = result.ok(multi) - reasons = (list(result.job_reasons(multi)) if ok is False else []) + _absolute(result) + unread = _unread_parts(text, result) + reasons = (list(result.job_reasons(multi)) if ok is False else []) + _absolute( + result, fm_read=not any("nvidia-fabricmanager" in part for part in unread)) if reasons: - return NodeHealth("bad", "is not healthy: " + "; ".join(dict.fromkeys(reasons))) + hint = XID_HINT if any(_HARDWARE_XID.search(r) for r in reasons) else "" + return NodeHealth("bad", "is not healthy: " + "; ".join(dict.fromkeys(reasons)) + hint) if ok is None: # the GPUs pass, the job's ports did not read (multi-node) return NodeHealth("unread", "its health check did not read (" + ("; ".join(result.reasons) or "unknown") + ")") + if unread: # a part the absolute rules need did not read + return NodeHealth("unread", f"its health check did not read ({'; '.join(unread)})") rates = _job_rates(text, hcas, getattr(checker, "fabric", None)) if multi else {} return NodeHealth("ok", rates=rates) -def judge_rates(nodes: Sequence[Any], health: dict[str, NodeHealth]) -> None: +def judge_rates(nodes: Sequence[Any], health: dict[str, NodeHealth], *, inventory: Sequence[Any] | None = None, + candidates: bool = False) -> None: """A multi-node island's job port rates (in place): on a node without ``min_ib_gbps`` (its checker holds the ports to that one), a port below half the fastest job port of - ``nodes`` makes the node bad.""" - fastest = max((r for n in nodes for r in (health.get(n.name) or NodeHealth("")).rates.values()), default=None) + the nodes of its fabric group (one group: an inventory without ``fabric_group``) makes + the node bad. ``candidates``: ``nodes`` are the island's candidates (a shared inventory).""" + by_group: dict[str, list[Any]] = {} + grouped = _grouped(list(nodes if inventory is None else inventory)) for node in nodes: - h = health.get(node.name) - # a node with min_ib_gbps: its checker held its ports to it already (CudaChecker) - if h is None or h.state != "ok" or not h.rates or getattr(node, "min_ib_gbps", None) is not None: - continue + by_group.setdefault(str(node.fabric_group or "") if grouped else "", []).append(node) + whose = "candidate nodes" if candidates else "nodes" + for group, members in by_group.items(): + fastest = max((r for n in members for r in (health.get(n.name) or NodeHealth("")).rates.values()), + default=None) if fastest is None: continue + where = f" in fabric group {group}" if grouped and group else " without a fabric group" if grouped else "" base = float(fastest) * RATE_FRACTION - slow = [f"{label} rate {rate:g} < {base:g} Gb/s (half the fastest job port of the island's nodes, " - f"{fastest:g} Gb/s)" for label, rate in h.rates.items() if rate < base * 0.999] - if slow: - health[node.name] = NodeHealth("bad", "is not healthy: " + "; ".join(slow), h.rates) + for node in members: + h = health.get(node.name) + # a node with min_ib_gbps: its checker held its ports to it already (CudaChecker) + if h is None or h.state != "ok" or not h.rates or getattr(node, "min_ib_gbps", None) is not None: + continue + slow = [f"{label} rate {rate:g} < {base:g} Gb/s (half the fastest job port of the island's {whose}{where}, " + f"{fastest:g} Gb/s)" for label, rate in h.rates.items() if rate < base * 0.999] + if slow: + health[node.name] = NodeHealth("bad", "is not healthy: " + "; ".join(slow), h.rates) def check_health(nodes: Sequence[Any], *, multi: bool, ssh: Any, out: JoinCheck, - env: Mapping[str, str] | None = None, cache: Mapping[str, NodeHealth] | None = None) -> None: + env: Mapping[str, str] | None = None, cache: Mapping[str, NodeHealth] | None = None, + inventory: Sequence[Any] | None = None, candidates: bool = False) -> None: """The health of ``nodes`` into ``out.health`` (a node in ``cache`` is not checked again).""" for node in nodes: if node.name in out.health: @@ -319,7 +358,7 @@ def check_health(nodes: Sequence[Any], *, multi: bool, ssh: Any, out: JoinCheck, cached = (cache or {}).get(node.name) out.health[node.name] = cached if cached is not None else read_health(node, multi=multi, ssh=ssh, env=env) if multi: - judge_rates(nodes, out.health) + judge_rates(nodes, out.health, inventory=inventory, candidates=candidates) def _health_problem(name: str, h: NodeHealth, *, force: bool, out: JoinCheck) -> str | None: @@ -397,7 +436,9 @@ def check(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str | No ``lease_store``); ``islands``: the fleet's other islands' launch prefix -> island (whose leases are theirs); ``inventory``: the whole inventory (default ``nodes``); ``env``: the island's own environment; ``force``: a check that does not read is a warning; - ``health``: node health already read (a recheck).""" + ``health``: node health already read (a recheck). With ``lease_store``, ``taken`` holds the + nodes of the islands whose inventory has no ``lease_store`` or another one (their leases + are not in this store).""" out = JoinCheck() if ssh is None: from .ssh_trainer_island import SshOps # noqa: PLC0415 @@ -409,7 +450,7 @@ def check(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str | No inventory=every) else: _check_leased(nodes, need=need, run_id=run_id, lease_store=lease_store, islands=islands or {}, ssh=ssh, - env=env, force=force, health=health, out=out, inventory=every) + env=env, force=force, health=health, out=out, inventory=every, taken=taken or {}) if out.refusals: out.nodes = [] return out @@ -426,7 +467,7 @@ def _check_listed(nodes: Sequence[Any], *, need: int, taken: Mapping[str, str], owner = next((taken[k] for k in sorted(node_keys(node)) if k in taken), None) if owner: out.refusals.append(f"node {node.name} is island {owner}'s") - check_health(nodes, multi=need > 1, ssh=ssh, out=out, env=env, cache=health) + check_health(nodes, multi=need > 1, ssh=ssh, out=out, env=env, cache=health, inventory=inventory) for node in nodes: problem = _health_problem(node.name, out.health[node.name], force=force, out=out) if problem: @@ -439,9 +480,20 @@ def _check_listed(nodes: Sequence[Any], *, need: int, taken: Mapping[str, str], out.nodes = [n.name for n in nodes] +def _owner(node: Any, taken: Mapping[str, str]) -> str | None: + return next((taken[k] for k in sorted(node_keys(node)) if k in taken), None) + + def _check_leased(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str, islands: Mapping[str, str], - ssh: Any, env: Any, force: bool, health: Any, out: JoinCheck, inventory: Sequence[Any]) -> None: - """An inventory with ``lease_store``: ``need`` of its trainer nodes, as the launch picks them.""" + ssh: Any, env: Any, force: bool, health: Any, out: JoinCheck, inventory: Sequence[Any], + taken: Mapping[str, str]) -> None: + """An inventory with ``lease_store``: ``need`` of its trainer nodes, as the launch picks them. + + The launch (``lease_trainer_nodes`` / ``pick_nodes``) runs under a new holder (a new + run dir: a new identity, ``-m`` after a move), so no node is its own yet: it + places the island on the free nodes, in the inventory's order; with too few it waits, + and once the island's earlier incarnation has let its nodes go it places on the free + nodes and those. Each of these picks that fits must take healthy nodes only.""" if len(nodes) < need: out.refusals.append(f"the island needs {need} trainer node(s); its inventory lists {len(nodes)} " f"{[n.name for n in nodes]}") @@ -449,11 +501,16 @@ def _check_leased(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: holders = lease_holders(nodes, lease_store=lease_store, run_id=run_id, out=out) if holders is None: return - held = {n.name: why for n in nodes if (why := lease_problem(holders[n.name], run_id=run_id, islands=islands))} - # the launch's order: the nodes its own launch holds, then the free ones (lease_trainer_nodes) - ours = [n for n in nodes if n.name not in held and holders[n.name] is not None] - usable = ours + [n for n in nodes if n.name not in held and n not in ours] - check_health(usable, multi=need > 1, ssh=ssh, out=out, env=env, cache=health) + held: dict[str, str] = {} + for node in nodes: + owner = _owner(node, taken) + why = f"is island {owner}'s" if owner else lease_problem(holders[node.name], run_id=run_id, islands=islands) + if why: + held[node.name] = why + usable = [n for n in nodes if n.name not in held] # free, or held by the island's earlier incarnation + free = [n for n in usable if holders[n.name] is None] + check_health(usable, multi=need > 1, ssh=ssh, out=out, env=env, cache=health, inventory=inventory, + candidates=True) sick = {} for node in usable: problem = _health_problem(node.name, out.health[node.name], force=force, out=out) @@ -467,7 +524,7 @@ def _check_leased(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: out.notes.append(f"fabric: {HINT}") try: - chosen = _pick_placement([n for n in usable if n.name not in sick], need, inventory) + _pick_placement([n for n in usable if n.name not in sick], need, inventory) except Exception as error: # noqa: BLE001 - no fit (PlacementError), or the check that cannot run fit = type(error).__name__ == "PlacementError" out.refusals += left_out + [(f"fabric: {error}" if grouped else @@ -475,22 +532,32 @@ def _check_leased(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: f"healthy, {need} needed") if fit else f"fabric: the placement check could not run ({type(error).__name__}: {error})"] return - try: # the launch's own pick (leases only): must not take a node found unhealthy - launch = _pick_placement(usable, need, inventory) - except Exception: # noqa: BLE001 - it fits without the sick nodes, so it fits with them - launch = chosen - if bad := [n.name for n in launch if n.name in sick]: + picks: list[list[Any]] = [] # the launch's picks: the free nodes; then with its earlier incarnation's + for offered in ([free, usable] if len(free) < len(usable) else [free]): + try: + picks.append(_pick_placement(offered, need, inventory)) + except Exception: # noqa: BLE001 - too few of them: the launch waits for the next ones + continue + bad = list(dict.fromkeys(n.name for pick in picks for n in pick if n.name in sick)) + if bad: out.refusals += [sick[name] for name in bad] + [ f"the island's launch picks its nodes by their leases and would take {', '.join(bad)}; take " "such a node out of the inventory's trainer nodes (roles) or clear its fault"] return out.notes += [f"left out: {why}" for why in left_out] - out.nodes = [n.name for n in launch] + out.nodes = [n.name for n in picks[0]] + if len(picks) > 1 and [n.name for n in picks[1]] != out.nodes: + out.notes.append(f"the island takes {names(out.nodes)} (free now); were they taken meanwhile, its launch " + f"waits for its earlier incarnation's nodes and takes {names(n.name for n in picks[1])} " + "(checked too)") -def taken_nodes(doc: Mapping[str, Any], *, other_than: str, fleet_argv: Sequence[str]) -> dict[str, str]: +def taken_nodes(doc: Mapping[str, Any], *, other_than: str, fleet_argv: Sequence[str], + lease_store: str | None = None) -> dict[str, str]: """Node key (:func:`node_keys`) -> island, for the ``ssh:`` trainer islands of the desired - state other than ``other_than`` (their inventories' trainer nodes).""" + state other than ``other_than`` (their inventories' trainer nodes). ``lease_store``: the + new island's; an island whose inventory has the same one is left out (its leases say + which nodes it holds).""" from yeto.launch.pool import desired as dz # noqa: PLC0415 from .node_inventory import island_nodes as role_nodes # noqa: PLC0415 @@ -504,10 +571,12 @@ def taken_nodes(doc: Mapping[str, Any], *, other_than: str, fleet_argv: Sequence if path is None: continue try: - nodes = role_nodes(load_inventory(path), "trainer") + listed = load_inventory(path) except Exception as error: # noqa: BLE001 - its nodes unknown: said, not taken as free raise ValueError(f"island {name}'s inventory {path} does not read ({error})") from None - for node in nodes: + if lease_store is not None and getattr(listed, "lease_store", None) == lease_store: + continue + for node in role_nodes(listed, "trainer"): for key in node_keys(node): out.setdefault(key, name) return out @@ -523,9 +592,10 @@ def fleet_prefixes(doc: Mapping[str, Any], *, other_than: str) -> dict[str, str] def check_member(member: Mapping[str, Any], doc: Mapping[str, Any], *, fleet_argv: Sequence[str], run_id: str, ssh: Any = None, log: Callable[[str], None] | None = None, force: bool = False, - health: Mapping[str, NodeHealth] | None = None) -> JoinCheck: + health: Mapping[str, NodeHealth] | None = None, seen: Iterable[str] = ()) -> JoinCheck: """:func:`check` of an island's trainer member (added, or moved) against the desired - state ``doc`` (its other islands).""" + state ``doc`` (its other islands). ``seen``: notes and warnings printed already (a + recheck prints only the new ones).""" say = log or (lambda m: print(m, file=sys.stderr)) argv = [*fleet_argv, *(member.get("argv") or ())] from .node_inventory import lease_store_of, load_inventory # noqa: PLC0415 @@ -535,13 +605,16 @@ def check_member(member: Mapping[str, Any], doc: Mapping[str, Any], *, fleet_arg store = lease_store_of(inventory) name = str(member["name"]) result = check(nodes, need=need, run_id=run_id, lease_store=store, - taken=None if store else taken_nodes(doc, other_than=name, fleet_argv=fleet_argv), + taken=taken_nodes(doc, other_than=name, fleet_argv=fleet_argv, lease_store=store), islands=fleet_prefixes(doc, other_than=name), ssh=ssh, inventory=inventory, env=island_env_of(argv), force=force, health=health) + shown = set(seen) for note in result.notes: - say(f"fleet island: note: island {name}: {note}") + if note not in shown: + say(f"fleet island: note: island {name}: {note}") for warning in result.warnings: - say(f"fleet island: WARNING: island {name}: {warning}") + if warning not in shown: + say(f"fleet island: WARNING: island {name}: {warning}") return result diff --git a/yeto/rl/fleet_islands.py b/yeto/rl/fleet_islands.py index eb66a347f..fc044a3a6 100644 --- a/yeto/rl/fleet_islands.py +++ b/yeto/rl/fleet_islands.py @@ -254,7 +254,7 @@ def join_check(cfg: dict[str, Any], doc: dict[str, Any], member: dict[str, Any], # a node leased by the island's own launch (its member prefix, -m after a move) is its own result = island_join.check_member(member, doc, fleet_argv=fleet_argv, run_id=str(member["prefix"]), ssh=ssh, force=force, health=None if first is None else first.health, - log=None if first is None else (lambda m: None)) + seen=() if first is None else [*first.notes, *first.warnings]) if not result.ok: again = "" if first is None else " (checked again on the desired state now)" raise IslandChangeError(f"island {member['name']}'s nodes cannot join{again}: " + "; ".join(result.refusals)) From 576973e30125ae0b1fad0a7c211b3fb03a2ed5ce Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 01:11:00 +0800 Subject: [PATCH 13/13] island join: refuse a launch pick of another island's machine; every unhealthy candidate refuses - the launch sees nodes of islands on no or another lease store, and the same machine under another name on this store, as free: a predicted pick that takes one refuses, naming the fix - the second predicted pick is made on the rest of the first; with a lease store any unhealthy candidate refuses; the self-contradicting note is gone - lease stores compare in one spelling (file:///x and /x) - a timed-out kernel log read says so; a fabric section killed (137) is a timeout - the running check holds a port to max(first-check rate, min_ib_gbps) Co-Authored-By: Claude Opus 5.5 --- docs/NODE_RUNTIME.md | 2 +- docs/OWN_CLUSTERS.md | 24 ++++-- tests/test_island_join.py | 132 ++++++++++++++++++++-------- tests/test_node_health_wiring.py | 15 ++++ yeto/hw/node_health.py | 6 +- yeto/launch/island_join.py | 142 +++++++++++++++++++++++-------- yeto/launch/node_inventory.py | 14 +-- 7 files changed, 249 insertions(+), 86 deletions(-) diff --git a/docs/NODE_RUNTIME.md b/docs/NODE_RUNTIME.md index d6fffe950..78aafb5df 100644 --- a/docs/NODE_RUNTIME.md +++ b/docs/NODE_RUNTIME.md @@ -278,7 +278,7 @@ One shell call reads, in this order: | ECC | the same query | the volatile uncorrectable ECC count grew since the previous check (a count that went down is the new baseline) | | NVLink fabric | the `Fabric` blocks of `nvidia-smi -q` | a GPU that has a fabric state is not `Completed/Success` (a PCIe card's `N/A` passes) | | fabric manager | `systemctl is-active nvidia-fabricmanager` | it was active and is now `inactive` or `failed` (a node without NVSwitch, never active, passes) | -| IB / RoCE ports | `ibstat` (`ibv_devinfo -v` only when ibstat fails) | a port named by `NCCL_IB_HCA` is missing, not `Active`, or slower than the node's `min_ib_gbps` in the inventory (without it: than at the first check); without `NCCL_IB_HCA`, no port of the fabric is active, or, with `min_ib_gbps`, an active one is slower | +| IB / RoCE ports | `ibstat` (`ibv_devinfo -v` only when ibstat fails) | a port named by `NCCL_IB_HCA` is missing, not `Active`, or slower than at the first check or than the node's `min_ib_gbps` in the inventory, whichever is higher; without `NCCL_IB_HCA`, no port of the fabric is active, or, with `min_ib_gbps`, an active one is slower | The XIDs and the ECC count only count from the second check on. What the kernel log holds at the first check is history: the preflight judged the node then. The nodes of diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 5353f619a..bd45423b4 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -602,19 +602,25 @@ nodes and prints the nodes the island takes: | Check | Refused when | |---|---| | Count | Without `lease_store`: the inventory does not list as many trainer nodes as `--gpu` says. With `lease_store` it may list more, as for a launch: the island takes as many as it needs of the free, healthy ones (below). | -| In this fleet | A node is a trainer node of another `ssh:` island whose inventory has no `lease_store`, or another one: the same name, or the same machine (its SSH target without `user@`, or its `address`, in any case). For an island on the same `lease_store`, its launch's lease says which nodes it holds. | +| In this fleet | A node is a trainer node of another `ssh:` island whose inventory has no `lease_store`, or another one: the same name, or the same machine (its SSH target without `user@`, or its `address`, in any case). For an island on the same `lease_store` (`file:///x` and `/x` are one store), its launch's lease says which nodes it holds; a lease is taken by node name, so the same machine under another name in its inventory counts as its node. | | Health | One SSH call per node runs the node health check of its device family, the check the island's launch runs while it trains. A node joining has no earlier check to compare with, so it is judged on absolute rules: a hardware Xid in the kernel log of this boot, a volatile uncorrectable ECC count above 0, NVSwitch GPUs whose `nvidia-fabricmanager` is not `active`, fewer GPUs than `cards_per_node`, an NVLink fabric not `Completed`. A multi-node island also needs its ports `Active`: those of `NCCL_IB_HCA` (the island's own `--island-env` value wins over the node's `env`), else the fabric's ports that NCCL takes. Each port runs at no less than the node's `min_ib_gbps` when the inventory sets it; else at no less than half the fastest of these ports on the island's nodes of the same fabric group. A check that does not read is refused: no answer, `nvidia-smi` or the fabric state timed out, a check still stuck on the node, an output cut off, the IB tools unread, or a kernel log the SSH user cannot read (`dmesg` restricted: add the user to the `adm` or `systemd-journal` group). With `--force` such a check is a WARNING and the node joins. A node found unhealthy is refused with `--force` too. A device family without a health check, or a node with `node_health: off`, is a note. | | Fabric group | The inventory declares `fabric_group` and no one group holds the island's nodes. An inventory without any `fabric_group` only gets a note. | | Lease | The inventory's `lease_store` shows a node leased to another run, or to another island of this fleet. A lease of the island's own launch (`/trainer`, or `-m/trainer` after a move) is not a refusal. A lease that does not read is refused. Without `lease_store` this is not checked, and a note says so. | -With `lease_store`, the nodes held by another run or island and the unhealthy ones are -left out, and the island's nodes are placed in the rest as its launch places them (one -fabric group in a grouped inventory, else in the inventory's order). When too few are -left, the refusal names each node left out and why. The launch picks by leases only, under -a holder of its own: after a move, the nodes the island's earlier incarnation holds are not -its own. It takes the free nodes first, and waits for the earlier incarnation's nodes only -when there are too few. A pick of the launch, either way, that would take a node found -unhealthy is refused: take that node out of the trainer nodes (`roles`) or clear its fault. +With `lease_store`, the nodes held by another run or island are left out, and the island +must fit on the healthy rest (one fabric group in a grouped inventory, else any). When it +does not, the refusal names each node left out and why. The launch picks by leases only, +under a holder of its own (after a move, the nodes the island's earlier incarnation holds +are not its own): it takes the free nodes in the inventory's order (the free and the +earlier incarnation's ones when too few are free), and the rest when those are taken +meanwhile. So: + +- any unhealthy candidate refuses, as a pick may come to it: take that node out of the + trainer nodes (`roles`) or clear its fault; +- a node of an island on no or another `lease_store`, or the same machine under another + name, looks free to the launch: a pick that would take it refuses (`launch would take + ...`): give both islands the same `lease_store` and one name per machine, or use + inventories without shared nodes. Limits: diff --git a/tests/test_island_join.py b/tests/test_island_join.py index 36130d8f0..3de9e411d 100644 --- a/tests/test_island_join.py +++ b/tests/test_island_join.py @@ -325,25 +325,27 @@ def test_the_group_placement_picks_from_the_free_healthy_nodes(tmp_path): assert "node b300-3 is not healthy: GPU 2 uncorrectable ECC 5 (volatile)" in out.refusals +MAY_TAKE = "the island's launch picks its nodes by their leases and may take {}; take such a node out of the " \ + "inventory's trainer nodes (roles) or clear its fault" + + def test_an_unhealthy_node_the_launch_would_pick_by_its_leases_is_refused(tmp_path): - """The island's launch picks by leases only (in order): the check refuses a pick it - would make onto a node found unhealthy, rather than pass nodes the launch does not take.""" + """The island's launch picks by leases only (in order): any unhealthy candidate refuses, + rather than pass nodes the launch does not take.""" store, nodes = _shared(tmp_path) _hold(store, nodes[0], "other-run/trainer") out = _check(nodes, Ssh({"b300-1": XID_79}), lease_store=store) - assert out.refusals[0] == "node b300-1 is not healthy: GPU 5 XID 79" + ij.XID_HINT - assert out.refusals[1].startswith("the island's launch picks its nodes by their leases and would take b300-1") + assert out.refusals == ["node b300-1 is not healthy: GPU 5 XID 79" + ij.XID_HINT, MAY_TAKE.format("b300-1")] def test_the_launch_s_pick_after_a_move_takes_no_node_as_its_own(tmp_path): - """After a move the launch runs as ``r-i2-m1/trainer@``: the nodes the island's - earlier incarnation (``r-i2``) holds are not its own, so it takes the free ones in the - inventory's order, as the real ``pick_nodes`` does, and the check judges that pick.""" + """Scenario A. After a move the launch runs as ``r-i2-m1/trainer@``: the + nodes the earlier incarnation (``r-i2``) holds are not its own, so it takes the free ones + in the inventory's order, as the real ``pick_nodes`` does.""" from yeto.launch.node_lease import pick_nodes store = str(tmp_path / "leases") - names = ["c-1", "d-2", "a-3", "b-4"] - nodes = load_inventory(_inventory(tmp_path / "inv.yaml", names, lease_store=store)) + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["c-1", "d-2", "a-3", "b-4"], lease_store=store)) for node in nodes[2:]: _hold(store, node, "r-i2/trainer") launch = NodeLeases(store, "r-i2-m1/trainer", identity="new") @@ -352,41 +354,70 @@ def test_the_launch_s_pick_after_a_move_takes_no_node_as_its_own(tmp_path): for node in picked: launch.release(node) out = _check(nodes, Ssh({"c-1": XID_79}), lease_store=store) - assert out.refusals[0] == "node c-1 is not healthy: GPU 5 XID 79" + ij.XID_HINT - assert "would take c-1" in out.refusals[-1] - ok = _check(nodes, Ssh({"a-3": XID_79}), lease_store=store) # neither pick takes a-3 - assert ok.ok and ok.nodes == ["c-1", "d-2"] - _hold(store, nodes[1], "other-run/trainer") # one free node: the launch waits for the earlier incarnation's - late = _check(nodes, Ssh({"a-3": XID_79}), lease_store=store) - assert late.refusals[0].startswith("node a-3 is not healthy") and "would take a-3" in late.refusals[-1] + assert out.refusals == ["node c-1 is not healthy: GPU 5 XID 79" + ij.XID_HINT, MAY_TAKE.format("c-1")] fine = _check(nodes, Ssh(), lease_store=store) - assert fine.ok and fine.nodes == ["c-1", "a-3"] + assert fine.ok and fine.nodes == ["c-1", "d-2"] + _hold(store, nodes[1], "other-run/trainer") # one free node: the free and the earlier incarnation's + assert _check(nodes, Ssh(), lease_store=store).nodes == ["c-1", "a-3"] -def test_the_free_nodes_are_judged_even_when_the_earlier_incarnation_s_come_first(tmp_path): - """Inventory order [a-1, b-2 (the earlier incarnation's), c-3, d-4 (free)]: the launch takes - c-3 and d-4 while they are free; an unhealthy c-3 refuses although a-1 and b-2 are fine.""" +def test_scenario_b_the_free_nodes_after_the_earlier_incarnation_s(tmp_path): + """[a-1, b-2 (the earlier incarnation's), c-3, d-4 (free)]: the launch takes c-3, d-4; an + unhealthy c-3 refuses although a-1 and b-2 are fine.""" store = str(tmp_path / "leases") nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["a-1", "b-2", "c-3", "d-4"], lease_store=store)) for node in nodes[:2]: _hold(store, node, "r-i2/trainer") - out = _check(nodes, Ssh({"c-3": XID_79}), lease_store=store) - assert not out.ok and "would take c-3" in out.refusals[-1] + assert _check(nodes, Ssh({"c-3": XID_79}), lease_store=store).refusals[-1] == MAY_TAKE.format("c-3") ok = _check(nodes, Ssh(), lease_store=store) - assert ok.nodes == ["c-3", "d-4"] - assert ("the island takes c-3, d-4 (free now); were they taken meanwhile, its launch waits for its earlier " - "incarnation's nodes and takes a-1, b-2 (checked too)") in ok.notes + assert ok.nodes == ["c-3", "d-4"] and not any("meanwhile" in n for n in ok.notes) + + +def test_scenario_d_an_unhealthy_candidate_no_predicted_pick_takes_still_refuses(tmp_path): + """[c-1, d-2 free; a-3, b-4 the earlier incarnation's; e-5 free and unhealthy]: the picks + take c-1, d-2, then a-3, b-4; e-5 still refuses (a pick may come to any candidate).""" + store = str(tmp_path / "leases") + nodes = load_inventory(_inventory(tmp_path / "inv.yaml", ["c-1", "d-2", "a-3", "b-4", "e-5"], lease_store=store)) + for node in nodes[2:4]: + _hold(store, node, "r-i2/trainer") + assert _check(nodes, Ssh({"e-5": XID_79}), lease_store=store).refusals[-1] == MAY_TAKE.format("e-5") + assert _check(nodes, Ssh(), lease_store=store).nodes == ["c-1", "d-2"] -def test_a_shared_inventory_also_leaves_out_the_nodes_of_islands_on_other_lease_stores(tmp_path): +def test_a_launch_that_would_take_another_island_s_nodes_is_refused(tmp_path): + """North (no lease_store) runs on b300-0 and b300-1 of south's shared inventory: south's + launch sees them free in its store and takes them first: refused.""" store, nodes = _shared(tmp_path) - taken = {k: "north" for n in nodes[:2] for k in ij.node_keys(n)} # an island whose inventory has no store + taken = {k: "north" for n in nodes[:2] for k in ij.node_keys(n)} out = _check(nodes, Ssh(), lease_store=store, taken=taken) - assert out.ok and out.nodes == ["b300-2", "b300-3"] - assert "left out: node b300-0 is island north's" in out.notes - out = _check(nodes, Ssh({"b300-3": XID_79}), lease_store=store, taken=taken) - assert out.refusals[:3] == ["node b300-0 is island north's", "node b300-1 is island north's", - "node b300-3 is not healthy: GPU 5 XID 79" + ij.XID_HINT] + assert out.refusals == ["launch would take b300-0, b300-1, island north's: give both islands the same " + "lease_store, or use inventories without shared nodes"] + late = {k: "north" for n in nodes[2:] for k in ij.node_keys(n)} # after the free nodes: the second pick + assert _check(nodes, Ssh(), lease_store=store, taken=late).refusals == [ + "launch would take b300-2, b300-3, island north's: give both islands the same lease_store, or use " + "inventories without shared nodes"] + three = load_inventory(_inventory(tmp_path / "three.yaml", FOUR[:3], lease_store=store)) + one = {k: "north" for k in ij.node_keys(three[2])} # no pick comes to b300-2: it may join + out = _check(three, Ssh(), lease_store=store, taken=one) + assert out.ok and out.nodes == ["b300-0", "b300-1"] and "left out: node b300-2 is island north's" in out.notes + + +def test_the_same_machine_under_another_name_on_one_lease_store_is_another_island_s(tmp_path): + store, nodes = _shared(tmp_path) + (theirs,) = load_inventory(_inventory(tmp_path / "theirs.yaml", ["north-a"], lease_store=store, + hosts={"north-a": "root@B300-0.example"}, + addresses={"north-a": "203.0.113.50"})) + aliases = {k: ("north", "north-a") for k in ij.node_keys(theirs) - {"name:north-a"}} + out = _check(nodes, Ssh(), lease_store=store, aliases=aliases) + assert out.refusals == ["launch would take b300-0, island north's (its node north-a, the same machine): give " + "the machine one name in both inventories, or use inventories without shared nodes"] + same = {k: ("north", "b300-0") for k in ij.node_keys(nodes[0]) - {"name:b300-0"}} # one name: the lease decides + assert _check(nodes, Ssh(), lease_store=store, aliases=same).ok + + +def test_lease_stores_compare_in_one_spelling(): + assert ij.store_key("file:///srv/leases/") == ij.store_key("/srv/leases") == "/srv/leases" + assert ij.store_key("s3://b/l/") == "s3://b/l" and ij.store_key(None) is None def test_min_ib_gbps_without_nccl_ib_hca_holds_the_fabric_s_ports(tmp_path): @@ -415,8 +446,10 @@ def test_the_relative_rate_compares_nodes_of_one_fabric_group_only(tmp_path): out = _check(nodes, Ssh(slow_b), lease_store=store) assert out.ok and out.nodes == ["b300-0", "b300-1"] out = _check(nodes, Ssh({"b300-3": SLOW}), lease_store=store) - assert "left out: node b300-3 is not healthy: mlx5_0 rate 100 < 200 Gb/s (half the fastest job port of the " \ - "island's candidate nodes in fabric group b, 400 Gb/s)" in "; ".join(out.notes) + assert out.refusals[0] == ("node b300-3 is not healthy: mlx5_0 rate 100 < 200 Gb/s (half the fastest job port of " + "the island's candidate nodes in fabric group b, 400 Gb/s)" + + "".join(f"; mlx5_{i} rate 100 < 200 Gb/s (half the fastest job port of the island's " + "candidate nodes in fabric group b, 400 Gb/s)" for i in range(1, 8))) def test_one_uncorrectable_ecc_error_refuses(tmp_path): @@ -427,6 +460,8 @@ def test_one_uncorrectable_ecc_error_refuses(tmp_path): @pytest.mark.parametrize(("over", "why"), [ ({"xid": (0, xid_text(source="none"))}, ij.XID_UNREAD), ({"fabric": (124, "")}, "nvidia-smi -q (NVLink fabric) timed out"), + ({"fabric": (137, "")}, "nvidia-smi -q (NVLink fabric) timed out"), # killed after its timeout + ({"xid": (124, "boot=" + "0" * 8)}, ij.XID_TIMED_OUT), # timed out: not "restricted" ({"fabricmanager": (124, "")}, "systemctl is-active nvidia-fabricmanager timed out"), ]) def test_a_kernel_log_or_fabric_that_does_not_read_refuses_unless_forced(tmp_path, over, why): @@ -536,6 +571,16 @@ def test_add_takes_an_ssh_island_whose_nodes_pass(fleet_store, wired, tmp_path, assert store.read()["generation"] == 2 and objects.read(claim_key(2)) is not None +def test_the_write_s_recheck_does_not_print_the_first_check_s_notes_again(fleet_store, wired, tmp_path, # noqa: F811 + capsys): + _cfg, _objects, _store, run_cli, samplers = fleet_store + wired.out["b300-5"] = BUSY + assert _add(run_cli, samplers, _inventory(tmp_path / "north.yaml", ["b300-4", "b300-5"]), "--force") == 0 + err = capsys.readouterr().err + assert err.count("note: island north: no lease_store") == 1 + assert err.count("WARNING: island north: node b300-5") == 1 + + def test_the_dry_run_of_a_shared_inventory_prints_the_nodes_the_island_takes(fleet_store, wired, tmp_path, # noqa: F811 capsys): _cfg, _objects, store, run_cli, samplers = fleet_store @@ -657,6 +702,25 @@ def test_islands_on_one_lease_store_are_judged_by_their_leases(fleet_store, wire assert _add(run_cli, south_samplers, south, name="south") == 0 +def test_an_island_on_one_lease_store_naming_the_machines_otherwise_is_refused(fleet_store, wired, tmp_path, # noqa: F811 + capsys): + """North and south share one lease store (written ``/x`` and ``file:///x``); north's + inventory names b300-4 and b300-5 ``n-a`` and ``n-b``: their leases do not keep south off.""" + cfg, _objects, _store, run_cli, samplers = fleet_store + south_samplers = samplers.parent / "south.samplers.json" + south_samplers.write_text(json.dumps([dict(cfg["islands"][1]["samplers"][0], name="sglang-south")])) + store = str(tmp_path / "l") + north = _inventory(tmp_path / "north.yaml", ["n-a", "n-b"], lease_store=store, + hosts={"n-a": "root@b300-4.example", "n-b": "root@b300-5.example"}, + addresses={"n-a": "198.51.100.14", "n-b": "198.51.100.15"}) + assert _add(run_cli, samplers, north) == 0 + south = _inventory(tmp_path / "south.yaml", ["b300-6", "b300-7", "b300-4", "b300-5"], lease_store="file://" + store) + capsys.readouterr() + assert _add(run_cli, south_samplers, south, name="south") == 2 + err = capsys.readouterr().err + assert "launch would take b300-4, island north's (its node n-a, the same machine): give the machine one name" in err + + def test_move_to_ssh_runs_the_same_join_checks(fleet_store, wired, tmp_path, capsys): # noqa: F811 _cfg, _objects, store, run_cli, samplers = fleet_store diff --git a/tests/test_node_health_wiring.py b/tests/test_node_health_wiring.py index 8e6f70923..eb48a8144 100644 --- a/tests/test_node_health_wiring.py +++ b/tests/test_node_health_wiring.py @@ -836,3 +836,18 @@ def test_a_node_s_min_ib_gbps_holds_its_trainer_island_s_ports(tmp_path): ops.add("isl", SshTrainerSpec(nodes=nodes, run_id="run1", workdir="/opt/yeto", run_script="echo island")) watches = ops.islands["isl"].health assert watches[1].checker.min_ib_gbps == 400.0 and watches[0].checker.min_ib_gbps is None + + +def test_a_declared_min_ib_gbps_does_not_hide_a_port_that_slowed_down(): + """The running check holds a port to max(its first-check rate, min_ib_gbps): 400 then 200 + with min_ib_gbps 100 is bad; 400 then 400 with min_ib_gbps 500 is bad too.""" + from test_cluster_preflight import ibstat_text + + low = node_health.checker_for("cuda", expect_gpus=8, min_ib_gbps=100) + first = low.parse(node_text(), node_health.hcas_of(HCA), None) + slowed = low.parse(node_text(ibstat=(0, ibstat_text(rate=200))), node_health.hcas_of(HCA), first.facts) + assert slowed.ok_multi is False and "mlx5_0 rate 200 < 400 Gb/s" in slowed.reasons + high = node_health.checker_for("cuda", expect_gpus=8, min_ib_gbps=500) + again = high.parse(node_text(), node_health.hcas_of(HCA), high.parse(node_text(), node_health.hcas_of(HCA), + None).facts) + assert again.ok_multi is False and "mlx5_0 rate 400 < 500 Gb/s" in again.reasons diff --git a/yeto/hw/node_health.py b/yeto/hw/node_health.py index 7e4502b4e..e285453c8 100644 --- a/yeto/hw/node_health.py +++ b/yeto/hw/node_health.py @@ -43,7 +43,7 @@ (:data:`HARDWARE_XIDS`) since the previous check, the NVLink fabric is ``Completed/Success`` on every GPU that has one, the fabric manager did not stop; * ``ok_multi``: also every port the job's ``NCCL_IB_HCA`` names exists, is ``Active`` - and runs at no less than its rate at the first check (or ``min_ib_gbps``); without + and runs at no less than its rate at the first check and ``min_ib_gbps``; without ``NCCL_IB_HCA``, one of the fabric's ports is active and, with ``min_ib_gbps``, every active one runs at no less. False whenever ``ok_single`` is; None when the GPUs pass but the job names HCAs and the IB @@ -557,7 +557,9 @@ def _ports(self, sections: Mapping[str, Any], hcas: Sequence[str], prev: Mapping if not p.active: out.append(f"{label} port {(p.state or 'unknown').upper()}") continue - base = self.min_ib_gbps if self.min_ib_gbps is not None else rates.get(label) + # the first check's rate, and the declared least one: a low min_ib_gbps never hides a slower port + known = [float(b) for b in (self.min_ib_gbps, rates.get(label)) if b is not None] + base = max(known) if known else None if p.rate_gbps is not None and base is not None and p.rate_gbps < float(base) * 0.999: out.append(f"{label} rate {p.rate_gbps:g} < {float(base):g} Gb/s") for p in ports: # every active port's best rate: the baseline of a later job port diff --git a/yeto/launch/island_join.py b/yeto/launch/island_join.py index 306a28f00..244b3e7bb 100644 --- a/yeto/launch/island_join.py +++ b/yeto/launch/island_join.py @@ -57,6 +57,7 @@ RATE_FRACTION = 0.5 # a job port below this fraction of the island's fastest one is refused XID_UNREAD = ("the kernel log does not read (dmesg restricted, no journalctl -k): add the SSH user to the adm or " "systemd-journal group, or let it run dmesg with sudo") +XID_TIMED_OUT = "reading the kernel log (dmesg / journalctl -k) timed out" XID_HINT = (" (a hardware Xid in the kernel log of this boot: fix the GPU and reboot the node, a new boot starts a " "new log, then add the island again)") _HARDWARE_XID = re.compile(r"\bXID (\d+)\b") @@ -240,14 +241,17 @@ def _absolute(result: Any, *, fm_read: bool = True) -> list[str]: def _unread_parts(text: str, result: Any) -> list[str]: """The parts of a whole check that the join's absolute rules need and that did not read: - the kernel log (no XID source: ``dmesg`` restricted and no ``journalctl -k``), the NVLink - fabric or the fabric manager timed out.""" + the kernel log (timed out, or no XID source: ``dmesg`` restricted and no ``journalctl + -k``), the NVLink fabric or the fabric manager timed out (a kill, 137, too).""" from yeto.hw.host_probe import parse_sections # noqa: PLC0415 out = [] - if (result.facts or {}).get("xid_source") == "none": - out.append(XID_UNREAD) sections = parse_sections(text) + xid = sections.get("xid") + if xid is not None and xid.rc in (124, 137): + out.append(XID_TIMED_OUT) + elif (result.facts or {}).get("xid_source") == "none": + out.append(XID_UNREAD) for name in ("fabric", "fabricmanager"): sec = sections.get(name) if sec is not None and sec.rc in (124, 137): @@ -430,7 +434,8 @@ def check_leases(nodes: Sequence[Any], *, lease_store: str | None, run_id: str, def check(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str | None = None, taken: Mapping[str, str] | None = None, islands: Mapping[str, str] | None = None, ssh: Any = None, inventory: Sequence[Any] | None = None, env: Mapping[str, str] | None = None, force: bool = False, - health: Mapping[str, NodeHealth] | None = None) -> JoinCheck: + health: Mapping[str, NodeHealth] | None = None, + aliases: Mapping[str, tuple[str, str]] | None = None) -> JoinCheck: """The checks of a new island's trainer ``nodes`` (module doc). ``taken``: a node key (:func:`node_keys`) -> the fleet island whose inventory lists it (an inventory without ``lease_store``); ``islands``: the fleet's other islands' launch prefix -> island (whose @@ -438,7 +443,9 @@ def check(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str | No island's own environment; ``force``: a check that does not read is a warning; ``health``: node health already read (a recheck). With ``lease_store``, ``taken`` holds the nodes of the islands whose inventory has no ``lease_store`` or another one (their leases - are not in this store).""" + are not in this store); ``aliases``: a machine key (SSH target / address) -> (island, its + node name) of the islands on the same ``lease_store`` (a lease is taken by node name: the + same machine under another name is not exclusive).""" out = JoinCheck() if ssh is None: from .ssh_trainer_island import SshOps # noqa: PLC0415 @@ -450,7 +457,8 @@ def check(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str | No inventory=every) else: _check_leased(nodes, need=need, run_id=run_id, lease_store=lease_store, islands=islands or {}, ssh=ssh, - env=env, force=force, health=health, out=out, inventory=every, taken=taken or {}) + env=env, force=force, health=health, out=out, inventory=every, taken=taken or {}, + aliases=aliases or {}) if out.refusals: out.nodes = [] return out @@ -484,16 +492,37 @@ def _owner(node: Any, taken: Mapping[str, str]) -> str | None: return next((taken[k] for k in sorted(node_keys(node)) if k in taken), None) +SHARED_STORE_FIX = "give both islands the same lease_store, or use inventories without shared nodes" +ALIAS_FIX = "give the machine one name in both inventories, or use inventories without shared nodes" + + +def _foreign(node: Any, taken: Mapping[str, str], + aliases: Mapping[str, tuple[str, str]]) -> tuple[str, str, str] | None: + """``(island, detail, fix)`` when ``node`` is another island's machine that this lease + store does not keep from the launch: an island on no or another lease store, or one on + this store that names the machine otherwise.""" + owner = _owner(node, taken) + if owner: + return owner, "", SHARED_STORE_FIX + for key in sorted(node_keys(node)): + island, other = aliases.get(key, (None, None)) + if island is not None and other != node.name: + return island, f" (its node {other}, the same machine)", ALIAS_FIX + return None + + def _check_leased(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: str, islands: Mapping[str, str], ssh: Any, env: Any, force: bool, health: Any, out: JoinCheck, inventory: Sequence[Any], - taken: Mapping[str, str]) -> None: + taken: Mapping[str, str], aliases: Mapping[str, tuple[str, str]]) -> None: """An inventory with ``lease_store``: ``need`` of its trainer nodes, as the launch picks them. The launch (``lease_trainer_nodes`` / ``pick_nodes``) runs under a new holder (a new run dir: a new identity, ``-m`` after a move), so no node is its own yet: it - places the island on the free nodes, in the inventory's order; with too few it waits, - and once the island's earlier incarnation has let its nodes go it places on the free - nodes and those. Each of these picks that fits must take healthy nodes only.""" + skips the nodes another holder leases and places the island in the inventory's order on + the free ones (the free and the earlier incarnation's ones when too few are free); were + those taken meanwhile, on the rest. It sees another island's nodes that this store does + not lease (:func:`_foreign`) as free: a pick that takes one refuses. Every candidate node + must be healthy (a pick may come to any of them).""" if len(nodes) < need: out.refusals.append(f"the island needs {need} trainer node(s); its inventory lists {len(nodes)} " f"{[n.name for n in nodes]}") @@ -501,14 +530,10 @@ def _check_leased(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: holders = lease_holders(nodes, lease_store=lease_store, run_id=run_id, out=out) if holders is None: return - held: dict[str, str] = {} - for node in nodes: - owner = _owner(node, taken) - why = f"is island {owner}'s" if owner else lease_problem(holders[node.name], run_id=run_id, islands=islands) - if why: - held[node.name] = why - usable = [n for n in nodes if n.name not in held] # free, or held by the island's earlier incarnation - free = [n for n in usable if holders[n.name] is None] + held = {n.name: why for n in nodes if (why := lease_problem(holders[n.name], run_id=run_id, islands=islands))} + foreign = {n.name: f for n in nodes if n.name not in held and (f := _foreign(n, taken, aliases))} + launch = [n for n in nodes if n.name not in held] # what the launch may take: free or the earlier incarnation's + usable = [n for n in launch if n.name not in foreign] check_health(usable, multi=need > 1, ssh=ssh, out=out, env=env, cache=health, inventory=inventory, candidates=True) sick = {} @@ -516,8 +541,9 @@ def _check_leased(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: problem = _health_problem(node.name, out.health[node.name], force=force, out=out) if problem: sick[node.name] = problem - left_out = [f"node {n.name} {held[n.name]}" if n.name in held else sick[n.name] - for n in nodes if n.name in held or n.name in sick] + why = {**held, **{name: f"is island {island}'s{detail}" for name, (island, detail, _) in foreign.items()}} + left_out = [f"node {n.name} {why[n.name]}" if n.name in why else sick[n.name] + for n in nodes if n.name in why or n.name in sick] grouped = need > 1 and _grouped(inventory) if need > 1 and not grouped: from .fabric_groups import HINT # noqa: PLC0415 @@ -532,24 +558,31 @@ def _check_leased(nodes: Sequence[Any], *, need: int, run_id: str, lease_store: f"healthy, {need} needed") if fit else f"fabric: the placement check could not run ({type(error).__name__}: {error})"] return - picks: list[list[Any]] = [] # the launch's picks: the free nodes; then with its earlier incarnation's - for offered in ([free, usable] if len(free) < len(usable) else [free]): + free = [n for n in launch if holders[n.name] is None] + picks: list[list[Any]] = [] + for offered in (free, launch): # the first pick: the free nodes, else with the earlier incarnation's try: picks.append(_pick_placement(offered, need, inventory)) - except Exception: # noqa: BLE001 - too few of them: the launch waits for the next ones + break + except Exception: # noqa: BLE001 - too few: the launch waits for the next ones continue - bad = list(dict.fromkeys(n.name for pick in picks for n in pick if n.name in sick)) - if bad: - out.refusals += [sick[name] for name in bad] + [ - f"the island's launch picks its nodes by their leases and would take {', '.join(bad)}; take " + try: # were those taken meanwhile: the rest + picks.append(_pick_placement([n for n in launch if n not in picks[0]], need, inventory)) + except Exception: # noqa: BLE001 - too few left: the launch waits + pass + if sick: + out.refusals += list(sick.values()) + [ + f"the island's launch picks its nodes by their leases and may take {', '.join(sick)}; take " "such a node out of the inventory's trainer nodes (roles) or clear its fault"] + hit: dict[tuple[str, str, str], list[str]] = {} + for name in dict.fromkeys(n.name for pick in picks for n in pick if n.name in foreign): + hit.setdefault(foreign[name], []).append(name) + for (island, detail, fix), taken_names in hit.items(): + out.refusals.append(f"launch would take {', '.join(taken_names)}, island {island}'s{detail}: {fix}") + if out.refusals: return - out.notes += [f"left out: {why}" for why in left_out] + out.notes += [f"left out: {w}" for w in left_out] out.nodes = [n.name for n in picks[0]] - if len(picks) > 1 and [n.name for n in picks[1]] != out.nodes: - out.notes.append(f"the island takes {names(out.nodes)} (free now); were they taken meanwhile, its launch " - f"waits for its earlier incarnation's nodes and takes {names(n.name for n in picks[1])} " - "(checked too)") def taken_nodes(doc: Mapping[str, Any], *, other_than: str, fleet_argv: Sequence[str], @@ -574,7 +607,7 @@ def taken_nodes(doc: Mapping[str, Any], *, other_than: str, fleet_argv: Sequence listed = load_inventory(path) except Exception as error: # noqa: BLE001 - its nodes unknown: said, not taken as free raise ValueError(f"island {name}'s inventory {path} does not read ({error})") from None - if lease_store is not None and getattr(listed, "lease_store", None) == lease_store: + if lease_store is not None and store_key(getattr(listed, "lease_store", None)) == store_key(lease_store): continue for node in role_nodes(listed, "trainer"): for key in node_keys(node): @@ -582,6 +615,46 @@ def taken_nodes(doc: Mapping[str, Any], *, other_than: str, fleet_argv: Sequence return out +def store_key(uri: str | None) -> str | None: + """A lease store URI in one spelling (``file:///x`` and ``/x`` are one store; no trailing ``/``).""" + if uri is None: + return None + text = str(uri).strip() + if text.startswith("file://"): + text = text[len("file://"):] + return text.rstrip("/") or text + + +def aliases_of(doc: Mapping[str, Any], *, other_than: str, fleet_argv: Sequence[str], + lease_store: str | None) -> dict[str, tuple[str, str]]: + """Machine key (SSH target / address of :func:`node_keys`) -> (island, node name), for + the ``ssh:`` islands whose inventory has the lease store ``lease_store``.""" + from yeto.launch.pool import desired as dz # noqa: PLC0415 + + from .node_inventory import island_nodes as role_nodes # noqa: PLC0415 + from .node_inventory import load_inventory # noqa: PLC0415 + + out: dict[str, tuple[str, str]] = {} + if lease_store is None: + return out + for name, member in dz.trainers(dict(doc)).items(): + if name == other_than or not str(member.get("gpu") or "").startswith("ssh:"): + continue + path = inventory_of([*fleet_argv, *(member.get("argv") or ())]) + if path is None: + continue + try: + listed = load_inventory(path) + except Exception as error: # noqa: BLE001 + raise ValueError(f"island {name}'s inventory {path} does not read ({error})") from None + if store_key(getattr(listed, "lease_store", None)) != store_key(lease_store): + continue + for node in role_nodes(listed, "trainer"): + for key in node_keys(node) - {f"name:{node.name}"}: + out.setdefault(key, (name, node.name)) + return out + + def fleet_prefixes(doc: Mapping[str, Any], *, other_than: str) -> dict[str, str]: """Launch prefix -> island, for the trainer islands of the desired state other than ``other_than``.""" from yeto.launch.pool import desired as dz # noqa: PLC0415 @@ -606,6 +679,7 @@ def check_member(member: Mapping[str, Any], doc: Mapping[str, Any], *, fleet_arg name = str(member["name"]) result = check(nodes, need=need, run_id=run_id, lease_store=store, taken=taken_nodes(doc, other_than=name, fleet_argv=fleet_argv, lease_store=store), + aliases=aliases_of(doc, other_than=name, fleet_argv=fleet_argv, lease_store=store), islands=fleet_prefixes(doc, other_than=name), ssh=ssh, inventory=inventory, env=island_env_of(argv), force=force, health=health) shown = set(seen) diff --git a/yeto/launch/node_inventory.py b/yeto/launch/node_inventory.py index b1c849b9c..7065421dc 100644 --- a/yeto/launch/node_inventory.py +++ b/yeto/launch/node_inventory.py @@ -79,10 +79,11 @@ share one group; a file without any ``fabric_group`` key places islands as before. ``fabric_group: unavailable`` (reserved) marks a node the probe found without RDMA to the others: it never joins a multi-node island, a single-node one takes it. -``min_ib_gbps`` is the least rate (Gb/s) of each port the job's ``NCCL_IB_HCA`` names -on the node: the node health check of a multi-node trainer island (``yeto.hw.node_health``) -and the join check of an island added at run time (:mod:`.island_join`) hold the -ports to it. +``min_ib_gbps`` is the least rate (Gb/s) of each port a multi-node job uses on the node: +the ports its ``NCCL_IB_HCA`` names, else every active port of the node's fabric that NCCL +takes. The node health check of a running trainer island (``yeto.hw.node_health``) holds +them to it and to their rate at its first check, whichever is higher; the join check of an +island added at run time (:mod:`.island_join`), which has no earlier check, to it alone. An NVIDIA (``cuda``) multi-node island over ``ib`` / ``roce``, e.g. 6 x 8 B300 (with ``--model-store local:///data/models --model-store-source s3://...`` the @@ -244,8 +245,9 @@ class Node: # :mod:`.fabric_groups`); None: no fabric_group key; FABRIC_UNGROUPED (""): the key is # null; FABRIC_UNAVAILABLE: reserved, the node has no RDMA to the others fabric_group: str | None = None - # the least rate (Gb/s) of each port of the job's NCCL_IB_HCA on the node (the node health - # check of a multi-node trainer island, the join check); None: not declared + # the least rate (Gb/s) of each port a multi-node job uses on the node (NCCL_IB_HCA's, else the + # fabric's active ports): the running health check also keeps its first-check rate, the join + # check has only this; None: not declared min_ib_gbps: float | None = None @property