diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index 76841e908..21796e012 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -252,8 +252,9 @@ nodes: Releasing kept leases: run `yeto cleanup --run `. After it confirmed the stop of the run's islands on their nodes, it releases the leases those islands kept (only the ones of that run, and only when kept or run out). A node that stays unreachable keeps -its lease kept; see "Spare nodes" (`yeto cluster release-node`) once that section is -in this guide. Until then, release such a node by hand: +its lease kept. A node a spare-pool island lost is quarantined: release it with +`yeto cluster release-node` (see "Spare nodes" below). Release any other such node by +hand: 1. Make sure nothing of the run is left on the node: no `yeto--*` or `yeto-sampler-*` containers (`docker ps`, `podman ps`, with `sudo -n` too where @@ -491,3 +492,197 @@ constraint. it was. `yeto cluster probe` and `yeto cluster check` always print the note. To drop the rule, delete the `fabric_group` lines. + +## Spare nodes + +A resident `ssh:` trainer island can keep running after one of its nodes is lost, +if its inventory lists one or more spare nodes. A spare has the role +`trainer-spare`: + +```yaml +nodes: + - {name: b300-0, roles: [trainer], fabric_group: A, ...} + - {name: b300-1, roles: [trainer], fabric_group: A, ...} + - {name: b300-5, roles: [trainer-spare], fabric_group: A, ...} # same card, card count, family, runtime +``` + +A spare is not an island node. The island still takes exactly as many `trainer` +nodes as its `--gpu` says, so an inventory without spares behaves exactly as +before. Every spare must match the island's nodes in device family, CPU +architecture, card, card count, runtime and `store_env_file`, and it must have a +rendezvous `address`. `yeto launch --dry-run` refuses a spare that cannot take a +node's place, and lists the spares and their fabric groups under the island's +`spares`. A device family without a node health checker (see "Node health" in +`docs/NODE_RUNTIME.md`) never gets a spare: its spares do not apply at all. The dry +run and the start print a WARN, and a failed island is relaunched on its own nodes, +as without spares. + +### When a node is lost + +A node is lost when either of these holds: + +- its log stream over SSH ended, and it then failed `unreachable_polls` SSH checks + in a row (3 by default); +- its node health check was bad twice in a row. + +An SSH check that fails while the node's stream still flows is not a loss on its +own: the island fails, and the relaunch first stops it on every node. A node whose +stop is not confirmed (on a power loss, rank 0 usually exits first and the dead +node's stream only ends minutes later) is checked with `ssh true` on each relaunch +poll; twice `unreachable_polls` checks in a row without an answer make it lost. A +node that answers again is relaunched on, as before. + +A network partition is enough: a node that cannot be reached for about 2 to 5 +minutes (the stream's keepalive timeout plus the checks) is lost and quarantined, +even if it was healthy. Each check of a waiting island tries the stops such a node +still owes again, so its old container stops once it answers. Nothing lifts a +quarantine on its own; release the node by hand (below) once it is reachable again. + +When a node is lost, the island writes `island_node_lost` and stops on its other +nodes. The lost node is not waited for; one that still answers (a health loss) is +stopped at once in the background. The node is quarantined: +`fleet/nodes//quarantine.json` in the run store records why, which stop the +node still owes, and the run's lease holder. With a `lease_store`: + +- the record is also written to `/nodes//quarantine.json`, next to + the node's `lease/`. Every run's trainer pick and spare pick leave the node out + until it is released. The pick prints which run and island quarantined each such + node and how to release it, once and on every waiting line. A new run whose + inventory lists no other free trainer node waits for one (`--rl-node-lease-wait-s`) + and then fails with the same note; it does not use a spare in its place; +- a record that cannot be read (the store fails, or the record is not JSON) counts + as a quarantine, with the reason `quarantine record unreadable: ...`; if the store + cannot list the records, each node's record is read instead. A running island's + node is not taken as lost on such a read failure; +- the run keeps its lease on the node (`kept: true`, no longer renewed) while it is + quarantined, also across a restarted launcher; +- once a spare took a node's place, the run dir's lease record (`node-leases.json`) + names the spare. It is written before the island starts on the spare, and put back + if that start fails. A restarted launcher leases the island's current nodes, taken + from the island's spares journal (`ssh-islands/-spares.json` in the run + dir), so it follows a replacement the old launcher stopped in the middle of. Every + start, reattach included, gives back the leases of old nodes the island no longer + runs on; an old node another run holds by then does not stop the island. + +A stop the node still owes stays in the run's ledger as a row of its own, priced as +that node only, so `yeto cleanup --run ` still tries to stop it there. A lost +node whose own stop was confirmed owes nothing for that incarnation and has no such +row; picked again later, a loss of its new incarnation owes its stop again. + +### Which spare is taken + +The spare and the nodes that stay are placed together as one island. The nodes that +stay never move; the spares are tried by node name, and the first one that meets +every condition below is taken: + +- it is in the fabric group of the nodes that stay (`fabric_group`); a node whose + group is `unavailable` takes no multi-node place; +- its node health check ran and passes now; an answer over SSH is not enough; +- no other island of the run holds it (`fleet/nodes//claim.json`, written + once with an exclusive create); +- it is not quarantined, by this run or (with a `lease_store`) by another run. The + wait reason names the run and island of another run's quarantine and how to + release the node; +- its cross-run lease is free, when the inventory names a `lease_store`. + +The claims need a run store with an atomic exclusive create (s3:// or r2:// with +`If-None-Match`, or a local directory). A check-then-write store, such as the OSS +relay, is refused: two islands could take one spare there. + +The health checks run before the pick, outside the launcher's lock, so the other +islands' supervision is not held up. The pick then claims the node and reads its +records again. + +The spare takes the lost node's place in the same layout. If rank 0 was lost, the +spare becomes rank 0 and the rendezvous address moves with it. The island's next +incarnation starts under the same learner id and resumes from that learner's newest +checkpoint: its round cut (`island-cuts/island/LATEST`), or else its newest +policy release (`trainer/policy-releases/` when its samplers follow it). +`island_node_replaced` records the old node, the new node and the resume step. To +the syncer this is a short absence followed by a re-JOIN: the island catches up to +the newest outer weights before it merges again, and the other islands keep merging +meanwhile. + +### No free spare: waiting and backoff + +If no spare qualifies, the island waits (`island_waiting_spare`, with the reason, +e.g. `fabric group A has no free healthy spare node (...)`). It checks again after +60 s, then 120 s, doubling up to 900 s, and writes `island_waiting_spare` again +every hour with `elapsed_s`. While it waits, the fleet controller does not give it +up on `--recover-timeout`. + +Two separate times apply while an island waits: + +| Setting | Default | What it decides | +|---|---|---| +| `fleet.waiting_absent_after_s` (run config) | 3600 s (1 hour) | Whether the fleet goes on. For this long after its wait began, the waiting island still counts toward `fleet.min_islands`; after that it counts as absent, and a fleet left with fewer than `min_islands` islands stops (its samplers stop billing with it). | +| `--spare-max-wait-s` (launch) | 86400 s (24 hours) | When the island is given up: after this long its relaunch is refused and it is abandoned (also under a fixed roster). | + +So in a fleet with more islands than `min_islands`, an island can wait up to 24 +hours while the others train. A one-island fleet, or one with exactly `min_islands` +islands, is not stopped the moment an island starts waiting, but it stops after 1 +hour of waiting. The wait's start is kept in the island's journal, so a restarted +launcher keeps counting; it starts normally, the quarantined node is lost again, +and the island goes on waiting. + +### Replacement limit + +An island may replace at most 3 nodes within 24 hours. On the next loss its +relaunch is refused, `island_replacement_limit` lists every node it replaced, and +the island is given up. The fleet then goes on if `fleet.min_islands` islands still +run. + +### Releasing a quarantined node + +Once a lost node is repaired, put it back with: + +```bash +yeto cluster release-node b300-1 --inventory inventory.yaml --store s3://RUN-STORE --dry-run # what would run +yeto cluster release-node b300-1 --inventory inventory.yaml --store s3://RUN-STORE +``` + +`--store` is the run's `--rl-checkpoint-store`. The command: + +1. checks the node: its health check must run and pass (an answer over SSH alone is + not enough). `--force` skips the check and prints a WARN; a device family without + a health checker needs it; +2. runs the stops the node still owes and closes each owed ledger row. The ledger is + the run's (`runs//resources.jsonl` on the machine that ran the launcher); run + elsewhere, the command says where the row is. When the launcher picks the node + again, it runs the row's stop and closes the row (`released elsewhere`) only once + that stop succeeded, so the node is billed once and the old container is gone. + A quarantine record that cannot be read needs `--force`: the stops it owes are not + known, so check the node for the run's containers by hand first; +3. gives up the run's lease on the node (with a `lease_store`). A kept lease ends at + once. A live one (the run's launcher still renews it) ends only after a probe over + SSH found nothing of the run on the node; a lease another run holds is not + touched; +4. removes the quarantine record, in the run store and in the `lease_store`. + +`--dry-run` prints the record, the stops it would run, the records it would remove +(in the run store and the `lease_store`) and what it would do with the lease. + +From then on any island may take the node again, including one waiting for a spare. +If the check, a stop, the probe or the lease release fails, the node stays +quarantined (exit 1). The launcher never releases a quarantined node on its own. + +The run's launcher may still be running during the release. It never writes a +quarantine record back: a stop it confirmed is recorded as a marker of its own +(`fleet/nodes//settled/`), and the release first writes `released.json`, with +its time, next to the record in both stores. A stop the launcher confirms after the +release therefore records nothing. The launcher reads the record again before each +stop it retries, and skips a stop the record no longer owes. A confirmed stop removes +its incarnation's pid file and leaves a `stopped` marker in its state dir, so a later +stop of that incarnation (release-node, `yeto cleanup`) succeeds without signalling a +process that reused the pid. A ledger row is closed only after its stop was confirmed. + +### Known limits + +- The K3.1 customer layout has no spare. Its PP3 x TP8 x CP2 x EP16 trainer takes all + 48 cards of the 6 x 8 B300 nodes, so a lost node fails the island as before. To + keep spares, use smaller islands, e.g. two 2-node islands, one sampler node and + one spare node. +- A network partition quarantines: a healthy node that cannot be reached for 2 to 5 + minutes is lost and stays quarantined until `yeto cluster release-node`. +- The layout is never shrunk: without a spare the island waits; it does not change + TP/PP/EP. diff --git a/tests/test_ssh_island_spares.py b/tests/test_ssh_island_spares.py new file mode 100644 index 000000000..5a846e029 --- /dev/null +++ b/tests/test_ssh_island_spares.py @@ -0,0 +1,936 @@ +"""Spare nodes of a resident ssh: trainer island (yeto.launch.island_spares, +own-cluster-fleet-stability 4.1, 4.2 and 4.4) over the fake SSH cluster of +test_rl_ssh_resident: when a node is lost, how a spare is picked, the replacement and its +journal, waiting for a spare, the replacement limit, and an inventory without spares +behaving as before. + +The interfaces of groups 1 and 2 (``yeto.hw.node_health``, ``Node.fabric_group``) are faked +here by their agreed signatures (CONTRACT.zh.md).""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from test_rl_ssh_resident import ( + Clock, + FakeCluster, + _SkySide, + _SyncThread, + _cards, # noqa: F401 - autouse: card checks and the run's resource ledger + b300, + make_ops, + spec, + wait_for, +) +from yeto.cost.ledger import ResourceLedger +from yeto.launch import island_spares as isp +from yeto.launch.fleet import ABANDONED, RECOVERING, RUNNING, FleetController, RelaunchBlocked +from yeto.launch.island_spares import IslandSpares, NodeRecords +from yeto.launch.ssh_resident import SshIslandOps +from yeto.modal_runner import RoutingOps +from yeto.rl.engine.object_store import DirectoryObjectStore + +NAMES = ["b300-0", "b300-1", "b300-2"] +HEALTH_MARK = "yeto-fake-health" + + +# ------------------------------------------------------------------ fakes of groups 1 and 2 +def grouped(node, group): + """``Node.fabric_group`` (group 2) on a node of this tree, where the field is not there yet.""" + object.__setattr__(node, "fabric_group", group) + return node + + +def spare(i: int, group: str | None = None): + node = b300(i, roles=(isp.SPARE_ROLE,)) + return grouped(node, group) if group is not None else node + + +@dataclass +class FakeHealthResult: + checked: bool + ok_single: bool | None + ok_multi: bool | None + reasons: list[str] = field(default_factory=list) + facts: dict = field(default_factory=dict) + + +class FakeChecker: + """``node_health.Checker`` by its agreed signature: one script, a pure parse.""" + + def script(self, hcas): + return f"echo {HEALTH_MARK} {','.join(hcas)}" + + def parse(self, text, hcas, prev): + bad = "bad" in text + return FakeHealthResult(True, not bad, not bad, ["XID 79 on GPU 3"] if bad else []) + + +class FakeTracker: + """``node_health.HealthTracker`` by its agreed signature: lost after two bad in a row.""" + + def __init__(self): + self.bad = 0 + + def update(self, result): + if not result.checked: + return "read_failed" + if result.ok_multi: + self.bad = 0 + return "ok" + self.bad += 1 + return "lost" if self.bad >= 2 else "bad_once" + + +class Cluster(FakeCluster): + """The fake cluster with the health checker's script and nodes whose health is bad.""" + + def __init__(self, names, **kw): + super().__init__(names, **kw) + self.sick: set[str] = set() + self.still_runs: dict[str, list[str]] = {} # node -> containers the lease probe finds + + def run(self, node, script, *, timeout=300.0): + if node.name in self.unreachable: # what was asked of a node that cannot answer + self.calls.append(("unanswered", node.name, "kill" if "kill -TERM" in script else "other")) + from yeto.launch.node_lease import PROBE_MARK + + if PROBE_MARK in script: # node_lease.ssh_probe: what of a run still runs on the node + import subprocess + + self.calls.append(("lease-probe", node.name)) + if node.name in self.unreachable: + return subprocess.CompletedProcess([], 255, stdout="", stderr="timed out") + found = "".join(f"{PROBE_MARK} found=container:{c}\n" for c in self.still_runs.get(node.name, ())) + return subprocess.CompletedProcess([], 0, stdout=f"{found}{PROBE_MARK} done\n", stderr="") + if HEALTH_MARK in script: + import subprocess + + self.calls.append(("health", node.name)) + if node.name in self.unreachable: + return subprocess.CompletedProcess([], 255, stdout="", stderr="timed out") + return subprocess.CompletedProcess([], 0, stdout="bad\n" if node.name in self.sick else "ok\n", + stderr="") + return super().run(node, script, timeout=timeout) + + def lose(self, name): + """The node loses power: no SSH answer, its streams end.""" + self.unreachable.add(name) + self.drop(name) + + +@pytest.fixture(autouse=True) +def _health(monkeypatch, tmp_path): + monkeypatch.setattr(isp, "_checker_for", lambda family, **kw: FakeChecker()) + monkeypatch.setattr("yeto.runs.RUNS_DIR", tmp_path / "runs") # the run dir (lease record) of make_ops' run1 + + +# node_health.Reading by its agreed fields (verdict, result.facts, degraded) +READING = SimpleNamespace(verdict="lost", result=FakeHealthResult(True, False, False, ["XID 79 on GPU 3"]), + degraded=False) + + +@dataclass +class Lease: + ok: bool + holder: str | None + took_over: bool = False + previous: str | None = None + blocked: bool = False + + +class FakeLeases: + """``node_lease.NodeLeases`` by its agreed signature.""" + + def __init__(self, run_id="run1/trainer", held=None): + self.run_id = run_id + self.holder_id = f"{run_id}@launcher-a" # holders are /@ + self.holders = dict(held or {}) + self.blocked: set[str] = set() + + def holder(self, node): + return self.holders.get(node.name) + + def acquire(self, node): + if node.name in self.blocked: # a run out lease whose run may still run there + return Lease(False, None, previous="old-run/trainer@x", blocked=True) + if self.holders.get(node.name, self.holder_id) != self.holder_id: + return Lease(False, self.holders[node.name]) + self.holders[node.name] = self.holder_id + return Lease(True, self.holder_id) + + def release(self, node): + self.holders.pop(node.name, None) + + def force_release(self, node, *, holder=None, force=False): + """As NodeLeases: a kept lease ends at once, a live one only with ``force``.""" + if node.name not in self.holders or (holder is not None and self.holders[node.name] != holder): + return False # only the given holder's lease + if node.name not in getattr(self, "kept", []) and not force: + return False # a live lease + self.holders.pop(node.name) + self.forced = [*getattr(self, "forced", []), (node.name, force)] + return True + + def held(self): + return [n for n, h in self.holders.items() if h == self.holder_id and n not in getattr(self, "kept", [])] + + def renew(self, node): + pass + + store_uri = "s3://leases/site" # the island's own start uses these (spec.leases) + + def renew_due(self): + return [] + + def lost(self): + return {} + + def release_all(self, nodes=None): + for n in nodes or (): + if self.holders.get(n.name) == self.holder_id: + self.holders.pop(n.name) + + def keep_all(self, nodes=None): + names = [n.name for n in nodes or ()] + self.kept = [*getattr(self, "kept", []), *(n for n in names if n not in getattr(self, "kept", []))] + return names + + +def join_stops(spares, timeout=5.0): + """Wait for the background stops of lost nodes that still answer.""" + for thread in spares.stop_threads: + thread.join(timeout) + assert not thread.is_alive() + + +def islands_spec(n=3, groups=None): + s = spec(n) + for i, node in enumerate(s.nodes): + if groups is not None: + grouped(node, groups[i]) + return s + + +def make_spares(tmp_path, island_spec, extra, **kw): + store = DirectoryObjectStore(tmp_path / "store") + records = NodeRecords(store, run_id="run1", log=lambda m: None) + resume = kw.pop("resume", lambda: {"source": "release", "step": 7, "ref": "r00000007-v7"}) + return IslandSpares(pool=(*island_spec.nodes, *extra), records=records, resume_probe=resume, **kw), store + + +def lost_island(tmp_path, *, extra, rank=1, groups=None, clock=None, **kw): + """A 3-node island with spares ``extra`` whose rank ``rank`` node lost power.""" + cluster = Cluster([*NAMES, *[n.name for n in extra]]) + clock = clock or Clock() + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=2) + s = islands_spec(groups=groups) + spares, store = make_spares(tmp_path, s, extra, **kw) + ops.add("isl", s, spares=spares) + ops.start("isl") + cluster.lose(NAMES[rank]) + assert wait_for(lambda: ops.islands["isl"].job.procs[rank].poll() is not None) + for _ in range(2): + status = str(ops.job_status("isl", 0)) + assert status == "FAILED" + return cluster, ops, spares, store, clock + + +# ------------------------------------------------------------------ 4.1: when a node is lost +def test_an_ssh_hiccup_while_the_stream_flows_is_no_loss(tmp_path): + cluster, clock = Cluster([*NAMES, "b300-3"]), Clock() + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=60.0, unreachable_polls=3) + s = islands_spec() + spares, store = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + cluster.unreachable.add("b300-1") # SSH checks fail, its log stream still flows + for _ in range(3): + clock.t += 61 + status = str(ops.job_status("isl", 0)) + assert status == "FAILED" # the island fails as it always did (relaunched on its nodes) + assert "does not answer over SSH" in ops.islands["isl"].reason + assert spares.lost == {} and ops.island_events("isl") == [] + assert store.read("fleet/nodes/b300-1/quarantine.json") is None + assert json.loads(store.read("fleet/nodes/b300-1/claim.json"))["island"] == "isl" # still its node + assert store.read("fleet/nodes/b300-3/claim.json") is None + for _ in range(5): # its stop is not confirmed and its stream flows: 2 x 3 checks before a loss, + assert ops.relaunch(None, "isl") is None # counted from the relaunch (not the watch's 3) + assert spares.lost == {} + cluster.unreachable.clear() + assert ops.relaunch(None, "isl") == 1 + assert [c[1] for c in cluster.calls if c[0] == "start" and c[2] == 1] == NAMES # the same nodes + + +def test_a_stream_that_ended_and_no_ssh_answer_is_a_lost_node(tmp_path): + cluster, ops, spares, store, _ = lost_island(tmp_path, extra=[spare(3)]) + (event,) = ops.island_events("isl") + assert event["kind"] == isp.NODE_LOST and event["node"] == "b300-1" and event["rank"] == 1 + assert "does not answer over SSH" in event["reason"] and "its stream ended" in event["reason"] + assert ("unanswered", "b300-1", "kill") not in cluster.calls # the lost node is not waited for + assert cluster.count("kill", 0) == 2 # the other nodes are stopped + q = json.loads(store.read("fleet/nodes/b300-1/quarantine.json")) + assert q["island"] == "isl" and q["owed"] == [{"run_id": "run1", "island": "isl", "incarnation": 0, "rank": 1, + "container": "yeto-run1-isl-i0-n1"}] + assert store.read("fleet/nodes/b300-1/claim.json") is None # the island gave its claim up + # the incarnation's row is closed; the lost node owes its stop in a row of its own (its price only) + (row,) = ResourceLedger(tmp_path / "ledger.jsonl").open_resources() + assert row.id == "run1/isl-i0-owed-b300-1" and row.attrs["ranks"] == [1] + assert [n["name"] for n in row.attrs["nodes"]] == ["b300-1"] and row.attrs["usd_per_hour"] == 8 * 2.0 + from yeto.launch.ssh_trainer_ledger import cleanup_release + + cluster.unreachable.discard("b300-1") # back: a cleanup stops the owed incarnation at its rank + scripts, real = [], cluster.run + cluster.run = lambda node, script, **kw: (scripts.append((node.name, script)), real(node, script, **kw))[1] + ok, _action, _ = cleanup_release(row, ssh=cluster) + assert ok and ("kill", "b300-1", 0) in cluster.calls + assert [n for n, sc in scripts if "yeto-run1-isl-i0-n1" in sc] == ["b300-1"] + + +def test_a_node_whose_stream_ended_is_lost_after_the_relaunch_checks(tmp_path): + """The island failed for another reason while a node's stream ended; that node is judged + at the relaunch: no answer ``unreachable_polls`` times in a row makes it lost.""" + cluster, clock = Cluster([*NAMES, "b300-3"]), Clock() + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=2) + s = islands_spec() + spares, _ = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + cluster.exit("b300-0", 0, 1) + cluster.lose("b300-2") + assert wait_for(lambda: all(ops.islands["isl"].job.procs[r].poll() is not None for r in (0, 2))) + assert str(ops.job_status("isl", 0)) == "FAILED" + assert spares.lost == {} + assert ops.relaunch(None, "isl") is None # one check without an answer + assert spares.lost == {} + assert ops.relaunch(None, "isl") == 1 # the second: lost, replaced + assert [c[1] for c in cluster.calls if c[0] == "start" and c[2] == 1] == ["b300-0", "b300-1", "b300-3"] + + +def test_health_bad_twice_in_a_row_is_a_lost_node(tmp_path): + cluster, clock = Cluster([*NAMES, "b300-3"]), Clock() + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0) + s = islands_spec() + spares, _ = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + rec, tracker, checker = ops.islands["isl"], FakeTracker(), FakeChecker() + cluster.sick.add("b300-2") + verdicts = [] + for _ in range(2): # the resident tick of group 1: the checker's verdict, then the hook on lost + done = cluster.run(s.nodes[2], checker.script(isp.hcas_of(s.nodes[2]))) + verdict = tracker.update(checker.parse(done.stdout, [], None)) + verdicts.append(verdict) + if verdict == "lost": + result = checker.parse(done.stdout, [], None) + ops._node_health_lost(rec, 2, result.reasons, SimpleNamespace(verdict="lost", result=result, + degraded=False)) + assert verdicts == ["bad_once", "lost"] + assert str(ops.job_status("isl", 0)) == "FAILED" and "node health bad in 2 checks in a row: XID 79" in rec.reason + (event,) = ops.island_events("isl") + assert event["kind"] == isp.NODE_LOST and event["node"] == "b300-2" + join_stops(spares) + assert cluster.count("kill", 0) == 3 # it still answers: stopped now (in the background) + assert ops.relaunch(None, "isl") == 1 + assert [c[1] for c in cluster.calls if c[0] == "start" and c[2] == 1] == ["b300-0", "b300-1", "b300-3"] + + +def test_without_spares_a_health_loss_relaunches_on_the_same_nodes(tmp_path): + cluster = Cluster(NAMES) + ops = make_ops(tmp_path, cluster, health_every_s=0) + ops.add("isl", islands_spec()) + ops.start("isl") + ops._node_health_lost(ops.islands["isl"], 2, ["XID 79 on GPU 3"], READING) + assert str(ops.job_status("isl", 0)) == "FAILED" + assert ops.island_events("isl") == [] and ops.spares_view("isl") is None + assert ops.relaunch(None, "isl") == 1 + assert [c[1] for c in cluster.calls if c[0] == "start" and c[2] == 1] == NAMES + + +# ------------------------------------------------------------------ the replacement +@pytest.mark.parametrize("rank", [1, 0]) +def test_a_spare_takes_the_lost_nodes_place_in_the_same_layout(tmp_path, rank): + cluster, ops, spares, store, _ = lost_island(tmp_path, extra=[spare(3)], rank=rank) + ops.island_events("isl") + assert ops.relaunch(None, "isl") == 1 + new = list(NAMES) + new[rank] = "b300-3" + assert [c[1] for c in cluster.calls if c[0] == "start" and c[2] == 1] == new + rec = ops.islands["isl"] + assert [n.name for n in rec.spec.nodes] == new and rec.spec.run_script == "echo island" + script0 = cluster.runs[new[0]][1]["script"] + # node 0's address is the rendezvous: a lost rank 0 hands it to the spare + assert f"export SKYPILOT_NODE_IPS='{rec.spec.addresses()[0]}" in script0 + assert rec.spec.addresses()[rank] == "198.51.100.13" + (event,) = ops.island_events("isl") + assert event == {"kind": isp.NODE_REPLACED, "island": "isl", "rank": rank, "lost": NAMES[rank], + "spare": "b300-3", "incarnation": 1, "reason": event["reason"], "resume_step": 7, + "resume": {"source": "release", "step": 7, "ref": "r00000007-v7"}, "group": None} + assert json.loads(store.read("fleet/nodes/b300-3/claim.json"))["island"] == "isl" + journal = json.loads((tmp_path / "runs/run1/ssh-islands/isl-spares.json").read_text()) + assert journal["nodes"] == {"0": NAMES, "1": new} + assert [r["spare"] for r in journal["replacements"]] == ["b300-3"] + view = ops.spares_view("isl") + assert view["nodes"] == new and view["lost"] == [] and view["replacements"] == 1 + assert view["waiting_spare"] is False and view["spare_nodes"] == [NAMES[rank]] + assert str(ops.job_status("isl", 1)) == "RUNNING" + # the new incarnation's ledger row names its own nodes (a cleanup stops it there) + rows = {r.id: r for r in ResourceLedger(tmp_path / "ledger.jsonl").open_resources()} + assert [n["name"] for n in rows["run1/isl-i1"].attrs["nodes"]] == new + + +def test_a_restarted_launcher_follows_the_island_onto_its_spare(tmp_path): + cluster, ops, spares, store, _ = lost_island(tmp_path, extra=[spare(3)]) + assert ops.relaunch(None, "isl") == 1 + rec = ops.islands["isl"] + rec.lock.close() + for proc in rec.job.procs: + proc.terminate() + again = make_ops(tmp_path, cluster, health_every_s=0) + fresh, _ = make_spares(tmp_path, islands_spec(), [spare(3)]) + again.add("isl", islands_spec(), spares=fresh) # the inventory's island nodes, as at the start + assert [n.name for n in again.islands["isl"].spec.nodes] == ["b300-0", "b300-3", "b300-2"] + assert again.start("isl") == 1 # reattached on the spare, no second start + assert cluster.count("start", 1) == 3 and cluster.count("follow", 1) == 3 + assert ("follow", "b300-3", 1) in cluster.calls and ("status", "b300-1", 1) not in cluster.calls + + +def test_a_spare_whose_start_fails_is_quarantined_and_the_next_one_is_taken(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3), spare(4)]) + real = cluster.run + + def run(node, script, *, timeout=300.0): + if node.name == "b300-3" and script.startswith("docker pull"): + import subprocess + + return subprocess.CompletedProcess([], 1, stdout="", stderr="no space left on device") + return real(node, script, timeout=timeout) + + cluster.run = run + assert ops.relaunch(None, "isl") is None + assert "its start as a spare failed" in json.loads(store.read("fleet/nodes/b300-3/quarantine.json"))["reason"] + assert [n.name for n in ops.islands["isl"].spec.nodes] == NAMES # back on the old nodes + assert store.read("fleet/nodes/b300-3/claim.json") is None + clock.t += 61 + assert ops.relaunch(None, "isl") == 1 + assert [c[1] for c in cluster.calls if c[0] == "start" and c[2] == 1] == ["b300-0", "b300-4", "b300-2"] + + +# ------------------------------------------------------------------ 4.2: which spare +def test_a_spare_of_another_fabric_group_is_never_picked(tmp_path): + groups = ["A", "A", "A"] + cluster, ops, spares, store, clock = lost_island( + tmp_path, extra=[spare(3, "B"), spare(4, "A")], groups=groups) + assert ops.relaunch(None, "isl") == 1 + assert [c[1] for c in cluster.calls if c[0] == "start" and c[2] == 1] == ["b300-0", "b300-4", "b300-2"] + assert ("health", "b300-3") not in cluster.calls # not even checked + assert ops.island_events("isl")[-1]["group"] == "A" + + +def test_only_a_spare_of_another_group_is_waited_on(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3, "B")], groups=["A", "A", "A"]) + assert ops.relaunch(None, "isl") is None + waiting = [e for e in ops.island_events("isl") if e["kind"] == isp.WAITING_SPARE] + assert waiting and waiting[0]["reason"].startswith("fabric group A has no free healthy spare node") + assert "b300-3: fabric group B" in waiting[0]["reason"] + assert ops.waiting_spare("isl") + + +def test_quarantined_held_leased_and_unhealthy_spares_are_skipped(tmp_path): + leases = FakeLeases(held={"b300-5": "other-run/trainer@b"}) + extra = [spare(3), spare(4), spare(5), spare(6), spare(7), spare(8)] + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=extra, leases=leases) + spares.records.quarantine("b300-3", island="isl", reason="XID 79 earlier") + leases.blocked.add("b300-7") # its earlier run may still hold the cards: not taken over + assert spares.records.claim("b300-4", "isl-other") is None # another island of this run holds it + cluster.sick.add("b300-6") + assert ops.relaunch(None, "isl") == 1 + assert [c[1] for c in cluster.calls if c[0] == "start" and c[2] == 1] == ["b300-0", "b300-8", "b300-2"] + assert leases.holders["b300-8"] == "run1/trainer@launcher-a" + assert "b300-7" not in leases.holders and spares.records.holder("b300-7") is None # claim given back + # a quarantined, held or leased spare is skipped before any SSH to it; the sick one was checked + assert {c[1] for c in cluster.calls if c[0] == "health"} == {"b300-6", "b300-7", "b300-8"} + + +def test_a_released_node_can_be_picked_again(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[]) # no other spare: the lost node waits + assert ops.relaunch(None, "isl") is None and ops.waiting_spare("isl") + lost = ops.islands["isl"].spec.nodes[1] + cluster.unreachable.discard("b300-1") # repaired + clock.t += 61 + assert ops.relaunch(None, "isl") is None # still quarantined: not picked (its owed stop retried) + join_stops(spares) + leases = FakeLeases(held={"b300-1": "run1/trainer@launcher-a"}) + leases.keep_all(nodes=[lost]) # kept while it was quarantined + ok, message = isp.release_node(spares.records, lost, cluster, kill_grace_s=1, leases=leases) + assert ok, message + assert "b300-1" not in leases.holders # force_release once its owed stop ran + assert ("kill", "b300-1", 0) in cluster.calls # the stop it owed ran first + assert store.read("fleet/nodes/b300-1/quarantine.json") is None + clock.t += 121 + assert ops.relaunch(None, "isl") == 1 + assert [c[1] for c in cluster.calls if c[0] == "start" and c[2] == 1] == NAMES + + +def test_release_keeps_the_quarantine_while_the_owed_stop_fails(tmp_path): + cluster, ops, spares, store, _ = lost_island(tmp_path, extra=[spare(3)]) + ok, message = isp.release_node(spares.records, ops.islands["isl"].spec.nodes[1], cluster, kill_grace_s=1) + assert not ok and "rc 255" in message + assert store.read("fleet/nodes/b300-1/quarantine.json") is not None + + +def test_two_islands_of_a_run_never_take_one_spare(tmp_path): + records = NodeRecords(DirectoryObjectStore(tmp_path / "store"), run_id="run1", log=lambda m: None) + assert records.claim("b300-3", "isl-a") is None + assert records.claim("b300-3", "isl-b") == "isl-a" + assert records.claim("b300-3", "isl-a") is None # its own claim again + records.unclaim("b300-3", "isl-b") # not its claim: kept + assert records.holder("b300-3") == "isl-a" + + +def test_the_pick_goes_by_node_name(tmp_path): + extra = [spare(6), spare(4), spare(5)] + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=extra) + assert ops.relaunch(None, "isl") == 1 + assert ("start", "b300-4", 1) in cluster.calls + + +def test_spares_must_fit_the_island(): + island = spec(2).nodes + with pytest.raises(isp.SpareError, match="card_per_node|cards_per_node 4"): + isp.check_spares(island, [b300(3, roles=(isp.SPARE_ROLE,), cards_per_node=4)]) + with pytest.raises(isp.SpareError, match="roles trainer and trainer-spare"): + isp.check_spares(island, [b300(3, roles=("trainer", isp.SPARE_ROLE))]) + isp.check_spares(island, [b300(3, roles=(isp.SPARE_ROLE,))]) + assert isp.spare_nodes([*island, b300(3, roles=(isp.SPARE_ROLE,))]) == [b300(3, roles=(isp.SPARE_ROLE,))] + + +# ------------------------------------------------------------------ 4.4: waiting, limit, the fleet +def test_without_a_free_spare_the_island_waits_with_a_backoff(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + spares.records.claim("b300-3", "isl-other") + assert ops.relaunch(None, "isl") is None + events = ops.island_events("isl") + assert [e["kind"] for e in events] == [isp.NODE_LOST, isp.WAITING_SPARE] + assert events[1]["reason"].startswith("the inventory has no free healthy spare node (b300-1: quarantined") + assert "; b300-3: held by island isl-other); placement: the island needs 3 node(s); 2 of 4 candidate(s) are free" \ + in events[1]["reason"], events[1]["reason"] + assert events[1]["next_check_s"] == 60.0 + waits = [] + for _ in range(6): # each check after the backoff moves the next one further out + before, due = clock.t, spares.next_check + for _ in range(200): + assert ops.relaunch(None, "isl") is None + if spares.next_check != due: + break + clock.t += 10 + waits.append(clock.t - before) + assert waits == [60, 120, 240, 480, 900, 900] + assert ops.island_events("isl") == [] # the same reason: one event, not one per check + spares.records.unclaim("b300-3", "isl-other") # the other island is done with it + clock.t += 900 + assert ops.relaunch(None, "isl") == 1 + assert not ops.waiting_spare("isl") + + +def test_the_replacement_limit_stops_the_island(tmp_path): + extra = [spare(i) for i in range(3, 8)] + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=extra) + for k in range(3): + assert ops.relaunch(None, "isl") == k + 1 + victim = ops.islands["isl"].spec.nodes[1].name + cluster.lose(victim) + assert wait_for(lambda: ops.islands["isl"].job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", k + 1) + ops.island_events("isl") + with pytest.raises(RelaunchBlocked, match=r"3 node replacement\(s\) within 24 h \(max 3\)"): + ops.relaunch(None, "isl") + (event,) = ops.island_events("isl") + assert event["kind"] == isp.REPLACEMENT_LIMIT + assert [(r["lost"], r["spare"]) for r in event["replaced"]] == [ + ("b300-1", "b300-3"), ("b300-3", "b300-4"), ("b300-4", "b300-5")] + # a day later the window has room again (the count is kept on the wall clock) + ops.wall = lambda: 1e10 + spares.limited = False + assert ops.relaunch(None, "isl") == 4 + + +def _controller(ops, names=("isl",), **kw): + return FleetController(learners={n: (ops.islands[n].spec, 0) for n in names}, syncer=None, + sky_ops=RoutingOps(_SkySide(), None, ssh_ops=ops), poll_interval=30.0, + recover_timeout=kw.pop("recover_timeout", 600.0), thread_cls=_SyncThread, + fixed_roster=kw.pop("fixed_roster", False), **kw) + + +class FleetLog: + def __init__(self): + self.rows = [] + + def event(self, kind, name, **fields): + self.rows.append((kind, name, fields)) + + def maybe_tick(self): + pass + + def cost_tick(self): + pass + + +def test_the_fleet_waits_past_its_recover_timeout_for_a_spare_then_replaces(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + spares.records.claim("b300-3", "isl-other") + log = FleetLog() + ctl = _controller(ops, recover_timeout=600.0, fleet_log=log) + ctl.ops.sky_ops.t = 0.0 + ctl.ops.now = lambda: clock.t + rec = ctl.learners["isl"] + ctl._poll_recorded(rec) # FAILED -> recovering, first relaunch: waiting + assert rec["state"] == RECOVERING + for _ in range(40): # 40 polls of 30 s: far past the 600 s recover timeout + clock.t += 30 + ctl._poll_recorded(rec) + assert rec["state"] == RECOVERING # not given up while it waits for a spare + kinds = [k for k, _, _ in log.rows] + assert "island_node_lost" in kinds and "island_waiting_spare" in kinds + spares.records.unclaim("b300-3", "isl-other") + for _ in range(40): + clock.t += 30 + ctl._poll_recorded(rec) + if rec["state"] == RUNNING: + break + assert rec["state"] == RUNNING and rec["job_id"] == 1 + replaced = [f for k, _, f in log.rows if k == "island_node_replaced"] + assert replaced and replaced[0]["lost"] == "b300-1" and replaced[0]["spare"] == "b300-3" + assert replaced[0]["resume_step"] == 7 + + +def test_past_the_limit_the_island_is_given_up_and_the_fleet_goes_on(tmp_path): + """Two islands of one launch: the one that keeps losing nodes is given up at its + replacement limit (abandoned: run up's fleet.min_islands judges its record); the + other island runs on.""" + cluster = Cluster([*NAMES, "c-0", "c-1", *[f"b300-{i}" for i in range(3, 8)]]) + clock = Clock() + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=1) + s = islands_spec() + spares, _ = make_spares(tmp_path, s, [spare(i) for i in range(3, 8)], max_replacements=1) + ops.add("isl", s, spares=spares) + other = spec(2) + other = type(other)(**{**other.__dict__, "nodes": tuple(b300(20 + i) for i in range(2))}) + cluster.runs.update({n.name: {} for n in other.nodes}) + cluster.streams.update({n.name: [] for n in other.nodes}) + ops.add("other", other) + ops.start("isl") + ops.start("other") + log = FleetLog() + ctl = _controller(ops, names=("isl", "other"), recover_timeout=600.0, fleet_log=log) + ctl.ops.now = lambda: clock.t + cluster.lose("b300-1") + assert wait_for(lambda: ops.islands["isl"].job.procs[1].poll() is not None) + for _ in range(3): + for rec in ctl.learners.values(): + ctl._poll_recorded(rec) + assert ctl.learners["isl"]["job_id"] == 1 # the first loss: replaced + cluster.lose("b300-3") + assert wait_for(lambda: ops.islands["isl"].job.procs[1].poll() is not None) + for _ in range(3): + clock.t += 30 + for rec in ctl.learners.values(): + ctl._poll_recorded(rec) + assert ctl.learners["isl"]["state"] == ABANDONED + assert "ABANDONED" in ctl.learners["isl"]["exit"] + assert ctl.learners["other"]["state"] == RUNNING and str(ops.job_status("other", 0)) == "RUNNING" + assert cluster.count("start", 1) == 3 and ("start", "b300-20", 1) not in cluster.calls # never relaunched + limit = [f for k, n, f in log.rows if k == "island_replacement_limit"] + assert limit and [r["spare"] for r in limit[0]["replaced"]] == ["b300-3"] + + +# ------------------------------------------------------------------ 4.4: no spare node, as before +def test_an_inventory_without_spares_loses_a_node_as_before(tmp_path): + """The 6 x 8 B300 K3.1 layout takes every node: no spare. A lost node fails the island, + its stop is waited for on every node (the lost one too), no new start runs while it does + not answer, nothing is written under fleet/nodes, and the fleet gives the island up at + its recover timeout.""" + cluster, clock = Cluster(NAMES), Clock() + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=2) + ops.add("isl", islands_spec()) + ops.start("isl") + cluster.lose("b300-1") + assert wait_for(lambda: ops.islands["isl"].job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", 0) + assert "rank 1 (b300-1) does not answer over SSH (2 checks in a row)" in ops.islands["isl"].reason + assert cluster.count("kill", 0) == 2 and ("unanswered", "b300-1", "kill") in cluster.calls # asked too + assert ops.relaunch(None, "isl") is None and cluster.count("start", 1) == 0 + assert ops.island_events("isl") == [] and ops.spares_view("isl") is None and not ops.waiting_spare("isl") + assert not (tmp_path / "store").exists() + assert not (tmp_path / "runs/run1/ssh-islands/isl-spares.json").exists() + log = FleetLog() + ctl = _controller(ops, recover_timeout=600.0, fleet_log=log) + ctl.ops.now = lambda: clock.t + rec = ctl.learners["isl"] + for _ in range(30): + clock.t += 30 + ctl._poll_recorded(rec) + assert rec["state"] == ABANDONED + assert not [k for k, _, _ in log.rows if k.startswith(("island_node", "island_waiting", "island_replacement"))] + + +def test_the_dry_run_names_spares_only_when_the_inventory_has_them(tmp_path): + from yeto.launch.ssh_resident import dry_run_record + + s = spec(2) + args = SimpleNamespace(rl_node_inventory_nodes=list(s.nodes), tensor_parallel=1, pipeline_parallel=1, + context_parallel=1, training_mode="rl", rl_ssh_trainer_workdir="/opt/yeto") + assert "spares" not in dry_run_record(args, s, "isl") + args.rl_node_inventory_nodes = [*s.nodes, spare(3, "A")] + view = dry_run_record(args, s, "isl")["spares"] + assert view["nodes"] == ["b300-3"] and view["fabric_groups"]["b300-3"] == "A" + assert view["waiting_spare_s"] == [60.0, 900.0] and view["max_replacements"] == {"count": 3, "window_h": 24.0} + + +def test_spares_from_args_is_none_without_spare_nodes(tmp_path): + s = spec(2) + args = SimpleNamespace(rl_node_inventory_nodes=list(s.nodes), cluster_prefix="run1", rl_checkpoint_store=None) + assert isp.spares_from_args(args, s) is None + from dataclasses import replace + + args.rl_node_inventory_nodes = [*s.nodes, replace(b300(3, roles=(isp.SPARE_ROLE,), address=None), + host="ops@spare-alias")] + with pytest.raises(isp.SpareError, match="no rendezvous address"): + isp.spares_from_args(args, s) + + +def test_latest_checkpoint_step_reads_the_round_cut_then_the_release(tmp_path): + store = DirectoryObjectStore(tmp_path / "s") + assert isp.latest_checkpoint_step(store) is None + store.write("policy-releases/LATEST.json", json.dumps({"seq": 3, "version": 12, "path": "r3-v12"}).encode()) + assert isp.latest_checkpoint_step(store) == {"source": "release", "step": 12, "ref": "r3-v12", + "key": "policy-releases/LATEST.json"} + store.write("LATEST", json.dumps({"seq": 1, "cut_id": "r000009-i2"}).encode()) + assert isp.latest_checkpoint_step(store) == {"source": "round_cut", "step": 9, "ref": "r000009-i2", + "key": "LATEST"} + + +def test_the_health_hook_is_safe_in_or_out_of_the_lock_and_once_per_loss(tmp_path): + """The node health watch may call the hook from inside job_status's watch (the ops lock + held) or outside it, on the tick the node turned lost or again later: no deadlock, one + loss, one failure, one stop.""" + import threading + + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0) + s = islands_spec() + spares, _ = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + rec = ops.islands["isl"] + rec.health = {2: SimpleNamespace(record=lambda: {"notes": ["xid 79 since the last check"]})} + with ops._lock: # as from inside the watch + ops._node_health_lost(rec, 2, ["XID 79 on GPU 3"], READING) + assert "notes: xid 79 since the last check" in rec.reason + done = threading.Event() + worker = threading.Thread(target=lambda: (ops._node_health_lost(rec, 2, ["XID 79 on GPU 3"], READING), + done.set())) + worker.start() # outside the lock, from another thread, a later tick + assert done.wait(5.0) + assert [e["kind"] for e in ops.island_events("isl")] == [isp.NODE_LOST] + join_stops(spares) + assert cluster.count("kill", 0) == 3 # the lost node once (in the background), then the others + assert str(ops.job_status("isl", 0)) == "FAILED" + ops._node_health_lost(rec, 9, ["no such rank"], READING) # a rank of another layout: ignored + assert ops.relaunch(None, "isl") == 1 + + +def _inventory(tmp_path, nodes): + import yaml + + rows = [] + for n in nodes: + rows.append({"name": n.name, "host": n.host, "device_family": n.device_family, "cpu_arch": n.cpu_arch, + "card": n.card, "cards_per_node": n.cards_per_node, "hbm_gib": n.hbm_gib, + "host_memory_gib": n.host_memory_gib, "fabric": n.fabric, "address": n.address, + "runtime": n.runtime, "image": n.image, "docker_args": list(n.docker_args), + **({"roles": list(n.roles)} if n.roles else {})}) + path = tmp_path / "inventory.yaml" + path.write_text(yaml.safe_dump({"nodes": rows})) + return str(path) + + +def test_release_node_checks_the_node_runs_its_owed_stops_and_removes_its_record(tmp_path): + cluster, ops, spares, store, _ = lost_island(tmp_path, extra=[spare(3)]) + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + lines = [] + common = dict(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, objects=store, + kill_grace_s=1, say=lines.append) + assert isp.release_node_main(**common, dry_run=True) == 0 + assert any("owes the stop of isl incarnation 0 (rank 1, container yeto-run1-isl-i0-n1)" in ln for ln in lines) + assert store.read("fleet/nodes/b300-1/quarantine.json") is not None + assert isp.release_node_main(**common) == 1 # still unreachable: the check fails, the record stays + assert "stays quarantined: unreachable" in lines[-1] + cluster.unreachable.discard("b300-1") + cluster.sick.add("b300-1") + assert isp.release_node_main(**common) == 1 and "unhealthy" in lines[-1] + cluster.sick.clear() + leases = FakeLeases(held={"b300-1": "run1/trainer@launcher-a"}) + assert isp.release_node_main(**common, leases=leases) == 0 + assert ("kill", "b300-1", 0) in cluster.calls and store.read("fleet/nodes/b300-1/quarantine.json") is None + assert "b300-1" not in leases.holders and "released (1 owed stop(s) run)" in lines[-1] + assert isp.release_node_main(**common) == 0 and "is not quarantined" in lines[-1] + assert isp.release_node_main(**{**common, "name": "nope"}) == 2 + + +def test_a_node_whose_ssh_fails_is_unreachable_whatever_the_checker_reads(): + cluster = Cluster(["b300-3"]) + cluster.unreachable.add("b300-3") + assert isp.node_check(spare(3), cluster, multi=True) == (False, "unreachable (rc 255)") + cluster.unreachable.clear() + assert isp.node_check(spare(3), cluster, multi=True) == (True, "healthy") + + +def test_a_spare_of_the_reserved_unavailable_group_never_joins_a_multi_node_island(tmp_path): + cluster, ops, spares, store, clock = lost_island( + tmp_path, extra=[spare(3, "unavailable"), spare(4, "A")], groups=["A", "A", "A"]) + spares.records.claim("b300-4", "isl-other") + assert ops.relaunch(None, "isl") is None # only the unavailable one is left: waiting + reason = [e for e in ops.island_events("isl") if e["kind"] == isp.WAITING_SPARE][0]["reason"] + assert "b300-3: fabric group unavailable (never in a multi-node island)" in reason + assert ("health", "b300-3") not in cluster.calls + + +def test_a_spare_whose_claim_is_lost_to_another_island_is_excluded_and_the_next_one_taken(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3), spare(4)]) + real = spares.records.claim + + def racing(name, island): # another island of the run claims b300-3 between the read and the claim + if name == "b300-3": + real(name, "isl-other") + return real(name, island) + + spares.records.claim = racing + assert ops.relaunch(None, "isl") == 1 + assert ("start", "b300-4", 1) in cluster.calls + assert spares.records.holder("b300-3") == "isl-other" + + +def test_the_pick_asks_pick_placement_and_excludes_a_failed_candidate(tmp_path, monkeypatch): + """The real fabric_groups.pick_placement: the island's nodes that stay are ``required`` + (need: the island's size), every node that is out is in ``excluded`` with its reason + (the lost node quarantined), and a spare whose health check fails is added to it, with + the check's reason, before the pick asks again.""" + from yeto.launch import fabric_groups + + asked = [] + real = fabric_groups.pick_placement + + def pick_placement(candidates, need, *, excluded=(), required=(), inventory=None): + asked.append(([n.name for n in candidates], need, dict(excluded), [n.name for n in required])) + return real(candidates, need, excluded=excluded, required=required, inventory=inventory) + + monkeypatch.setattr(fabric_groups, "pick_placement", pick_placement) + cluster, ops, spares, store, clock = lost_island( + tmp_path, extra=[spare(3, "A"), spare(4, "A"), spare(5, "B")], groups=["A", "A", "A"]) + cluster.sick.add("b300-3") + assert ops.relaunch(None, "isl") == 1 + assert ("start", "b300-4", 1) in cluster.calls + stay = ["b300-0", "b300-2"] + pool = [*stay, "b300-1", "b300-3", "b300-4"] # b300-5 of group B is no candidate + assert all(a[0] == pool and a[1] == 3 and a[3] == stay for a in asked) + first, second = asked[0][2], asked[1][2] + assert list(first) == ["b300-1"] and first["b300-1"].startswith("quarantined (rank 1 (b300-1)") + assert sorted(second) == ["b300-1", "b300-3"] and second["b300-3"] == "unhealthy: XID 79 on GPU 3" + assert len(asked) == 4 # the checks first (outside the ops lock), then the pick under it: the same order + assert started(cluster, 1) == ["b300-0", "b300-4", "b300-2"] # the nodes that stay, unchanged + + +def started(cluster, k): + return [c[1] for c in cluster.calls if c[0] == "start" and c[2] == k] + + +def test_a_replacement_keeps_the_nodes_that_stay_when_another_group_has_more_free_nodes(tmp_path): + extra = [spare(3, "A"), *(spare(i, "B") for i in range(4, 8))] + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=extra, groups=["A", "A", "A"]) + assert ops.relaunch(None, "isl") == 1 + assert started(cluster, 1) == ["b300-0", "b300-3", "b300-2"] # not moved to group B's four free nodes + + +def test_a_placement_error_is_the_wait_reason_and_other_errors_are_raised(tmp_path, monkeypatch): + from yeto.launch import fabric_groups + + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3, "B")], groups=["A", "A", "A"]) + assert ops.relaunch(None, "isl") is None and ops.waiting_spare("isl") + reason = spares.wait_reason + assert "placement: the island needs 3 healthy nodes of one fabric group" in reason, reason + a0, a1, a2 = grouped(b300(0), "A"), grouped(b300(1), "A"), spare(2, "A") + with pytest.raises(TypeError): # one string as excluded: the real function's TypeError is raised + fabric_groups.pick_placement([a0, a1, a2], 3, excluded="b300-1") + + def broken(candidates, need, *, excluded=(), required=(), inventory=None): + raise TypeError("a bug inside pick_placement") + + monkeypatch.setattr(fabric_groups, "pick_placement", broken) + with pytest.raises(TypeError, match="a bug inside"): + isp._pick_placement([a2], 3, required=[a0, a1]) + + +def test_a_placement_that_moves_a_node_that_stays_is_no_placement(monkeypatch): + from yeto.launch import fabric_groups + + a0, a1, a2, a3 = grouped(b300(0), "A"), grouped(b300(1), "A"), spare(2, "A"), spare(3, "A") + assert isp._pick_placement([a2, a3], 3, required=[a0, a1])[0].name == "b300-2" + node, why = isp._pick_placement([a2, a3], 3, required=[a0, a1], excluded={"b300-1": "quarantined"}) + assert node is None and "required node(s) excluded: b300-1: quarantined" in why + monkeypatch.setattr(fabric_groups, "pick_placement", lambda candidates, need, *, excluded=(), required=(), + inventory=None: SimpleNamespace(group="A", nodes=(a0, a2, a3))) # drops b300-1 + node, why = isp._pick_placement([a2, a3], 3, required=[a0, a1]) + assert node is None and "drops a node that stays" in why + + +def test_the_release_node_command_parses_its_flags_and_runs_release_node_main(tmp_path): + import argparse + + from yeto import cluster_release_node as crn + + cluster, ops, spares, store, _ = lost_island(tmp_path, extra=[spare(3)]) + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + parser = argparse.ArgumentParser(prog="yeto cluster") + crn.add_parser(parser.add_subparsers(dest="cluster_command")) + args = parser.parse_args(["release-node", "b300-1", "--inventory", inv, "--store", str(tmp_path / "store"), + "--dry-run", "--kill-grace-s", "5"]) + assert (args.cluster_command, args.name, args.dry_run, args.force, args.kill_grace_s) == ( + "release-node", "b300-1", True, False, 5) + lines = [] + assert crn.main(args, ssh=cluster, objects=store, say=lines.append) == 0 + assert any("dry run: would check b300-1, run 1 stop(s)" in ln for ln in lines) + assert lines[-1] == "[yeto] no lease store: no lease to end" + assert store.read("fleet/nodes/b300-1/quarantine.json") is not None + args = parser.parse_args(["release-node", "b300-9", "--inventory", inv, "--store", str(tmp_path / "store")]) + assert crn.main(args, ssh=cluster, objects=store, say=lines.append) == 2 # not in the inventory + + +def test_yeto_cluster_release_node_runs_from_the_cluster_command(tmp_path, capsys): + import argparse + + from yeto import cluster_cli + + cluster, ops, spares, store, _ = lost_island(tmp_path, extra=[spare(3)]) + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + parser = argparse.ArgumentParser(prog="yeto") + cluster_cli.add_parser(parser.add_subparsers(dest="command")) + args = parser.parse_args(["cluster", "release-node", "b300-1", "--inventory", inv, "--store", + str(tmp_path / "store"), "--dry-run"]) + assert cluster_cli.main(args) == 0 # the documented dry run: no SSH, nothing removed + out = capsys.readouterr().out + assert "node b300-1: quarantined by island isl of run run1" in out + assert "dry run: would check b300-1, run 1 stop(s) and remove fleet/nodes/b300-1/quarantine.json" in out + assert store.read("fleet/nodes/b300-1/quarantine.json") is not None + usage = argparse.ArgumentParser(prog="yeto") + cluster_cli.add_parser(usage.add_subparsers(dest="command")) + with pytest.raises(SystemExit): + usage.parse_args(["cluster", "--help"]) + assert "{probe,check,release-node}" in capsys.readouterr().out diff --git a/tests/test_ssh_island_spares_e2e.py b/tests/test_ssh_island_spares_e2e.py new file mode 100644 index 000000000..bf37bfdaa --- /dev/null +++ b/tests/test_ssh_island_spares_e2e.py @@ -0,0 +1,307 @@ +"""A resident ssh: trainer island replaces a lost node while the fleet trains, end to end +(own-cluster-fleet-stability 4.3): the real Rust syncer, a local store, the fleet +controller over SshIslandOps and the fake SSH cluster, fake trainers (rank 0 of each +incarnation is one syncer client of the island's learner id; no Ray, no GPU). + +Two islands train: island 0 is a plain syncer client of learner 0 for the whole run; +island 1 is a two-node ssh: island (learner 1) whose inventory holds one spare node. +Its rank 0 node loses power while it holds a PULL (no LEAVE: the machine is just gone). +The controller judges the node lost (its stream ended, no SSH answer twice), the island +is stopped on its other node, the spare takes rank 0's place and the next incarnation +resumes from the newest checkpoint of its store under the same learner id: to the syncer +a short absence, then a re-JOIN that catches up to the newest outer weights before it +merges again. As in the move test (test_fleet_island_move_e2e) the replacement starts +after island 1's lease, so the round it held merges without it, and island 0 does not run +ahead of the rounds open at the loss while island 1 is away. + +Checked: the merge sequence has every step once (1..N, none twice), no fragment is pushed +twice, the resume step is the newest checkpoint's step, the final weights and the +catch-up equal the f32 Nesterov recomputation (1e-6), and island 0 runs on one +connection from start to end.""" + +from __future__ import annotations + +import json +import secrets +import subprocess +import time +from types import SimpleNamespace + +import numpy as np +import pytest + +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 MAX_LEARNERS, P, POOL, _client, _delta, _nesterov, _outer_steps, _values +from test_rl_ssh_resident import Clock, _SyncThread, _cards, b300, make_ops, spec # noqa: F401 - _cards: autouse +from test_ssh_island_spares import Cluster, FleetLog, _health, spare # noqa: F401 - _health: autouse +from yeto.launch import island_spares as isp +from yeto.launch.fleet import RUNNING, FleetController +from yeto.launch.island_spares import IslandSpares, NodeRecords, latest_checkpoint_step +from yeto.modal_runner import RoutingOps +from yeto.rl.engine.object_store import DirectoryObjectStore + +LEASE_S = float(POOL[POOL.index("--rl-sync-island-lease-s") + 1]) # 5 s +TOLERANCE_S = 1.5 +RETURN_AFTER_S = LEASE_S + 3 # the controller sees the loss (and replaces) this long after it +# where the trainer of learner 1 (samplers following it) keeps its newest release: its own +# trainer1/ sub-store; the launcher finds it through resume_keys of the launch's args +CHECKPOINT = "trainer1/policy-releases/LATEST.json" +ARGS = SimpleNamespace(rl_sample_role="trainer", rl_single_island_no_sync=False, rl_island_sample_role=None, + rl_sampler_follow="trainer", rl_backend="miles", rl_max_policy_age=2, + rl_checkpoint_store="/store", rl_island_buffer_shards=["0:a", "1:b"], + rl_island_release_every=None, rl_island_max_policy_age=None) + + +def _own_checkpoint(store): + """The fake trainer's resume: its own release, read as it writes it (not via the launcher).""" + raw = store.read(CHECKPOINT) + return None if raw is None else json.loads(raw)["version"] + + +class Sky: + def __init__(self, clock): + self.clock = clock + + def now(self): + return self.clock.t + + def sleep(self, s): + self.clock.t += s + + +class TrainerCluster(Cluster): + """The fake SSH cluster whose rank 0 start of island 1 is a fake trainer: a syncer + client of learner 1 that resumes from its store's newest checkpoint; its stop (or its + node's power loss) closes the client without a LEAVE.""" + + def __init__(self, names, *, port, profile_hash, store): + super().__init__(names) + self.port, self.profile_hash, self.store = port, profile_hash, store + self.trainers: dict[int, dict] = {} # incarnation -> {client, node, resume, catching} + self.current: int | None = None + + def start(self, node, script): + stream = super().start(node, script) + if "setsid bash -c" in script and "export SKYPILOT_NODE_RANK=0\n" in script: + k = self._k(script) + checkpoint = _own_checkpoint(self.store) + client = _client(1, self.port, self.profile_hash) + client.start() + self.trainers[k] = {"client": client, "node": node.name, + "resume": checkpoint, + "catching": {} if k > 0 else None, "closed": False} + self.current = k + return stream + + def run(self, node, script, *, timeout=300.0): + done = super().run(node, script, timeout=timeout) + if "kill -TERM" in script and done.returncode == 0: + k = self._k(script) + trainer = self.trainers.get(k) + if trainer is not None and trainer["node"] == node.name: + self.close_trainer(k) + return done + + def close_trainer(self, k): + trainer = self.trainers[k] + if not trainer["closed"]: + trainer["closed"] = True + trainer["client"].close() # torn down / power lost: the connection just drops + + def live(self): + k = self.current + if k is None or self.trainers[k]["closed"]: + return None + return self.trainers[k] + + +@needs_cargo +def test_an_island_replaces_a_lost_node_and_the_fleet_merges_on(syncer_binary, tmp_path, monkeypatch): # noqa: F811 + monkeypatch.setenv("YETO_ISLAND_HMAC_KEY", f"spare-test-key-{secrets.token_hex(6)}") + total_steps, lose_at = 10, 3 + process, port, profile_hash = _start_async_syncer(syncer_binary, tmp_path, *POOL, total_steps=total_steps, + log_file=tmp_path / "syncer.log") + store = DirectoryObjectStore(tmp_path / "store") # island 1's run store: checkpoints, node records + names = ["b300-0", "b300-1", "b300-3"] + cluster = TrainerCluster(names, port=port, profile_hash=profile_hash, store=store) + clock = Clock() + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=2) + island = spec(2) + spares = IslandSpares(pool=(*island.nodes, spare(3)), records=NodeRecords(store, run_id="run1", log=lambda m: None), + resume_probe=lambda: latest_checkpoint_step(store, isp.resume_keys(ARGS, 1, 2))) + ops.add("isl1", island, spares=spares) + log = FleetLog() + ctl = FleetController(learners={"isl1": (island, 0)}, syncer=None, sky_ops=RoutingOps(Sky(clock), None, ssh_ops=ops), + poll_interval=30.0, recover_timeout=600.0, thread_cls=_SyncThread, fixed_roster=False, + fleet_log=log) + rec = ctl.learners["isl1"] + + island0 = _client(0, port, profile_hash) + generation0 = None + versions = {k: [0] * P for k in range(MAX_LEARNERS)} + pushed: list[tuple[int, int, int]] = [] # (learner, fragment, global step) of every push + seen: dict[int, set] = {0: set(), 1: set()} # island 1's survive its incarnations (its checkpoint) + held: dict[int, list] = {0: [], 1: []} + state = {"lost_at": None, "unanswered": [], "catch_up": {}, "checkpoints": [], "back": False} + beat = [0.0] + polled = [0.0] + + def away() -> bool: + return state["lost_at"] is not None and not state["back"] + + def checkpoint(step: int) -> None: + if not state["checkpoints"] or state["checkpoints"][-1] < step: + state["checkpoints"].append(step) + store.write(CHECKPOINT, json.dumps({"seq": len(state["checkpoints"]), "version": step, + "path": f"r{step:08d}-v{step}"}).encode()) + + def drain(k, client, trainer=None): + client.check_health() + if trainer is not None and trainer["catching"] is not None: # the re-JOIN applies its catch-up first + caught = trainer["catching"] + for update in client.drain_updates(): + caught.setdefault(update.fragment_id, (update.version, _values(update.data))) + held[k].extend(client.drain_pulls()) + if len(caught) < P: + return + versions[k] = [caught[fid][0] for fid in range(P)] + state["catch_up"] = dict(caught) + trainer["catching"] = None + state["back"] = True + for update in client.drain_updates(): + versions[k][update.fragment_id] = max(versions[k][update.fragment_id], update.version) + if k == 1: + checkpoint(min(versions[1])) # the trainer's newest checkpoint follows its outer weights + later = [] + for permit in held[k] + client.drain_pulls(): + if k == 0 and away() and state["unanswered"] and \ + permit.global_step > max(p.global_step for p in state["unanswered"]): + later.append(permit) # island 0 does not run ahead while island 1 is away + continue + key = (permit.global_step, permit.round_attempt) + if key in seen[k]: + continue + if k == 1 and state["lost_at"] is None and min(versions[0]) >= lose_at: + # island 1 holds this PULL when its rank 0 node loses power + state["unanswered"] = [permit] + state["lost_at"] = time.monotonic() + state["newest_at_loss"] = state["checkpoints"][-1] if state["checkpoints"] else None + cluster.close_trainer(cluster.current) + cluster.lose(trainer["node"]) + return + seen[k].add(key) + base = versions[k][permit.fragment_id] + client.push_fragment(permit.fragment_id, permit.global_step, permit.round_attempt, base, + permit.global_step, 1, 7, _f32(_delta(k, permit.global_step))) + pushed.append((k, permit.fragment_id, permit.global_step)) + held[k] = later + + def poll(): + nonlocal generation0 + if time.monotonic() - beat[0] > 1: # the islands renew their leases (5 s) while they wait + beat[0] = time.monotonic() + island0.heartbeat(0) + if cluster.live() is not None: + cluster.live()["client"].heartbeat(0) + if generation0 is None: + generation0 = island0.connection_generation + drain(0, island0) + trainer = cluster.live() + if trainer is not None: + drain(1, trainer["client"], trainer) + if (state["lost_at"] is not None and time.monotonic() - state["lost_at"] >= RETURN_AFTER_S + and time.monotonic() - polled[0] > 0.1): + polled[0] = time.monotonic() + clock.t += 30 + ctl._poll_recorded(rec) # the fleet controller's poll of island 1 + trainer = cluster.live() + return (state["back"] and trainer is not None and island0.finalizing.is_set() + and trainer["client"].finalizing.is_set()) + + finals = {} + try: + island0.start() + assert ops.start("isl1") == 0 + for fid in range(P): + island0.send_init(fid, _f32(_initial(fid))) + _wait(poll, "the fleet never finalized", timeout=180) + for k, client in ((0, island0), (1, cluster.live()["client"])): + manifest, fragments = client.wait_for_final_fragments(timeout=30) + finals[k] = {f.fragment_id: _values(f.data) for f in fragments} + client.acknowledge_finalization(manifest) + assert process.wait(timeout=15) == 0 + finally: + island0.close() + for k in list(cluster.trainers): + cluster.close_trainer(k) + ops.close() + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=10) + raise + + # the controller replaced the lost rank 0 node by the spare: same learner id, same layout + assert rec["state"] == RUNNING and rec["job_id"] == 1 and rec["relaunches"] == 1 + assert [n.name for n in ops.islands["isl1"].spec.nodes] == ["b300-3", "b300-1"] + assert cluster.trainers[1]["node"] == "b300-3" + rows = {kind: fields for kind, _, fields in log.rows if kind.startswith("island_node")} + assert rows["island_node_lost"]["node"] == "b300-0" and rows["island_node_lost"]["rank"] == 0 + replaced = rows["island_node_replaced"] + assert (replaced["lost"], replaced["spare"], replaced["rank"], replaced["incarnation"]) == ("b300-0", "b300-3", 0, 1) + assert json.loads(store.read("fleet/nodes/b300-0/quarantine.json"))["island"] == "isl1" + assert ("kill", "b300-1", 0) in cluster.calls # the island was stopped on its other node + assert ("unanswered", "b300-0", "kill") not in cluster.calls # the lost node was not waited for + + # it resumed from the newest checkpoint of its store, and the event says which + newest = state["newest_at_loss"] + assert cluster.trainers[1]["resume"] == replaced["resume_step"] == newest + assert replaced["resume"] == {"source": "release", "step": newest, "ref": f"r{newest:08d}-v{newest}", + "key": CHECKPOINT} + assert newest >= lose_at - 1 + + # the merge sequence: every global step of every fragment once, no fragment pushed twice + tape_text = (tmp_path / "tape.jsonl").read_text() + tape = tape_text.splitlines() + events = [json.loads(line) for line in tape] + steps = _outer_steps(tape_text) + assert [r["step"] for r in steps] == list(range(1, total_steps * P + 1)) + assert len(pushed) == len(set(pushed)) + for record in steps: + learners = [int(e[0]) for e in record["raw_weights"]] + assert len(learners) == len(set(learners)), record + assert abs(sum(float(e[2]) for e in record["weights"]) - 1.0) < 1e-9 + assert {int(e[0]) for r in steps for e in r["raw_weights"]} == {0, 1} # no third learner id + assert [r for r in steps if r["timed_out"]] == [] + + # the syncer saw island 1 go (no LEAVE: its machine was gone) and come back under its id + (gone,) = [e for e in events if e.get("kind") == "pool_leave"] + assert int(gone["island_id"]) == 1 and gone["reason"] == "disconnected" + at_leave = next(i for i, line in enumerate(tape) if '"pool_leave"' in line) + later = [json.loads(line) for line in tape[at_leave:] if '"kind":"outer_step"' in line] + assert any(int(e[0]) == 1 for r in later for e in r["raw_weights"]), "island 1 never merged again" + record = {(r["step"], r["fragment"]): r for r in steps} + for permit in state["unanswered"]: # the round it held waited one lease, then merged without it + r = record[(permit.global_step, permit.fragment_id)] + waited = r["time_unix"] - gone["time_unix"] + assert LEASE_S - 0.5 <= waited <= LEASE_S + TOLERANCE_S, (waited, r) + assert 1 not in {int(e[0]) for e in r["raw_weights"]} + + # island 0 was never interrupted: one connection, a push in every merged round + assert island0.connection_generation == generation0 + assert all(0 in {int(e[0]) for e in r["raw_weights"]} for r in steps) + + # the catch-up of the re-JOIN and the final weights: the f32 Nesterov recomputation + assert sorted(state["catch_up"]) == list(range(P)) + for fid, (version, values) in state["catch_up"].items(): + np.testing.assert_allclose(values, _nesterov(steps, upto=version)[fid], rtol=0, atol=1e-6) + expected = _nesterov(steps) + assert finals.keys() == {0, 1} + for fid in range(P): + assert np.array_equal(finals[0][fid], finals[1][fid]) + np.testing.assert_allclose(finals[0][fid], expected[fid], rtol=0, atol=1e-6) + assert isp.NODE_REPLACED in {k for k, _, _ in log.rows} diff --git a/tests/test_ssh_island_spares_recovery.py b/tests/test_ssh_island_spares_recovery.py new file mode 100644 index 000000000..36e62b6d3 --- /dev/null +++ b/tests/test_ssh_island_spares_recovery.py @@ -0,0 +1,1791 @@ +"""Spare nodes of a resident ssh: trainer island, the recovery details +(yeto.launch.island_spares, own-cluster-fleet-stability 4.1-4.3): the usual loss order of a +power cut (rank 0 exits first, the lost node's stream ends minutes later), the longest +wait for a spare, what a lost node owes on the ledger, the per-learner resume point, the +health check a pick and a release need, the lease release, the quarantine shared through +the lease store (and a launcher restarted while it waits), a stale health reading, the +checks outside the ops lock, a store without an atomic create. + +Over the fake SSH cluster of test_rl_ssh_resident and the fakes of test_ssh_island_spares.""" + +from __future__ import annotations + +import json +import threading +from types import SimpleNamespace + +import pytest + +from test_rl_ssh_resident import Clock, _cards, b300, make_ops, spec, wait_for # noqa: F401 - _cards: autouse +from test_ssh_island_spares import ( + NAMES, + READING, + Cluster, + FakeLeases, + FleetLog, + _controller, + _health, # noqa: F401 - autouse: the fake health checker + _inventory, + islands_spec, + join_stops, + lost_island, + make_spares, + spare, +) +from tests.test_run_up_fleet import _cfg, files # noqa: F401 - files: fixture +from tests.test_run_up_fleet_runtime import fleet_run # noqa: F401 - fixture +from yeto.cost.ledger import ResourceLedger +from yeto.launch import island_spares as isp +from yeto.launch.fleet import ABANDONED, RECOVERING, RUNNING, FixedRosterIslandAbandoned, RelaunchBlocked +from yeto.launch.island_spares import IslandSpares, NodeRecords +from yeto.rl.engine.object_store import DirectoryObjectStore + + +def started(cluster, k): + return [c[1] for c in cluster.calls if c[0] == "start" and c[2] == k] + + +def open_rows(tmp_path): + return sorted(r.id for r in ResourceLedger(tmp_path / "ledger.jsonl").open_resources()) + + +# ------------------------------------------------------------------ H1: rank 0 exits first +def _rank0_exits_while(tmp_path, *, polls=2): + """An island whose rank 0 exits (its collective failed) while node b300-1 does not answer + over SSH and its stream still looks open: the release does not confirm b300-1's stop.""" + cluster, clock = Cluster([*NAMES, "b300-3"]), Clock() + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=polls) + s = islands_spec() + spares, store = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + rec = ops.islands["isl"] + cluster.unreachable.add("b300-1") + cluster.exit("b300-0", 0, 1) + assert wait_for(lambda: rec.job.procs[0].poll() is not None) + assert str(ops.job_status("isl", 0)) == "FAILED" + assert rec.job.procs[1].poll() is None # its stop is not confirmed: its stream stays open + assert rec.job.procs[2].poll() is not None # a confirmed node's stream is ended + assert spares.unconfirmed == {1} and spares.lost == {} + return cluster, ops, spares, store, rec + + +def test_rank_0_exits_first_and_the_lost_nodes_stream_ends_minutes_later(tmp_path): + """A power cut: the dead node's stream ends minutes after rank 0 exited; then + ``unreachable_polls`` checks without an answer make it lost.""" + cluster, ops, spares, store, rec = _rank0_exits_while(tmp_path) + for _ in range(2): # its stream still open: two checks are not enough + assert ops.relaunch(None, "isl") is None + assert spares.lost == {} + cluster.drop("b300-1") # the keepalive gives up: its stream ends + assert wait_for(lambda: rec.job.procs[1].poll() is not None) + assert ops.relaunch(None, "isl") == 1 # the stream ended and no answer: lost, replaced + assert started(cluster, 1) == ["b300-0", "b300-3", "b300-2"] + (lost,) = [e for e in ops.island_events("isl") if e["kind"] == isp.NODE_LOST] + assert lost["node"] == "b300-1" and "its stream ended and it does not answer over SSH (3 checks" in lost["reason"] + assert str(ops.job_status("isl", 1)) == "RUNNING" + assert open_rows(tmp_path) == ["run1/isl-i0-owed-b300-1", "run1/isl-i1"] + assert json.loads(store.read("fleet/nodes/b300-1/quarantine.json"))["owed"][0]["incarnation"] == 0 + + +def test_a_node_whose_stream_never_ends_is_lost_after_twice_the_checks(tmp_path): + cluster, ops, spares, store, rec = _rank0_exits_while(tmp_path) + for _ in range(3): + assert ops.relaunch(None, "isl") is None + assert spares.lost == {} and rec.job.procs[1].poll() is None + assert ops.relaunch(None, "isl") == 1 # 2 x unreachable_polls checks: lost + (lost,) = [e for e in ops.island_events("isl") if e["kind"] == isp.NODE_LOST] + assert "its stop was not confirmed, its stream still open, and it does not answer over SSH (4 checks" \ + in lost["reason"] + + +def test_sshd_refusing_new_sessions_while_the_old_one_lives_is_no_loss(tmp_path): + cluster, ops, spares, store, rec = _rank0_exits_while(tmp_path) + for _ in range(3): # three refusals in a row, its old connection alive + assert ops.relaunch(None, "isl") is None + cluster.unreachable.discard("b300-1") # sshd takes sessions again + assert ops.relaunch(None, "isl") == 1 + assert started(cluster, 1) == NAMES and spares.lost == {} # the same nodes, nothing quarantined + assert store.read("fleet/nodes/b300-1/quarantine.json") is None + + +# ------------------------------------------------------------------ M1: the longest wait +def test_a_wait_past_max_wait_gives_the_island_up_with_an_hourly_report(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)], max_wait_s=3 * 3600.0) + spares.records.claim("b300-3", "isl-other") + wall = [5000.0] + ops.wall = lambda: wall[0] + ops.island_events("isl") + assert ops.relaunch(None, "isl") is None + (first,) = [e for e in ops.island_events("isl") if e["kind"] == isp.WAITING_SPARE] + assert first["elapsed_s"] == 0 + journal = json.loads((tmp_path / "runs/run1/ssh-islands/isl-spares.json").read_text()) + assert journal["waiting_since"] == 5000.0 # a restarted launcher keeps the wait's start + for _ in range(35): # every 5 minutes, up to 2 h 55 min + clock.t += 300 + wall[0] += 300 + assert ops.relaunch(None, "isl") is None + hourly = [e for e in ops.island_events("isl") if e["kind"] == isp.WAITING_SPARE] + assert [e["elapsed_s"] for e in hourly] == [3600, 7200] + assert all("b300-3: held by island isl-other" in e["reason"] for e in hourly) + clock.t += 300 + wall[0] += 300 + with pytest.raises(RelaunchBlocked, match=r"waited 10800 s for a spare node .*--spare-max-wait-s"): + ops.relaunch(None, "isl") + (given_up,) = ops.island_events("isl") + assert given_up["kind"] == isp.WAITING_SPARE and given_up["given_up"] is True + + +def test_spare_max_wait_s_reaches_the_island(tmp_path): + s = islands_spec() + args = SimpleNamespace(rl_node_inventory_nodes=[*s.nodes, spare(3)], cluster_prefix="run1", + rl_checkpoint_store=str(tmp_path / "store"), spare_max_wait_s=600.0) + assert isp.spares_from_args(args, s).max_wait_s == 600.0 + assert isp.spares_from_args(SimpleNamespace(**{**vars(args), "spare_max_wait_s": None}), s).max_wait_s == 86400.0 + assert isp.spare_view(args, s)["max_wait_s"] == 600.0 + + +@pytest.mark.parametrize("fixed_roster", [False, True]) +def test_the_fleet_gives_a_waiting_island_up_at_max_wait_also_with_a_fixed_roster(tmp_path, fixed_roster, capsys): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)], max_wait_s=1800.0) + spares.records.claim("b300-3", "isl-other") + ops.wall = lambda: clock.t + ctl = _controller(ops, recover_timeout=600.0, fleet_log=FleetLog(), fixed_roster=fixed_roster) + ctl.ops.sky_ops.t = 0.0 + ctl.ops.now = lambda: clock.t + rec = ctl.learners["isl"] + ctl._poll_recorded(rec) + assert rec["state"] == RECOVERING + for _ in range(50): # 25 min: past the recover timeout, short of the longest wait + clock.t += 30 + ctl._poll_recorded(rec) + assert rec["state"] == RECOVERING + err = capsys.readouterr().err + # while it waits, the controller's retry line comes every 15 min, not every poll + assert 1 <= err.count("relaunch attempt for isl failed (waiting for a spare node); will retry") <= 2 + assert "relaunch attempt for isl failed; will retry" not in err + assert err.count("while it waits for a spare node; not given up") == 1 + with pytest.raises(FixedRosterIslandAbandoned) if fixed_roster else _nothing(): + for _ in range(20): + clock.t += 30 + ctl._poll_recorded(rec) + if rec["state"] == ABANDONED: + break + assert rec["state"] == ABANDONED and "waited" in capsys.readouterr().err + + +class _nothing: + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +def test_each_wait_for_a_spare_is_said_again(tmp_path, capsys): + extra = [spare(3), spare(4)] + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=extra) + spares.records.claim("b300-3", "isl-other") + spares.records.claim("b300-4", "isl-other") + ctl = _controller(ops, recover_timeout=300.0, fleet_log=FleetLog()) + ctl.ops.sky_ops.t = 0.0 + ctl.ops.now = lambda: clock.t + rec = ctl.learners["isl"] + + def wait_then_free(name): + for _ in range(20): # past the recover timeout while it waits + clock.t += 30 + ctl._poll_recorded(rec) + spares.records.unclaim(name, "isl-other") + for _ in range(40): + clock.t += 30 + ctl._poll_recorded(rec) + if rec["state"] == RUNNING: + return + raise AssertionError("not replaced") + + ctl._poll_recorded(rec) + wait_then_free("b300-3") + cluster.lose("b300-3") # the spare is lost too: a second wait + assert wait_for(lambda: ops.islands["isl"].job.procs[1].poll() is not None) + wait_then_free("b300-4") + assert capsys.readouterr().err.count("while it waits for a spare node; not given up") == 2 + + +def _runtime(islands, min_islands, records, absent_after_s=3600.0): + """A fleet runtime of ``islands`` names over island ``records`` (no run behind it).""" + from yeto.rl import up_fleet_runtime + + rt = up_fleet_runtime.FleetRuntime.__new__(up_fleet_runtime.FleetRuntime) + rt.plan = SimpleNamespace(min_islands=min_islands, absent_after_s=absent_after_s, + islands=[SimpleNamespace(index=k, name=n) for k, n in enumerate(islands)]) + ks = tuple(range(len(islands))) + stops = SimpleNamespace(running=lambda: ks, fleet_stop_reason=None, stop_reason=lambda k: None) + rt.stops = lambda: stops + rt.active = lambda: list(ks) + rt.trainer_records = lambda now: records + return rt + + +def _waiting(since): + return {"state": "recovering", "spares": {"waiting_spare": True, "wait_reason": "no free spare", + "waiting_since": since}} + + +def test_a_single_island_fleet_waiting_under_an_hour_goes_on_and_stops_past_it(monkeypatch): + """A one-island fleet (min_islands 1) is not stopped the moment it waits: its island counts + for fleet.waiting_absent_after_s (1 h), then as absent; its own give-up stays 24 h.""" + import time + + records = {0: _waiting(10_000.0)} + rt = _runtime(["east"], 1, records) + monkeypatch.setattr(time, "time", lambda: 10_000.0 + 3000) + assert rt.waiting_spare() == {} and rt.all_stopped() is None + monkeypatch.setattr(time, "time", lambda: 10_000.0 + 3700) + (why,) = rt.waiting_spare().values() + assert "waiting 3700 s, past fleet.waiting_absent_after_s 3600 s" in why + assert rt.all_stopped() == "fleet.min_islands" + + +def test_in_a_fleet_an_island_waiting_past_the_limit_is_absent(monkeypatch): + import time + + records = {0: {"state": "running"}, 1: _waiting(10_000.0)} + monkeypatch.setattr(time, "time", lambda: 10_000.0 + 1800) + assert _runtime(["east", "west"], 2, records).all_stopped() is None # still counted + monkeypatch.setattr(time, "time", lambda: 10_000.0 + 3601) + assert _runtime(["east", "west"], 2, records).all_stopped() == "fleet.min_islands" + assert _runtime(["east", "west"], 1, records).all_stopped() is None # island 0 is enough + assert _runtime(["east", "west"], 2, records, absent_after_s=7200.0).all_stopped() is None # configured + records[1]["spares"]["waiting_spare"] = False + assert _runtime(["east", "west"], 2, records).all_stopped() is None + + +def test_an_island_waiting_3599_s_counts_and_3601_s_is_absent(monkeypatch): + import time + + records = {0: {"state": "running"}, 1: _waiting(10_000.0)} + rt = _runtime(["east", "west"], 2, records) + monkeypatch.setattr(time, "time", lambda: 10_000.0 + 3599) + assert rt.waiting_spare() == {} and rt.all_stopped() is None + monkeypatch.setattr(time, "time", lambda: 10_000.0 + 3601) + assert list(rt.waiting_spare()) == [1] and rt.all_stopped() == "fleet.min_islands" + + +def test_a_wait_without_its_start_counts_from_when_it_is_first_seen(): + rt = _runtime(["east"], 1, {0: _waiting(None)}, absent_after_s=60.0) + assert rt.waiting_spare(now=5000.0) == {} + assert rt.waiting_spare(now=5050.0) == {} + assert list(rt.waiting_spare(now=5061.0)) == [0] + + +def test_waiting_absent_after_s_is_a_fleet_key_kept_in_the_plan(): + from yeto.rl import fleet + + assert fleet.waiting_absent_after_s({"fleet": {}}) is None + assert fleet.waiting_absent_after_s({"fleet": {"waiting_absent_after_s": 900}}) == 900.0 + for bad in (0, -1, True, "600"): + with pytest.raises(ValueError, match="fleet.waiting_absent_after_s must be a number of seconds > 0"): + fleet.waiting_absent_after_s({"fleet": {"waiting_absent_after_s": bad}}) + plan = fleet.FleetPlan(run="r", store="/s", dispense="fleet", islands=(), waiting_absent_after_s=900.0) + doc = plan.to_json() + assert doc["roster"]["waiting_absent_after_s"] == 900.0 + assert fleet.FleetPlan.from_json(doc).absent_after_s == 900.0 + default = fleet.FleetPlan(run="r", store="/s", dispense="fleet", islands=()) + assert "waiting_absent_after_s" not in default.to_json()["roster"] # unset: the plan is as before + assert default.absent_after_s == 3600.0 + + +def test_the_compiled_plan_keeps_waiting_absent_after_s(fleet_run, files): # noqa: F811 + cfg = _cfg(files) + cfg["fleet"]["waiting_absent_after_s"] = 900 + assert fleet_run(cfg).fleet_plan().absent_after_s == 900.0 + assert fleet_run(_cfg(files)).fleet_plan().absent_after_s == 3600.0 + + +def test_the_island_record_carries_the_waits_start(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + spares.records.claim("b300-3", "isl-other") + ops.wall = lambda: 7777.0 + assert ops.relaunch(None, "isl") is None + view = ops.spares_view("isl") + assert view["waiting_spare"] is True and view["waiting_since"] == 7777.0 + + +# ------------------------------------------------------------------ M2: what a lost node owes +def test_a_lost_node_whose_own_stop_is_confirmed_owes_nothing(tmp_path): + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0) + s = islands_spec() + spares, store = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + ops._node_health_lost(ops.islands["isl"], 2, ["XID 79 on GPU 3"], READING) + join_stops(spares) + assert spares.records.own_quarantine("b300-2")["owed"] == [] # stopped: owes nothing (a settle marker) + assert json.loads(store.read("fleet/nodes/b300-2/quarantine.json"))["owed"] # the record itself is not rewritten + assert str(ops.job_status("isl", 0)) == "FAILED" + assert ops.relaunch(None, "isl") == 1 + assert open_rows(tmp_path) == ["run1/isl-i1"] # no owed row for b300-2 + + +def test_release_node_closes_the_owed_row_and_a_node_picked_again_is_billed_once(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + assert ops.relaunch(None, "isl") == 1 + assert open_rows(tmp_path) == ["run1/isl-i0-owed-b300-1", "run1/isl-i1"] + cluster.unreachable.discard("b300-1") + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, say=lambda m: None) == 0 + assert open_rows(tmp_path) == ["run1/isl-i1"] # released: no more billing for its owed stop + cluster.lose("b300-3") # the spare is lost; b300-1 (released) is picked again + rec = ops.islands["isl"] + assert wait_for(lambda: rec.job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", 1) + assert ops.relaunch(None, "isl") == 2 + assert started(cluster, 2) == ["b300-0", "b300-1", "b300-2"] + assert open_rows(tmp_path) == ["run1/isl-i1-owed-b300-3", "run1/isl-i2"] + rows = {r.id: r for r in ResourceLedger(tmp_path / "ledger.jsonl").open_resources()} + assert [n["name"] for n in rows["run1/isl-i2"].attrs["nodes"]].count("b300-1") == 1 + + +def _health_lost_then_picked_again(tmp_path): + """b300-2 is lost by its health and its stop confirmed (it owes nothing for i0); b300-3 + takes its place (i1); b300-2 is released by hand, then b300-3 loses power and b300-2 is + picked again (i2).""" + cluster = Cluster([*NAMES, "b300-3", "b300-4"]) + ops = make_ops(tmp_path, cluster, health_every_s=0, unreachable_polls=2) + s = islands_spec() + spares, store = make_spares(tmp_path, s, [spare(3), spare(4)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + rec = ops.islands["isl"] + ops._node_health_lost(rec, 2, ["XID 79 on GPU 3"], READING) + join_stops(spares) + assert ("b300-2", 0) in spares.stopped + assert str(ops.job_status("isl", 0)) == "FAILED" and ops.relaunch(None, "isl") == 1 + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3), spare(4)]) + assert isp.release_node_main(inventory=inv, name="b300-2", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, say=lambda m: None) == 0 + cluster.lose("b300-3") + assert wait_for(lambda: rec.job.procs[2].poll() is not None) + for _ in range(2): + ops.job_status("isl", 1) + assert ops.relaunch(None, "isl") == 2 and started(cluster, 2) == ["b300-0", "b300-1", "b300-2"] + assert not [k for k in spares.stopped if k[0] == "b300-2"] # picked again: its old confirmation is gone + return cluster, ops, spares, rec + + +def test_a_node_picked_again_and_then_power_lost_owes_its_stop_again(tmp_path): + cluster, ops, spares, rec = _health_lost_then_picked_again(tmp_path) + cluster.lose("b300-2") + assert wait_for(lambda: rec.job.procs[2].poll() is not None) + for _ in range(2): + ops.job_status("isl", 2) + assert ops.relaunch(None, "isl") == 3 + assert "run1/isl-i2-owed-b300-2" in open_rows(tmp_path) # cleanup and the reaper still stop it there + + +def test_a_node_picked_again_and_then_health_lost_with_a_failed_stop_owes_it(tmp_path): + cluster, ops, spares, rec = _health_lost_then_picked_again(tmp_path) + cluster.kill_rc["b300-2"] = 1 # its stop does not go through this time + ops._node_health_lost(rec, 2, ["XID 79 on GPU 3"], READING) + join_stops(spares) + assert ("b300-2", 2) not in spares.stopped + assert str(ops.job_status("isl", 0)) == "FAILED" and ops.relaunch(None, "isl") == 3 + assert "run1/isl-i2-owed-b300-2" in open_rows(tmp_path) + + +# ------------------------------------------------------------------ M3: the per-learner resume point +ARGS = dict(rl_sample_role="trainer", rl_single_island_no_sync=False, rl_island_sample_role=None, + rl_sampler_follow="trainer", rl_backend="miles", rl_max_policy_age=2, rl_checkpoint_store="/store", + rl_island_buffer_shards=["0:a", "1:b"], rl_island_release_every=None, rl_island_max_policy_age=None) + + +def test_the_resume_point_is_the_learners_own(tmp_path): + args = SimpleNamespace(**ARGS, rl_cut_every=5) + assert isp.resume_keys(args, 1, 2) == ("island-cuts/island1/LATEST", "trainer1/policy-releases/LATEST.json") + assert isp.resume_keys(SimpleNamespace(**ARGS), 0, 2) == ("LATEST", "trainer0/policy-releases/LATEST.json") + assert isp.resume_keys(None, None) == ("LATEST", "policy-releases/LATEST.json") + store = DirectoryObjectStore(tmp_path / "store") + store.write("policy-releases/LATEST.json", json.dumps({"version": 99, "path": "x"}).encode()) # not its own + store.write("trainer1/policy-releases/LATEST.json", json.dumps({"version": 12, "path": "r12"}).encode()) + keys = isp.resume_keys(args, 1, 2) + assert isp.latest_checkpoint_step(store, keys)["step"] == 12 # no cut yet: its own release + store.write("LATEST", json.dumps({"cut_id": "r000050-i0"}).encode()) # another island's place + store.write("island-cuts/island1/LATEST", json.dumps({"cut_id": "r000014-i1"}).encode()) + assert isp.latest_checkpoint_step(store, keys) == {"source": "round_cut", "step": 14, "ref": "r000014-i1", + "key": "island-cuts/island1/LATEST"} + + +def test_a_per_island_launch_reads_the_cut_of_its_learner_id_not_its_index(): + """fleet.launch per_island: each launch has one island (index 0) whose learner id is the + fleet's (``--rl-fleet-learner-id``): learner 2 reads island-cuts/island2.""" + args = SimpleNamespace(rl_fleet_role="island", rl_fleet_learner_id=2, rl_fleet_learners=3, + rl_checkpoint_store="/store", rl_cut_every=5) + assert isp.resume_keys(args, 0, 1)[0] == "island-cuts/island2/LATEST" + assert isp.spares_from_args(SimpleNamespace(**vars(args), rl_node_inventory_nodes=[*islands_spec().nodes, spare(3)], + cluster_prefix="run1"), + islands_spec(), island_index=0, num_islands=1) is not None + + +def test_start_resident_ssh_gives_each_island_its_index(tmp_path, monkeypatch): + from yeto.launch import ssh_resident, trainer_provision + + seen = [] + + class Ops: + def __init__(self, **kw): + pass + + def add(self, name, spec, *, spares=None): + pass + + def start(self, name): + return 0 + + monkeypatch.setattr(ssh_resident, "SshIslandOps", Ops) + monkeypatch.setattr(isp, "spares_from_args", lambda args, spec, **kw: seen.append(kw) or None) + args = SimpleNamespace(cluster_prefix="run1") + trainer_provision.start_resident_ssh(args, {"a": islands_spec(), "b": islands_spec()}, ["a", "b"], {}, {}, None, {}, + island_index={"a": 1, "b": 3}, num_islands=4) + assert seen == [{"island_index": 1, "num_islands": 4}, {"island_index": 3, "num_islands": 4}] + + +# ------------------------------------------------------------------ M4: a health check, not an answer +def test_without_a_health_checker_no_spare_is_picked_and_no_node_released(tmp_path, monkeypatch): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + monkeypatch.setattr(isp, "_checker_for", lambda family, **kw: None) + assert isp.node_check(spare(3), cluster, multi=True) == ( + False, "no health check for device family cuda here (yeto.hw.node_health)") + assert ops.relaunch(None, "isl") is None + assert "no health check for device family cuda" in ops.spares_view("isl")["wait_reason"] + cluster.unreachable.discard("b300-1") + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + lines = [] + common = dict(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, objects=store, + kill_grace_s=1, say=lines.append) + assert isp.release_node_main(**common) == 1 + assert "stays quarantined: no health check" in lines[-1] and "--force" in lines[-1] + assert store.read("fleet/nodes/b300-1/quarantine.json") is not None + assert isp.release_node_main(**common, force=True) == 0 + assert any(line.startswith("[yeto] WARN: --force: node b300-1 is released without its health check") + for line in lines) + assert store.read("fleet/nodes/b300-1/quarantine.json") is None + + +def test_spares_without_a_health_checker_are_named_in_the_dry_run_and_at_the_start(tmp_path, monkeypatch, capsys): + s = islands_spec() + args = SimpleNamespace(rl_node_inventory_nodes=[*s.nodes, spare(3)], cluster_prefix="run1", + rl_checkpoint_store=str(tmp_path / "store")) + assert "note" not in isp.spare_view(args, s) # a checker: nothing said + monkeypatch.setattr(isp, "_checker_for", lambda family, **kw: None) + view = isp.spare_view(args, s) + assert "the spare nodes do not apply; a failed island is relaunched on its own nodes" in view["note"] + assert "WARN: the inventory declares trainer-spare nodes" in capsys.readouterr().err # the dry run says it + lines = [] + assert isp.spares_from_args(args, s, log=lines.append) is None # as on main + assert [ln for ln in lines if "WARN" in ln and "device family cuda has no node health check" in ln] + assert isp.spare_view(SimpleNamespace(rl_node_inventory_nodes=list(s.nodes)), s) is None # no spares: silent + + +def test_a_check_that_did_not_run_is_no_pass(monkeypatch): + class Unchecked: + def script(self, hcas): + return "echo yeto-fake-health" + + def parse(self, text, hcas, prev): + return SimpleNamespace(checked=False, ok_single=None, ok_multi=None, reasons=[]) + + cluster = Cluster(["b300-3"]) + monkeypatch.setattr(isp, "_checker_for", lambda family, **kw: Unchecked()) + assert isp.node_check(spare(3), cluster, multi=True) == (False, "health not checked (rc 0)") + + +def test_a_failed_lease_release_keeps_the_quarantine_and_says_why(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + cluster.unreachable.discard("b300-1") + + class Broken(FakeLeases): + def force_release(self, node, *, holder=None): + raise OSError("lease store unreachable") + + lines = [] + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + rc = isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, say=lines.append, leases=Broken()) + assert rc == 1 and "its lease could not be released (OSError: lease store unreachable)" in lines[-1] + assert store.read("fleet/nodes/b300-1/quarantine.json") is not None # the record stays + + +# ------------------------------------------------------------------ M5: only this run's lease +def test_release_node_gives_up_only_its_own_lease(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + cluster.unreachable.discard("b300-1") + leases = FakeLeases(held={"b300-1": "other-run/trainer@b"}) + leases.kept = ["b300-1"] # kept by that run: only its holder's release may end it + lines = [] + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, say=lines.append, leases=leases) == 0 + assert leases.holders["b300-1"] == "other-run/trainer@b" # another run's lease is not touched + assert "its lease is held by other-run/trainer@b, not released" in lines[-1] + + +def test_release_node_probes_a_live_lease_before_it_forces_it_and_refuses_a_node_still_running(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + cluster.unreachable.discard("b300-1") + leases = FakeLeases(held={"b300-1": "run1/trainer@launcher-a"}) # live: renewed, not kept + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + lines = [] + common = dict(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, objects=store, + kill_grace_s=1, say=lines.append, leases=leases) + cluster.still_runs["b300-1"] = ["yeto-run1-isl-i0-n1"] + assert isp.release_node_main(**common) == 1 + assert "still runs and the node is not confirmed free (node b300-1 still runs run run1" in lines[-1] + assert leases.holders["b300-1"] == "run1/trainer@launcher-a" + assert store.read("fleet/nodes/b300-1/quarantine.json") is not None + cluster.still_runs.clear() + assert isp.release_node_main(**common) == 0 + assert leases.forced == [("b300-1", True)] and "b300-1" not in leases.holders + probes = [i for i, c in enumerate(cluster.calls) if c == ("lease-probe", "b300-1")] + assert probes and probes[-1] < len(cluster.calls) # the probe ran before the forced release + + +def test_the_quarantine_names_the_lease_holder_and_a_restart_keeps_it(tmp_path): + leases = FakeLeases(held={n: "run1/trainer@launcher-a" for n in NAMES}) + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)], leases=leases) + doc = json.loads(store.read("fleet/nodes/b300-1/quarantine.json")) + assert doc["lease_holder"] == "run1/trainer@launcher-a" + spares.records.claim("b300-3", "isl-other") + assert ops.relaunch(None, "isl") is None # waiting + ops.close() + again_leases = FakeLeases(held={n: "run1/trainer@launcher-a" for n in NAMES}) # the restart took them back + again = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=2) + spares2, _ = make_spares(tmp_path, islands_spec(), [spare(3)], leases=again_leases) + again.add("isl", islands_spec(), spares=spares2) + again.start("isl") + assert again_leases.kept == ["b300-1"] # the quarantined node's lease out of the renewals again + + +# ------------------------------------------------------------------ M6: the shared quarantine +def test_a_quarantine_is_shared_through_the_lease_store_and_other_runs_skip_the_node(tmp_path): + shared = DirectoryObjectStore(tmp_path / "leases") + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0, unreachable_polls=2) + s = islands_spec() + store = DirectoryObjectStore(tmp_path / "store") + spares = IslandSpares(pool=(*s.nodes, spare(3)), records=NodeRecords(store, run_id="run1", log=lambda m: None, + shared=shared)) + ops.add("isl", s, spares=spares) + ops.start("isl") + cluster.lose("b300-1") + assert wait_for(lambda: ops.islands["isl"].job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", 0) + doc = json.loads(shared.read("nodes/b300-1/quarantine.json")) + assert doc["run"] == "run1" and doc["island"] == "isl" + shared.write("nodes/b300-2/lease/00000001.json", b"{}") # node_lease's objects: not quarantines + shared.write("nodes/b300-2/events/quarantine.json", b"{}") + assert isp.shared_quarantined_names(shared) == {"b300-1"} # for another run's pick (excluded) + # another run on the same inventory: its own run store, the same lease store + other = IslandSpares(pool=(*spec(2).nodes,), records=NodeRecords(DirectoryObjectStore(tmp_path / "store2"), + run_id="run2", log=lambda m: None, shared=shared)) + pick = isp.pick_spare(other, "isl", [b300(0), b300(2)], [1], ops=cluster) + assert pick.node is None and pick.skipped["b300-1"].startswith( # who, why and how to release it + "quarantined: b300-1 by run run1 island isl (rank 1 (b300-1) does not answer") + assert pick.skipped["b300-1"].endswith("once fixed, run `yeto cluster release-node b300-1` with this inventory " + "and the run store of the run that quarantined it") + assert "release-node b300-1" in pick.why_none() + cluster.unreachable.discard("b300-1") + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=store, shared=shared, kill_grace_s=1, say=lambda m: None) == 0 + assert shared.read("nodes/b300-1/quarantine.json") is None and isp.shared_quarantined_names(shared) == set() + + +def test_a_launcher_restarted_while_waiting_starts_and_waits_on(tmp_path): + """Formerly a known limit: a launcher restarted while the island waited for a spare + refused to start (the lost node did not answer). Its quarantined node is lost again at + the start, the waiting goes on (its start is kept) and a free spare replaces it.""" + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)], max_wait_s=7200.0) + spares.records.claim("b300-3", "isl-other") + ops.wall = lambda: 1000.0 + assert ops.relaunch(None, "isl") is None and ops.waiting_spare("isl") + ops.close() + again = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=2) + again.wall = lambda: 1000.0 + 3600.0 + spares2, _ = make_spares(tmp_path, islands_spec(), [spare(3)], max_wait_s=7200.0) + again.add("isl", islands_spec(), spares=spares2) + job = again.start("isl") # no refusal + assert job == 0 and str(again.job_status("isl", job)) == "FAILED" and again.waiting_spare("isl") + assert spares2.wait_since == 1000.0 # the wait's start survived the restart + assert "b300-1" in str(again.islands["isl"].reason) + spares2.records.unclaim("b300-3", "isl-other") + clock.t += 3600 + assert again.relaunch(None, "isl") == 1 + assert started(cluster, 1) == ["b300-0", "b300-3", "b300-2"] + assert spares2.wait_since is None + + +def test_a_node_another_run_quarantined_is_replaced_at_the_first_start(tmp_path): + shared = DirectoryObjectStore(tmp_path / "leases") + NodeRecords(DirectoryObjectStore(tmp_path / "store2"), run_id="run2", log=lambda m: None, + shared=shared).quarantine("b300-2", island="x", reason="XID 79 in run2") + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0) + s = islands_spec() + spares = IslandSpares(pool=(*s.nodes, spare(3)), records=NodeRecords(DirectoryObjectStore(tmp_path / "store"), + run_id="run1", log=lambda m: None, + shared=shared)) + ops.add("isl", s, spares=spares) + assert ops.start("isl") == 0 + assert started(cluster, 0) == ["b300-0", "b300-1", "b300-3"] + + +def test_a_lost_nodes_lease_is_kept_until_release_node(tmp_path): + leases = FakeLeases(held={n: "run1/trainer@launcher-a" for n in NAMES}) + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)], leases=leases) + assert leases.kept == ["b300-1"] # held without renewal: no other run gets the broken node + assert leases.holders["b300-1"] == "run1/trainer@launcher-a" + assert ops.relaunch(None, "isl") == 1 + cluster.unreachable.discard("b300-1") + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, leases=leases, say=lambda m: None) == 0 + assert "b300-1" not in leases.holders + + +# ------------------------------------------------------------------ L1: a stale health reading +def _real_reading(): + from yeto.hw import node_health + + result = node_health.HealthResult(checked=True, ok_single=False, ok_multi=False, reasons=["XID 79 on GPU 3"], + facts={"gpu_reasons": ["XID 79 on GPU 3"]}) + return node_health.Reading(verdict="lost", result=result, event=node_health.EVENT_LOST) + + +def test_a_health_reading_taken_before_a_spare_took_the_rank_is_ignored(tmp_path): + """The real node_health.Reading names no node: the resident tick stamps the reading with + the rank's node and its replacement count, and the hook drops one taken before.""" + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + rec = ops.islands["isl"] + old = _real_reading() + ops._health_reading(rec, 1, old) # rank 1 (b300-1) judged lost by its health, the hook not run yet + rec.health_pending = [] # job_status took it (the hook runs after the lock, below) + assert ops.relaunch(None, "isl") == 1 and rec.spec.nodes[1].name == "b300-3" + ops._node_health_lost(rec, 1, ["XID 79 on GPU 3"], old) + assert spares.lost == {} and str(ops.job_status("isl", 1)) == "RUNNING" # b300-3 is not taken as lost + fresh = _real_reading() + ops._health_reading(rec, 1, fresh) # a reading of b300-3 itself + rec.health_pending = [] + ops._node_health_lost(rec, 1, ["XID 79 on GPU 3"], fresh) + assert list(spares.lost) == [1] and str(ops.job_status("isl", 1)) == "FAILED" + + +def test_a_health_reading_of_the_same_node_back_in_its_rank_after_a_replacement_is_stale(tmp_path): + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0) + s = islands_spec() + spares, _ = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + rec = ops.islands["isl"] + old = _real_reading() + ops._health_reading(rec, 2, old) + rec.health_pending = [] + rec.rank_gen[2] = rec.rank_gen.get(2, 0) + 1 # a spare took rank 2 and handed it back to b300-2 since + ops._node_health_lost(rec, 2, ["XID 79 on GPU 3"], old) + ops._node_health_lost(rec, 2, ["XID 79 on GPU 3"], old) # asked again: still stale + assert spares.lost == {} and str(ops.job_status("isl", 0)) == "RUNNING" + + +# ------------------------------------------------------------------ L2 / L3: no SSH under the ops lock +def test_the_lost_nodes_stop_and_the_spares_checks_run_outside_the_ops_lock(tmp_path, monkeypatch): + cluster = Cluster([*NAMES, "b300-3", "b300-4"]) + ops = make_ops(tmp_path, cluster, health_every_s=0) + s = islands_spec() + spares, _ = make_spares(tmp_path, s, [spare(3), spare(4)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + held = [] + real_check, real_run = isp.node_check, cluster.run + + def check(node, o, **kw): + held.append(("check", node.name, ops._lock._is_owned())) + return real_check(node, o, **kw) + + def run(node, script, **kw): + if "kill -TERM" in script and node.name == "b300-2": + held.append(("stop", node.name, ops._lock._is_owned())) + return real_run(node, script, **kw) + + monkeypatch.setattr(isp, "node_check", check) + cluster.run = run + ops._node_health_lost(ops.islands["isl"], 2, ["XID 79 on GPU 3"], READING) + join_stops(spares) + cluster.sick.add("b300-3") # the first candidate fails its check: the next one is checked too + assert ops.relaunch(None, "isl") == 1 + assert started(cluster, 1) == ["b300-0", "b300-1", "b300-4"] + assert held == [("stop", "b300-2", False), ("check", "b300-3", False), ("check", "b300-4", False)] + + +# ------------------------------------------------------------------ L5: an atomic create or nothing +class CheckThenWrite(DirectoryObjectStore): + atomic_create = False # e.g. the OSS relay + + def __init__(self, root): + super().__init__(root) + self.creates = [] + + def create(self, key, data): + self.creates.append(key) + return super().create(key, data) + + +def test_a_store_without_an_atomic_create_is_refused_for_claims(tmp_path): + store = CheckThenWrite(tmp_path / "store") + records = NodeRecords(store, run_id="run1", log=lambda m: None) + with pytest.raises(isp.SpareError, match="no atomic exclusive create"): + records.claim("b300-3", "isl") + assert store.creates == [] # refused before any create (no claim written, even for a moment) + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0) + s = islands_spec() + ops.add("isl", s, spares=IslandSpares(pool=(*s.nodes, spare(3)), records=records)) + from yeto.launch.ssh_trainer_island import SshIslandError + + with pytest.raises(SshIslandError, match="no atomic exclusive create"): + ops.start("isl") + assert cluster.count("start") == 0 + + +def test_a_store_that_finds_out_on_the_create_is_refused_and_leaves_no_claim(tmp_path): + class Finds(DirectoryObjectStore): + conditional_writes = True + + def create(self, key, data): + created = super().create(key, data) + self.conditional_writes = False # the endpoint refused If-None-Match: a fallback write + return created + + store = Finds(tmp_path / "store") + records = NodeRecords(store, run_id="run1", log=lambda m: None) + with pytest.raises(isp.SpareError): + records.claim("b300-3", "isl") + assert store.read("fleet/nodes/b300-3/claim.json") is None + + +# ------------------------------------------------------------------ M7: the release hint +def test_the_lost_node_log_names_release_node(tmp_path): + lines = [] + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0, unreachable_polls=2) + ops.log = lines.append + s = islands_spec() + spares, _ = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + ops._node_health_lost(ops.islands["isl"], 2, ["XID 79 on GPU 3"], READING) + critical = [ln for ln in lines if "CRITICAL" in ln and "is lost" in ln] + assert critical and "run `yeto cluster release-node b300-2`" in critical[0] + assert "until released by hand: run `yeto cluster release-node `" in isp.spare_view( + SimpleNamespace(rl_node_inventory_nodes=[*s.nodes, spare(3)]), s)["quarantine"] + + +def test_the_trainer_pick_leaves_out_a_node_quarantined_in_the_lease_store(tmp_path, monkeypatch, capsys): + """A node another run's island lost (quarantined in the lease store, its lease kept or + released) is no candidate of a new run's trainer pick until release-node.""" + from tests.test_rl_object_store import FakeS3 + from yeto.cloud.s3_store import S3ObjectStore + from yeto.launch import ssh_trainer_island as sti + from yeto.launch.node_lease import NodeLeases + + objects, clock = S3ObjectStore("s3://leases/x", client=FakeS3()), Clock() + objects.write("nodes/b300-0/quarantine.json", json.dumps( + {"node": "b300-0", "run": "run7", "island": "isl0", "reason": "rank 1 (b300-0): no answer"}).encode()) + objects.write("nodes/b300-1/lease/other.json", b"{}") # node_lease's own keys: not a quarantine + monkeypatch.setattr(sti, "_lease_record", lambda args: {}) + monkeypatch.setattr(sti, "_record_island_nodes", lambda args, name, nodes: None) + leases = NodeLeases("s3://leases/x", "run2/trainer", objects=objects, clock=clock, monotonic=clock) + trainers = [b300(i) for i in range(3)] + args = SimpleNamespace(cluster_prefix=f"oc-f-{tmp_path.name}") + picked = sti.lease_trainer_nodes(args, trainers, 2, leases, name="isl", wait_s=0) + assert [n.name for n in picked] == ["b300-1", "b300-2"] and leases.held() == ["b300-1", "b300-2"] + assert isp.shared_quarantined_names(objects) == {"b300-0"} + err = capsys.readouterr().err + note = "quarantined, left out: b300-0 by run run7 island isl0 (rank 1 (b300-0): no answer)" + assert f"island isl: {note}" in err and "run `yeto cluster release-node ` with this inventory" in err + with pytest.raises(sti.SshIslandError) as caught: # only the quarantined node is left: no candidate + sti.lease_trainer_nodes(args, trainers, 1, leases, name="isl2", wait_s=0) + assert note in str(caught.value) and "release-node" in str(caught.value) # not just "no free node" + assert "b300-0" not in leases.held() + + +def test_the_lease_wait_line_names_who_quarantined_the_node(tmp_path, monkeypatch, capsys): + from tests.test_rl_object_store import FakeS3 + from yeto.cloud.s3_store import S3ObjectStore + from yeto.launch import ssh_trainer_island as sti + from yeto.launch.node_lease import NodeLeases + + objects, clock = S3ObjectStore("s3://leases/x", client=FakeS3()), Clock() + objects.write("nodes/b300-0/quarantine.json", json.dumps({"run": "run7", "island": "isl0"}).encode()) + NodeLeases("s3://leases/x", "run9/trainer", objects=objects, clock=clock, monotonic=clock).acquire("b300-1") + monkeypatch.setattr(sti, "_lease_record", lambda args: {}) + monkeypatch.setattr(sti, "_record_island_nodes", lambda args, name, nodes: None) + from yeto.launch import node_lease + + real = node_lease.pick_nodes + + def pick_nodes(*a, **kw): # its waiting line (every 5 minutes) goes through the given log + kw["log"]("[node-lease] 2 node(s) needed, 1 free; held: b300-1 by run run9; waiting 300s so far") + return real(*a, **kw) + + monkeypatch.setattr(node_lease, "pick_nodes", pick_nodes) + leases = NodeLeases("s3://leases/x", "run2/trainer", objects=objects, clock=clock, monotonic=clock) + with pytest.raises(sti.SshIslandError, match="held: b300-1 by run run9.*b300-0 by run run7 island isl0"): + sti.lease_trainer_nodes(SimpleNamespace(cluster_prefix=f"oc-f-{tmp_path.name}"), [b300(0), b300(1)], 2, + leases, name="isl", wait_s=0) + assert ("waiting 300s so far; quarantined, left out: b300-0 by run run7 island isl0. Once a node is fixed, run " + "`yeto cluster release-node ` with this inventory and the run store of the run that quarantined it") in capsys.readouterr().err + + +def test_a_start_on_nodes_another_run_holds_is_refused(tmp_path): + import dataclasses + + from yeto.launch.ssh_trainer_island import SshIslandError + + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, clock=Clock(), health_every_s=0, unreachable_polls=2) + leases = FakeLeases(held={"b300-2": "run9/trainer@other"}) + s = dataclasses.replace(islands_spec(), leases=leases) + spares, _ = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + with pytest.raises(SshIslandError, match="b300-2 by run run9/trainer@other"): + ops.start("isl") + assert not [c for c in cluster.calls if c[0] == "start"] + assert leases.holders["b300-2"] == "run9/trainer@other" + + +def test_a_replacement_rebuilds_the_health_watches_on_the_new_nodes(tmp_path, monkeypatch): + built = [] + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + real = ops._health_watches + + def watches(spec_): + built.append([n.name for n in spec_.nodes]) + return real(spec_) + + monkeypatch.setattr(ops, "_health_watches", watches) + assert ops.relaunch(None, "isl") == 1 + assert built == [["b300-0", "b300-3", "b300-2"]] + + +def test_release_node_ends_the_lease_of_the_holder_the_quarantine_names(tmp_path): + """The command runs under its own lease holder; the lease it ends is the one of the run + that quarantined the node (the record's ``lease_holder``).""" + run_leases = FakeLeases(held={n: "run1/trainer@launcher-a" for n in NAMES}) + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)], leases=run_leases) + assert run_leases.kept == ["b300-1"] + cluster.unreachable.discard("b300-1") + cli = FakeLeases(run_id="yeto-cluster-release-node") + cli.holders, cli.kept = run_leases.holders, run_leases.kept # one lease store + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + lines = [] + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, say=lines.append, leases=cli) == 0 + assert "b300-1" not in run_leases.holders and "not released" not in lines[-1] + + +def test_the_islands_own_node_leases_hold_the_spares_and_the_shared_quarantine(tmp_path): + """On the production path the spares get no leases of their own: the island's + ``spec.leases`` (``trainer_leases``) is used, and its store holds the shared quarantine.""" + import dataclasses + + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, clock=Clock(), health_every_s=0, unreachable_polls=2) + leases = FakeLeases() + leases.objects = DirectoryObjectStore(tmp_path / "lease-store") + s = dataclasses.replace(islands_spec(), leases=leases) + spares, _ = make_spares(tmp_path, s, [spare(3)]) + assert spares.leases is None and spares.records.shared is None + ops.add("isl", s, spares=spares) + assert spares.leases is leases and spares.records.shared is leases.objects + ops.start("isl") + cluster.lose("b300-1") + assert wait_for(lambda: ops.islands["isl"].job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", 0) + assert leases.objects.read("nodes/b300-1/quarantine.json") is not None + assert leases.kept == ["b300-1"] + + +# ------------------------------------------------------------------ REV-885c 2: the leases of a restarted launcher +LEASE_STORE = "s3://leases/site" + + +def _lease_run(tmp_path, *, extra=(spare(3),)): + """Island isl of run1 picks b300-0..2 by real node leases (lease record in the run dir, + real NodeLeases on a fake S3 store); b300-1 loses power and b300-3 takes its place.""" + import dataclasses + + from tests.test_rl_object_store import FakeS3 + from yeto.cloud.s3_store import S3ObjectStore + from yeto.launch import ssh_trainer_island as sti + from yeto.launch.node_lease import NodeLeases + + objects, clock = S3ObjectStore(LEASE_STORE, client=FakeS3()), Clock() + args = SimpleNamespace(cluster_prefix="run1", rl_node_inventory_nodes=[*islands_spec().nodes, *extra]) + + def leases_of(identity="aaaa"): + return NodeLeases(LEASE_STORE, "run1/trainer", identity=identity, objects=objects, clock=clock, monotonic=clock) + + def island(leases): + nodes = sti.lease_trainer_nodes(args, islands_spec().nodes, 3, leases, name="isl", wait_s=0) + return dataclasses.replace(islands_spec(), nodes=tuple(nodes), leases=leases) + + cluster = Cluster([*NAMES, *[n.name for n in extra]]) + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=2) + first = leases_of() + spares, store = make_spares(tmp_path, islands_spec(), list(extra)) + ops.add("isl", island(first), spares=spares) + ops.start("isl") + cluster.lose("b300-1") + rec = ops.islands["isl"] + assert wait_for(lambda: rec.job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", 0) + assert ops.relaunch(None, "isl") == 1 and started(cluster, 1) == ["b300-0", "b300-3", "b300-2"] + assert sti._lease_record(args)["islands"]["isl"] == ["b300-0", "b300-3", "b300-2"] # (a): the spare recorded + cluster.unreachable.discard("b300-1") # repaired, then released by hand + inv = _inventory(tmp_path, [*islands_spec().nodes, *extra]) + cli = NodeLeases(LEASE_STORE, isp.RELEASE_NODE_RUN, objects=objects, clock=clock, monotonic=clock) + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, say=lambda m: None, leases=cli) == 0 + rec.lock.close() + for proc in rec.job.procs: # the launcher goes (no --keep); the island runs on + proc.terminate() + + def restart(identity="aaaa"): + leases = leases_of(identity) + again = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=2) + fresh, _ = make_spares(tmp_path, islands_spec(), list(extra)) + again.add("isl", island(leases), spares=fresh) + assert again.start("isl") == 1 # reattached + return again, leases + + return SimpleNamespace(objects=objects, clock=clock, args=args, leases_of=leases_of, restart=restart, + cluster=cluster) + + +def test_a_restarted_launcher_renews_the_lease_of_its_spare(tmp_path): + from yeto.launch.node_lease import NodeLeases + + run = _lease_run(tmp_path) + again, leases = run.restart() + assert sorted(leases.held()) == ["b300-0", "b300-2", "b300-3"] + run.clock.t += 3600 # an hour on: the spare's lease is this run's, renewed, not taken over + leases.renew_due() + other = NodeLeases(LEASE_STORE, "run9/trainer", objects=run.objects, clock=run.clock, monotonic=run.clock) + got = other.acquire("b300-3") + assert not got.ok and got.holder == leases.holder_id + + +def test_a_restarted_launcher_does_not_hold_a_released_old_node(tmp_path): + from yeto.launch import ssh_trainer_island as sti + + run = _lease_run(tmp_path) + # a stale record (the launcher went before it wrote the spare in): the old node is leased again + sti._record_island_nodes(run.args, "isl", islands_spec().nodes) + again, leases = run.restart() + assert "b300-1" not in leases.held() and sorted(leases.held()) == ["b300-0", "b300-2", "b300-3"] + assert sti._lease_record(run.args)["islands"]["isl"] == ["b300-0", "b300-3", "b300-2"] # (b): set right again + + +def test_the_island_reattaches_when_another_run_took_its_old_node(tmp_path): + from yeto.launch.node_lease import NodeLeases + + run = _lease_run(tmp_path) + other = NodeLeases(LEASE_STORE, "run9/trainer", objects=run.objects, clock=run.clock, monotonic=run.clock) + assert other.acquire("b300-1").ok + again, leases = run.restart() + assert sorted(leases.held()) == ["b300-0", "b300-2", "b300-3"] and other.held() == ["b300-1"] + assert run.cluster.count("follow", 1) == 3 and ("follow", "b300-3", 1) in run.cluster.calls # reattached + + +# ------------------------------------------------------------------ REV-885c 3: release-node away from the run dir +def test_release_node_away_from_the_runs_ledger_says_where_the_row_is_and_the_launcher_closes_it( + tmp_path, monkeypatch): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + assert ops.relaunch(None, "isl") == 1 + assert open_rows(tmp_path) == ["run1/isl-i0-owed-b300-1", "run1/isl-i1"] + cluster.unreachable.discard("b300-1") + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + lines = [] + elsewhere = tmp_path / "elsewhere" / "resources.jsonl" # another machine: no row of this run + with monkeypatch.context() as m: + m.setenv("YETO_RESOURCE_LEDGER", str(elsewhere)) + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, say=lines.append) == 0 + assert (f"WARN: its owed ledger row run1/isl-i0-owed-b300-1 is not open in {elsewhere}: the row is in the " + "run dir of the machine that ran the launcher of run run1 (runs/run1/resources.jsonl)") in lines[-1] + assert open_rows(tmp_path) == ["run1/isl-i0-owed-b300-1", "run1/isl-i1"] # still open in the run's ledger + cluster.lose("b300-3") # the spare is lost; b300-1 (released elsewhere) is picked again + rec = ops.islands["isl"] + assert wait_for(lambda: rec.job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", 1) + assert ops.relaunch(None, "isl") == 2 and started(cluster, 2) == ["b300-0", "b300-1", "b300-2"] + assert open_rows(tmp_path) == ["run1/isl-i1-owed-b300-3", "run1/isl-i2"] # billed once + rows = [json.loads(ln) for ln in (tmp_path / "ledger.jsonl").read_text().splitlines()] + closed = [r for r in rows if r.get("id") == "run1/isl-i0-owed-b300-1" and r.get("op") == "release"] + assert closed and closed[-1]["attrs"]["reason"] == "released elsewhere" + + + +# ------------------------------------------------------------------ REV-885c 4: an unreadable shared quarantine +class _FlakyStore: + """A lease store whose reads (and, with ``list_fails``, listings) fail.""" + + def __init__(self, inner, *, read_fails=(), list_fails=False): + self.inner, self.read_fails, self.list_fails = inner, set(read_fails), list_fails + + def read(self, key): + if any(key == f"nodes/{n}/quarantine.json" for n in self.read_fails): + raise OSError("connection reset") + return self.inner.read(key) + + def list(self, prefix): + if self.list_fails and prefix == "nodes/": # the quarantine listing (node_lease lists deeper) + raise OSError("list timed out") + return self.inner.list(prefix) + + def __getattr__(self, name): + return getattr(self.inner, name) + + +def test_an_unreadable_shared_quarantine_keeps_the_spare_out(tmp_path): + shared = DirectoryObjectStore(tmp_path / "leases") + shared.write("nodes/b300-3/quarantine.json", b"{not json") # a broken record + flaky = _FlakyStore(shared, read_fails={"b300-4"}) + other = IslandSpares(pool=(b300(0), b300(2), spare(3), spare(4)), # rank 1 is lost (not in the pool) + records=NodeRecords(DirectoryObjectStore(tmp_path / "store2"), run_id="run2", + log=lambda m: None, shared=flaky)) + cluster = Cluster([*NAMES, "b300-3", "b300-4"]) + pick = isp.pick_spare(other, "isl", spec(3).nodes, [1], ops=cluster) + assert pick.node is None + assert "quarantine record unreadable: not a JSON object" in pick.skipped["b300-3"] + assert "quarantine record unreadable: OSError: connection reset" in pick.skipped["b300-4"] + flaky.read_fails.clear() # the next round reads it again + assert isp.pick_spare(other, "isl", spec(3).nodes, [1], ops=cluster).node.name == "b300-4" + + +def test_an_unreadable_shared_quarantine_keeps_the_trainer_node_out(tmp_path, monkeypatch, capsys): + from tests.test_rl_object_store import FakeS3 + from yeto.cloud.s3_store import S3ObjectStore + from yeto.launch import ssh_trainer_island as sti + from yeto.launch.node_lease import NodeLeases + + inner, clock = S3ObjectStore(LEASE_STORE, client=FakeS3()), Clock() + inner.write("nodes/b300-0/quarantine.json", json.dumps({"run": "run7", "island": "isl0"}).encode()) + flaky = _FlakyStore(inner, read_fails={"b300-1"}, list_fails=True) + monkeypatch.setattr(sti, "_lease_record", lambda args: {}) + monkeypatch.setattr(sti, "_record_island_nodes", lambda args, name, nodes: None) + leases = NodeLeases(LEASE_STORE, "run2/trainer", objects=flaky, clock=clock, monotonic=clock) + picked = sti.lease_trainer_nodes(SimpleNamespace(cluster_prefix="run2"), [b300(i) for i in range(4)], 2, + leases, name="isl", wait_s=0) + assert [n.name for n in picked] == ["b300-2", "b300-3"] # b300-0 quarantined, b300-1 unreadable: out + err = capsys.readouterr().err + assert "the lease store's quarantine list failed (OSError: list timed out); each node's record is read" in err + assert "b300-1 (quarantine record unreadable: OSError: connection reset)" in err + assert "b300-0 by run run7 island isl0" in err + + +def test_a_store_error_on_the_quarantine_of_a_running_node_is_no_loss(tmp_path): + shared = DirectoryObjectStore(tmp_path / "leases") + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0, unreachable_polls=2) + lines = [] + ops.log = lines.append + s = islands_spec() + spares = IslandSpares(pool=(*s.nodes, spare(3)), records=NodeRecords( + DirectoryObjectStore(tmp_path / "store"), run_id="run1", log=lambda m: None, + shared=_FlakyStore(shared, read_fails={"b300-1"}))) + ops.add("isl", s, spares=spares) + assert ops.start("isl") == 0 and started(cluster, 0) == NAMES # not replaced on a store hiccup + assert any("quarantine record of b300-1 could not be read" in ln for ln in lines) + + + +# ------------------------------------------------------------------ REV-885c 5: down() skips a lost node +def test_down_does_not_wait_for_a_lost_node(tmp_path): + cluster = Cluster(NAMES) + ops = make_ops(tmp_path, cluster, clock=Clock(), health_every_s=0, unreachable_polls=2) + s = islands_spec() + spares, _ = make_spares(tmp_path, s, []) + ops.add("isl", s, spares=spares) + ops.start("isl") + cluster.kill_rc["b300-0"] = 1 # the release at the loss is not confirmed on b300-0 + cluster.lose("b300-1") + assert wait_for(lambda: ops.islands["isl"].job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", 0) + assert 1 in spares.lost and 0 not in ops.islands["isl"].released + cluster.kill_rc.clear() + before = len(cluster.calls) + assert ops.down("isl") is True # confirmed on the nodes that answer; the lost one is not asked + assert not [c for c in cluster.calls[before:] if c[1] == "b300-1"] + assert open_rows(tmp_path) == ["run1/isl-i0-owed-b300-1"] # its stop stays owed (cleanup, release-node) + + +# ------------------------------------------------------------------ REV-885c 6: the spare's ports +def test_a_spares_health_check_reads_the_islands_job_ports(tmp_path, monkeypatch): + import dataclasses + + from test_ssh_island_spares import FakeChecker + from yeto.hw import node_health + + seen = [] + + class Recording(FakeChecker): + def script(self, hcas): + seen.append(list(hcas)) + return super().script(hcas) + + monkeypatch.setattr(isp, "_checker_for", lambda family, **kw: Recording()) + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0, unreachable_polls=2) + s = dataclasses.replace(islands_spec(), env={"NCCL_IB_HCA": "=mlx5_4,mlx5_5"}) # the island's job env wins + extra = dataclasses.replace(spare(3), env={"NCCL_IB_HCA": "mlx5_0"}) + spares, _ = make_spares(tmp_path, s, [extra]) + ops.add("isl", s, spares=spares) + ops.start("isl") + cluster.lose("b300-1") + assert wait_for(lambda: ops.islands["isl"].job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", 0) + assert ops.relaunch(None, "isl") == 1 + assert seen and all(h == node_health.hcas_of("=mlx5_4,mlx5_5") for h in seen) + assert isp.hcas_of(extra) == node_health.hcas_of("mlx5_0") # its own env alone (release-node) + + +def test_release_node_dry_run_names_the_lease_it_ends_and_the_records_it_removes(tmp_path): + shared = DirectoryObjectStore(tmp_path / "leases") + run_leases = FakeLeases(held={n: "run1/trainer@launcher-a" for n in NAMES}) + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)], leases=run_leases) + spares.records.shared = shared + spares.records.quarantine("b300-1", island="isl", reason="lost", lease_holder=run_leases.holder_id) + cli = FakeLeases(run_id=isp.RELEASE_NODE_RUN) + cli.holders, cli.kept, cli.store_uri = run_leases.holders, run_leases.kept, "s3://leases/site" + cli.objects = shared + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + lines = [] + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, say=lines.append, leases=cli, dry_run=True) == 0 + text = "\n".join(lines) + assert (f"would remove fleet/nodes/b300-1/quarantine.json in the run store {tmp_path / 'store'} and " + "nodes/b300-1/quarantine.json in the lease store s3://leases/site") in text + assert "would end the lease of run1/trainer@launcher-a on b300-1 (a kept one at once" in text + assert run_leases.holders["b300-1"] == "run1/trainer@launcher-a" # a dry run ends nothing + + +def test_release_node_of_a_broken_record_needs_force(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + cluster.unreachable.discard("b300-1") + store.write("fleet/nodes/b300-1/quarantine.json", b"{truncated") + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + lines = [] + common = dict(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, objects=store, + kill_grace_s=1, say=lines.append) + assert isp.release_node_main(**common) == 1 + assert "its quarantine record is unreadable (quarantine record unreadable: not a JSON object): the stops it " \ + "still owes cannot be known" in "\n".join(lines) + assert "release it with --force" in lines[-1] and store.read("fleet/nodes/b300-1/quarantine.json") is not None + assert isp.release_node_main(**common, force=True) == 0 + assert any("released without running any owed stop" in ln for ln in lines) + assert store.read("fleet/nodes/b300-1/quarantine.json") is None + + +def test_a_lost_node_back_from_a_partition_gets_its_owed_stop_at_the_next_check(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[]) # no spare: the island waits + assert ops.relaunch(None, "isl") is None and ops.waiting_spare("isl") + assert open_rows(tmp_path) == ["run1/isl-i0-owed-b300-1"] + cluster.unreachable.discard("b300-1") # the partition heals: the old container still runs there + clock.t += 61 + assert ops.relaunch(None, "isl") is None # the backoff check: still no spare, the owed stop retried + join_stops(spares) + assert ("kill", "b300-1", 0) in cluster.calls + assert open_rows(tmp_path) == [] # stopped: no more billing + assert spares.records.own_quarantine("b300-1")["owed"] == [] # it stays quarantined until release-node + + + +def test_a_confirmed_stop_owes_no_row_even_when_its_record_is_not_updated(tmp_path, monkeypatch): + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0) + s = islands_spec() + spares, store = make_spares(tmp_path, s, [spare(3)]) + + def settle(*a, **kw): + raise OSError("store unavailable") + + monkeypatch.setattr(spares.records, "settle", settle) + ops.add("isl", s, spares=spares) + ops.start("isl") + ops._node_health_lost(ops.islands["isl"], 2, ["XID 79 on GPU 3"], READING) + join_stops(spares) + assert json.loads(store.read("fleet/nodes/b300-2/quarantine.json"))["owed"] # the record still lists it + assert str(ops.job_status("isl", 0)) == "FAILED" and ops.relaunch(None, "isl") == 1 + assert open_rows(tmp_path) == ["run1/isl-i1"] # the stop went through: no owed row + + +def test_a_health_reading_of_a_node_back_in_its_rank_after_two_replacements_is_stale(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + rec = ops.islands["isl"] + old = _real_reading() + ops._health_reading(rec, 1, old) # of b300-1 at rank 1, before it was replaced + rec.health_pending = [] + assert ops.relaunch(None, "isl") == 1 # b300-3 at rank 1 + cluster.unreachable.discard("b300-1") + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, say=lambda m: None) == 0 + cluster.lose("b300-3") + assert wait_for(lambda: rec.job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", 1) + assert ops.relaunch(None, "isl") == 2 and rec.spec.nodes[1].name == "b300-1" # back in rank 1 + ops._node_health_lost(rec, 1, ["XID 79 on GPU 3"], old) + assert spares.lost == {} and str(ops.job_status("isl", 2)) == "RUNNING" + + +# ------------------------------------------------------------------ REV-885d M1: a settle racing release-node +def test_a_settle_racing_release_node_never_writes_the_quarantine_back(tmp_path): + """REV-885d's order: the settle has read the record; release-node removes it and run9 + leases the node; then the settle goes on. Nothing of run1's quarantine comes back, in + the run store or in the lease store, so run9 never sees its node as quarantined.""" + from tests.test_rl_object_store import FakeS3 + from yeto.cloud.s3_store import S3ObjectStore + from yeto.launch.node_lease import NodeLeases + + store, shared = DirectoryObjectStore(tmp_path / "store"), DirectoryObjectStore(tmp_path / "leases") + clock = Clock() + lease_objects = S3ObjectStore("s3://leases/site", client=FakeS3()) + records = NodeRecords(store, run_id="run1", log=lambda m: None, shared=shared) + records.quarantine("b300-1", island="isl", reason="lost", + owed=[{"run_id": "run1", "island": "isl", "incarnation": 0, "rank": 1, "container": None}]) + cli = NodeRecords(store, run_id="", log=lambda m: None, shared=shared) + run9 = NodeLeases("s3://leases/site", "run9/trainer", objects=lease_objects, clock=clock, monotonic=clock) + real_read, armed = records._read, [True] + + def racing(key): + doc = real_read(key) + if key == "fleet/nodes/b300-1/quarantine.json" and armed and armed.pop(): + cli.release("b300-1") # release-node, between the settle's read and its write + assert run9.acquire("b300-1").ok + return doc + + records._read = racing + records.settle("b300-1", run_id="run1", island="isl", incarnation=0) + assert store.read("fleet/nodes/b300-1/quarantine.json") is None + assert not store.list("fleet/nodes/b300-1/settled/") # the tombstone is newer: no marker either + assert shared.read("nodes/b300-1/quarantine.json") is None + run9_records = NodeRecords(DirectoryObjectStore(tmp_path / "store9"), run_id="run9", log=lambda m: None, + shared=shared) + assert run9_records.quarantined("b300-1") is None # run9's own node is not "quarantined by run1" + assert run9.held() == ["b300-1"] + + +def test_an_owed_stop_retry_that_races_release_node_leaves_the_node_released(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[]) # no spare: the island waits + shared = DirectoryObjectStore(tmp_path / "leases") + spares.records.shared = shared + assert ops.relaunch(None, "isl") is None and ops.waiting_spare("isl") + cluster.unreachable.discard("b300-1") + cli = NodeRecords(store, run_id="", log=lambda m: None, shared=shared) + real = cluster.run + + def run(node, script, *, timeout=300.0): + if node.name == "b300-1" and "kill -TERM" in script: # release-node runs while the retry kills + cli.release("b300-1") + return real(node, script, timeout=timeout) + + cluster.run = run + clock.t += 61 + ops.relaunch(None, "isl") # the retry runs in the background: b300-1 may be picked again at once + join_stops(spares) + assert store.read("fleet/nodes/b300-1/quarantine.json") is None + assert shared.read("nodes/b300-1/quarantine.json") is None + assert not store.list("fleet/nodes/b300-1/settled/") + + +def test_a_settle_after_the_release_tombstone_writes_nothing(tmp_path): + store = DirectoryObjectStore(tmp_path / "store") + clock = Clock() + records = NodeRecords(store, run_id="run1", log=lambda m: None) + records.wall = clock + records.quarantine("b300-1", island="isl", reason="lost", + owed=[{"run_id": "run1", "island": "isl", "incarnation": 0}]) + clock.t += 5 # a release-node whose delete did not reach the store: its tombstone is newer + store.write("fleet/nodes/b300-1/released.json", json.dumps({"at": clock.t}).encode()) + records.settle("b300-1", run_id="run1", island="isl", incarnation=0) + assert not store.list("fleet/nodes/b300-1/settled/") + records.settle("b300-2", run_id="run1", island="isl", incarnation=0) # no record: nothing either + assert not store.list("fleet/nodes/b300-2/") + + +# ------------------------------------------------------------------ REV-885d M2: a launcher gone mid-replacement +def _died_mid_replacement(tmp_path, monkeypatch): + """b300-1 loses power; the launcher goes while it starts the spare (its preflight), after + the spares journal named the new nodes; b300-1 is then repaired and released by hand.""" + import dataclasses + + from tests.test_rl_object_store import FakeS3 + from yeto.cloud.s3_store import S3ObjectStore + from yeto.launch import ssh_trainer_island as sti + from yeto.launch.node_lease import NodeLeases + + objects, clock = S3ObjectStore(LEASE_STORE, client=FakeS3()), Clock() + args = SimpleNamespace(cluster_prefix="run1", rl_node_inventory_nodes=[*islands_spec().nodes, spare(3)]) + + def leases_of(run="run1/trainer", identity="aaaa"): + return NodeLeases(LEASE_STORE, run, identity=identity, objects=objects, clock=clock, monotonic=clock) + + def island(leases): + nodes = sti.lease_trainer_nodes(args, islands_spec().nodes, 3, leases, name="isl", wait_s=0) + return dataclasses.replace(islands_spec(), nodes=tuple(nodes), leases=leases) + + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=2) + spares, store = make_spares(tmp_path, islands_spec(), [spare(3)]) + ops.add("isl", island(leases_of()), spares=spares) + ops.start("isl") + rec = ops.islands["isl"] + cluster.lose("b300-1") + assert wait_for(lambda: rec.job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", 0) + real_launch = sti.SshTrainerIslands.launch + + def died(self, incarnation, *a, **kw): + raise SystemExit("the launcher went during the spare's preflight") + + monkeypatch.setattr(sti.SshTrainerIslands, "launch", died) + with pytest.raises(SystemExit): + ops.relaunch(None, "isl") + monkeypatch.setattr(sti.SshTrainerIslands, "launch", real_launch) + rec.lock.close() + for proc in rec.job.procs: + proc.terminate() + cluster.unreachable.discard("b300-1") + inv = _inventory(tmp_path, [*islands_spec().nodes, spare(3)]) + cli = NodeLeases(LEASE_STORE, isp.RELEASE_NODE_RUN, objects=objects, clock=clock, monotonic=clock) + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, say=lambda m: None, leases=cli) == 0 + + def restart(): + leases = leases_of() + again = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=2) + fresh, _ = make_spares(tmp_path, islands_spec(), [spare(3)]) + again.add("isl", island(leases), spares=fresh) + again.start("isl") + return again, leases + + return SimpleNamespace(args=args, leases_of=leases_of, restart=restart, cluster=cluster) + + +def test_a_restart_after_a_launcher_gone_mid_replacement_does_not_hold_the_released_old_node(tmp_path, monkeypatch): + from yeto.launch import ssh_trainer_island as sti + + run = _died_mid_replacement(tmp_path, monkeypatch) + assert sti._lease_record(run.args)["islands"]["isl"] == ["b300-0", "b300-3", "b300-2"] # written before the start + again, leases = run.restart() + assert "b300-1" not in leases.held() and sorted(leases.held()) == ["b300-0", "b300-2", "b300-3"] + assert run.leases_of("run9/trainer").acquire("b300-1").ok # free for another run + + +def test_a_restart_after_a_launcher_gone_mid_replacement_is_not_refused_by_another_runs_old_node( + tmp_path, monkeypatch): + from yeto.launch import ssh_trainer_island as sti + + run = _died_mid_replacement(tmp_path, monkeypatch) + sti._record_island_nodes(run.args, "isl", islands_spec().nodes) # an older record, as before this fix + assert run.leases_of("run9/trainer").acquire("b300-1").ok + again, leases = run.restart() # the spares journal names the island's nodes: not "not moving the island" + assert sorted(leases.held()) == ["b300-0", "b300-2", "b300-3"] + assert [n.name for n in again.islands["isl"].spec.nodes] == ["b300-0", "b300-3", "b300-2"] + + +# ------------------------------------------------------------------ REV-885d L4: a row closes after its stop +def _picked_again_after(tmp_path, release): + """b300-1 lost (owed row open), b300-3 replaces it; ``release(...)`` frees b300-1 without + its owed stop; then b300-3 is lost and b300-1 picked again.""" + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + assert ops.relaunch(None, "isl") == 1 + cluster.unreachable.discard("b300-1") + release(cluster, spares, store) + assert open_rows(tmp_path) == ["run1/isl-i0-owed-b300-1", "run1/isl-i1"] + kills_before = cluster.count("kill", 0) + rec = ops.islands["isl"] + cluster.lose("b300-3") + assert wait_for(lambda: rec.job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", 1) + return cluster, ops, kills_before + + +def _force_a_broken_record(tmp_path): + def release(cluster, spares, store): + store.write("fleet/nodes/b300-1/quarantine.json", b"{broken") + inv = _inventory(tmp_path, [*spec(3).nodes, spare(3)]) + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, say=lambda m: None, force=True) == 0 + return release + + +def test_after_force_over_a_broken_record_the_launcher_stops_the_old_incarnation_before_it_closes_the_row(tmp_path): + cluster, ops, kills_before = _picked_again_after(tmp_path, _force_a_broken_record(tmp_path)) + assert ops.relaunch(None, "isl") == 2 and started(cluster, 2) == ["b300-0", "b300-1", "b300-2"] + assert cluster.count("kill", 0) > kills_before # i0's owed stop ran on b300-1 first + assert open_rows(tmp_path) == ["run1/isl-i1-owed-b300-3", "run1/isl-i2"] + + +def test_a_row_whose_stop_fails_stays_open(tmp_path): + def release(cluster, spares, store): + _force_a_broken_record(tmp_path)(cluster, spares, store) + cluster.kill_rc["b300-1"] = 1 # its old container cannot be removed + + cluster, ops, kills_before = _picked_again_after(tmp_path, release) + ops.relaunch(None, "isl") + assert "run1/isl-i0-owed-b300-1" in open_rows(tmp_path) # still billed: cleanup tries it again + + +def test_records_kept_in_memory_a_restart_stops_the_old_incarnation_before_it_closes_the_row(tmp_path): + def release(cluster, spares, store): + spares.records = NodeRecords(None, run_id="run1", log=lambda m: None) # a restart without a run store + + cluster, ops, kills_before = _picked_again_after(tmp_path, release) + assert ops.relaunch(None, "isl") == 2 + assert cluster.count("kill", 0) > kills_before + assert "run1/isl-i0-owed-b300-1" not in open_rows(tmp_path) + + +# ------------------------------------------------------------------ REV-885d: the guards of the surviving mutants +def test_a_stale_lease_is_given_back_but_not_one_another_island_picked_or_claims(tmp_path): + """M4/M5/M17: two islands of the run in one launcher share its NodeLeases. Island isa's + stale pick names b300-3 (gone), b300-4 (island isb's pick) and b300-5 (claimed by isb): + only b300-3 is given back, and only it leaves ``assigned``.""" + import dataclasses + + from tests.test_rl_object_store import FakeS3 + from yeto.cloud.s3_store import S3ObjectStore + from yeto.launch.node_lease import NodeLeases + + objects, clock = S3ObjectStore(LEASE_STORE, client=FakeS3()), Clock() + leases = NodeLeases(LEASE_STORE, "run1/trainer", identity="aaaa", objects=objects, clock=clock, monotonic=clock) + for n in ("b300-3", "b300-4", "b300-5"): + assert leases.acquire(n).ok + cluster = Cluster([*NAMES, "b300-3", "b300-4", "b300-5"]) + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0) + s = dataclasses.replace(islands_spec(), leases=leases) + spares, _ = make_spares(tmp_path, s, [spare(3), spare(4), spare(5)]) + ops.add("isa", s, spares=spares) + leases.picks.update({"isa": [*NAMES, "b300-3", "b300-4", "b300-5"], "isb": ["b300-4"]}) + leases.assigned |= {*NAMES, "b300-3", "b300-4", "b300-5"} + spares.records.claim("b300-5", "isb") + ops._release_stale_leases(ops.islands["isa"]) + assert sorted(leases.held()) == ["b300-4", "b300-5"] # b300-3 given back; isb's pick and claim kept + assert "b300-3" not in leases.assigned and {"b300-4", *NAMES} <= leases.assigned + assert leases.picks["isa"] == NAMES + + +def test_an_owed_stop_is_retried_only_while_the_island_waits(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + assert ops.relaunch(None, "isl") == 1 # replaced at the first check: no wait, no retry + join_stops(spares) + assert ("unanswered", "b300-1", "kill") not in cluster.calls # the dead node is not asked to stop + assert not ops.islands["isl"].owed_retries + + +def test_an_islands_retry_runs_only_its_own_owed_stops(tmp_path): + """M10: islands isa and isb of one run; b300-1 owes isa's stop. isb waits for a spare + with b300-1 in its pool: its retries never run isa's stop.""" + import dataclasses + + cluster = Cluster([*NAMES, "b300-3", "b300-4", "b300-5", "b300-6"]) + clock = Clock() + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=2) + sa = islands_spec() + spa, _ = make_spares(tmp_path, sa, [spare(3)]) + ops.add("isa", sa, spares=spa) + sb = dataclasses.replace(islands_spec(), nodes=(b300(4), b300(5), b300(6))) + spb, _ = make_spares(tmp_path, sb, [b300(1)]) # its only spare is isa's lost node + ops.add("isb", sb, spares=spb) + ops.start("isa") + ops.start("isb") + cluster.lose("b300-1") + assert wait_for(lambda: ops.islands["isa"].job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isa", 0) + assert ops.relaunch(None, "isa") == 1 # isa: b300-3 in b300-1's place + cluster.lose("b300-5") + assert wait_for(lambda: ops.islands["isb"].job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isb", 0) + assert ops.relaunch(None, "isb") is None and ops.waiting_spare("isb") # b300-1 is quarantined + cluster.unreachable.discard("b300-1") + before = len(cluster.calls) + clock.t += 61 + assert ops.relaunch(None, "isb") is None # isb's backoff check + join_stops(spb) + assert "b300-1" not in ops.islands["isb"].owed_retries # not isb's to stop + assert not [c for c in cluster.calls[before:] if c[0] == "kill" and c[1] == "b300-1"] + assert "run1/isa-i0-owed-b300-1" in open_rows(tmp_path) # isa's to stop (release-node, its own retry) + + +def test_a_settled_stop_is_not_owed_again_after_a_restart(tmp_path): + """M22: b300-2's own stop went through (settled); a restarted launcher, with no memory + of that, releases incarnation 0 again and records no owed row for it.""" + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0) + s = islands_spec() + spares, store = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + rec = ops.islands["isl"] + cluster.kill_rc["b300-0"] = 1 # the release at the loss is not confirmed: the restart releases again + ops._node_health_lost(rec, 2, ["XID 79 on GPU 3"], READING) + join_stops(spares) + assert ("b300-2", 0) in spares.stopped and spares.records.own_quarantine("b300-2")["owed"] == [] + rec.lock.close() + for proc in rec.job.procs: + proc.terminate() + cluster.kill_rc.clear() + again = make_ops(tmp_path, cluster, health_every_s=0) + fresh, _ = make_spares(tmp_path, islands_spec(), [spare(3)]) + again.add("isl", islands_spec(), spares=fresh) + again.start("isl") + assert not [r for r in open_rows(tmp_path) if r.endswith("-owed-b300-2")] + + +def test_a_settle_clears_only_that_nodes_stop_of_that_incarnation(tmp_path): + records = NodeRecords(DirectoryObjectStore(tmp_path / "store"), run_id="run1", log=lambda m: None) + rows = [{"run_id": "run1", "island": "isl", "incarnation": k} for k in (0, 1)] + records.quarantine("b300-1", island="isl", reason="lost", owed=rows) + records.quarantine("b300-2", island="isl", reason="lost", owed=rows[:1]) + records.settle("b300-1", run_id="run1", island="isl", incarnation=0) + assert [o["incarnation"] for o in records.own_quarantine("b300-1")["owed"]] == [1] + assert [o["incarnation"] for o in records.own_quarantine("b300-2")["owed"]] == [0] + records.settle("b300-1", run_id="run1", island="other", incarnation=1) # another island's: nothing + assert [o["incarnation"] for o in records.own_quarantine("b300-1")["owed"]] == [1] + records.release("b300-1") # the record and its markers go; the tombstone stays + assert [k.rsplit("/", 1)[-1] for k in records.objects.list("fleet/nodes/b300-1/")] == ["released.json"] + + +def test_a_confirmed_owed_stop_removes_the_pid_file_and_a_second_try_signals_nothing(tmp_path): + """The owed stop, run by bash: it stops the incarnation's process group, removes its + pid file and leaves a marker; a second try, and the ledger's plain kill script (the + pid file gone, the state dir there), exit 0 without a pid. Without the marker the + plain kill script exits 3 (the island may still run).""" + import os + import signal + import subprocess + import time as _time + + from yeto.launch.ssh_trainer_island import STATE_DIR, kill_script, remote_paths + + home = tmp_path / "home" + sdir = home / STATE_DIR / "run1" / "isl-i0" + sdir.mkdir(parents=True) + # the island's process group, not a child of this test (a dead child stays a zombie + # that ``kill -0`` still finds on Linux): its leader exits, the sleep is orphaned + out = subprocess.run(["bash", "-c", "sleep 60 >/dev/null 2>&1 & echo $!"], start_new_session=True, + capture_output=True, text=True, timeout=30) + pid = int(out.stdout) + try: + (sdir / "pgid").write_text(f"{os.getpgid(pid)}\n") + env = {**os.environ, "HOME": str(home)} + script = isp.owed_kill_script("run1", "isl", 0, 5, None) + assert subprocess.run(["bash", "-c", script], env=env, timeout=30).returncode == 0 + assert not (sdir / "pgid").exists() and (sdir / "stopped").exists() + assert subprocess.run(["bash", "-c", script], env=env, timeout=30).returncode == 0 + plain = kill_script(remote_paths("run1", "isl", 0), 2) + assert subprocess.run(["bash", "-c", plain], env=env, timeout=30, capture_output=True).returncode == 0 + (sdir / "stopped").unlink() + assert subprocess.run(["bash", "-c", plain], env=env, timeout=30, capture_output=True).returncode == 3 + finally: + deadline = _time.monotonic() + 10 + while _time.monotonic() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + break + _time.sleep(0.05) + else: # still there: this test's own sleep + os.kill(pid, signal.SIGKILL) + + +def test_a_failed_owed_stop_keeps_the_pid_file(tmp_path): + import os + import subprocess + + from yeto.launch.ssh_trainer_island import STATE_DIR + + home = tmp_path / "home" + sdir = home / STATE_DIR / "run1" / "isl-i0" + sdir.mkdir(parents=True) + (sdir / "pgid").write_text("") # no pid in it: the stop is not confirmed (exit 3) + script = isp.owed_kill_script("run1", "isl", 0, 1, None) + done = subprocess.run(["bash", "-c", script], env={**os.environ, "HOME": str(home)}, timeout=30, + capture_output=True) + assert done.returncode == 3 + assert (sdir / "pgid").exists() and not (sdir / "stopped").exists() + + +def test_an_owed_stop_reads_the_record_again_and_skips_a_node_released_meanwhile(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[]) # no spare: the island waits + assert ops.relaunch(None, "isl") is None and ops.waiting_spare("isl") + rec, node = ops.islands["isl"], spares.pool[1] + rows = spares.records.own_quarantine("b300-1")["owed"] # read by the retry + cluster.unreachable.discard("b300-1") + NodeRecords(store, run_id="", log=lambda m: None).release("b300-1") # release-node, before its kill + ops._stop_owed(rec, node, rows) + assert ("kill", "b300-1", 0) not in cluster.calls + + +def test_an_owed_stop_of_another_island_is_not_run(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[]) + assert ops.relaunch(None, "isl") is None + cluster.unreachable.discard("b300-1") + doc = json.loads(store.read("fleet/nodes/b300-1/quarantine.json")) + doc["owed"] = [{**o, "island": "isb"} for o in doc["owed"]] # incarnation 0 of island isb + store.write("fleet/nodes/b300-1/quarantine.json", json.dumps(doc).encode()) + assert not ops._run_owed_stop(ops.islands["isl"], spares.pool[1], 0, None, what="quarantined node") + assert ("kill", "b300-1", 0) not in cluster.calls + + +def test_an_owed_stop_closes_its_row_even_when_its_settle_fails(tmp_path, monkeypatch): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[]) + assert ops.relaunch(None, "isl") is None and open_rows(tmp_path) == ["run1/isl-i0-owed-b300-1"] + + def settle(*a, **kw): + raise OSError("store unavailable") + + monkeypatch.setattr(spares.records, "settle", settle) + cluster.unreachable.discard("b300-1") + clock.t += 61 + ops.relaunch(None, "isl") + join_stops(spares) + assert ("kill", "b300-1", 0) in cluster.calls + assert open_rows(tmp_path) == [] # stopped: the row closes + assert spares.records.own_quarantine("b300-1")["owed"] # the record still lists it: release-node runs it again + + +@pytest.mark.parametrize("how", ["down", "close"]) +def test_the_owed_stop_retries_are_joined_when_the_island_goes(tmp_path, how): + import threading + import time as _time + + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0) + s = islands_spec() + spares, _ = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + rec = ops.islands["isl"] + retry = threading.Thread(target=_time.sleep, args=(0.5,), daemon=True) + retry.start() + rec.owed_retries["b300-1"] = retry + ops.down("isl") if how == "down" else ops.close() + assert not retry.is_alive() and rec.owed_retries == {} + + +def test_a_start_gives_back_a_stale_lease_of_a_node_the_island_no_longer_runs_on(tmp_path): + """A first start whose leases picked an old node for the island (a lease record older + than its spares journal): the start gives it back and records the island's nodes.""" + import dataclasses + + from tests.test_rl_object_store import FakeS3 + from yeto.cloud.s3_store import S3ObjectStore + from yeto.launch.node_lease import NodeLeases + + objects, clock = S3ObjectStore(LEASE_STORE, client=FakeS3()), Clock() + leases = NodeLeases(LEASE_STORE, "run1/trainer", identity="aaaa", objects=objects, clock=clock, monotonic=clock) + for n in (*NAMES, "b300-3"): + assert leases.acquire(n).ok + leases.picks["isl"] = [*NAMES, "b300-3"] + leases.assigned |= {*NAMES, "b300-3"} + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0) + s = dataclasses.replace(islands_spec(), leases=leases) + spares, _ = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + assert "b300-3" not in leases.held() and leases.picks["isl"] == NAMES + + +def test_a_stopped_node_owes_no_row_at_a_later_release_even_while_its_record_lists_it(tmp_path): + """The stop of b300-2 went through but its settle marker was not written (the record + still lists the stop): a release of that incarnation afterwards records no owed row.""" + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0) + s = islands_spec() + spares, _ = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops.start("isl") + rec = ops.islands["isl"] + spares.lost[2] = "XID 79 on GPU 3" + spares.records.quarantine("b300-2", island="isl", reason="lost", + owed=[isp.owed_stop("run1", "isl", 0, 2, False)]) + spares.stopped.add(("b300-2", 0)) + assert ops._release(rec, 0, skip=frozenset({"b300-2"})) + assert not [r for r in open_rows(tmp_path) if "-owed-" in r] + + +def test_a_reattach_holds_its_nodes_leases_when_its_pick_did_not(tmp_path): + """A restarted launcher whose leases hold the island's old nodes but not the spare that + runs at rank 1 (an older pick): the reattach takes the spare's lease too.""" + import dataclasses + + run = _lease_run(tmp_path) + leases = run.leases_of() + for n in ("b300-0", "b300-2"): + assert leases.acquire(n).ok + again = make_ops(tmp_path, run.cluster, clock=run.clock, health_every_s=0, unreachable_polls=2) + fresh, _ = make_spares(tmp_path, islands_spec(), [spare(3)]) + again.add("isl", dataclasses.replace(islands_spec(), leases=leases), spares=fresh) + assert again.start("isl") == 1 # reattached + assert sorted(leases.held()) == ["b300-0", "b300-2", "b300-3"] + + +def test_a_failed_start_on_a_spare_puts_the_lease_record_back(tmp_path, monkeypatch): + import dataclasses + + from tests.test_rl_object_store import FakeS3 + from yeto.cloud.s3_store import S3ObjectStore + from yeto.launch import ssh_trainer_island as sti + from yeto.launch.node_lease import NodeLeases + + objects, clock = S3ObjectStore(LEASE_STORE, client=FakeS3()), Clock() + args = SimpleNamespace(cluster_prefix="run1", rl_node_inventory_nodes=[*islands_spec().nodes, spare(3)]) + leases = NodeLeases(LEASE_STORE, "run1/trainer", identity="aaaa", objects=objects, clock=clock, monotonic=clock) + nodes = sti.lease_trainer_nodes(args, islands_spec().nodes, 3, leases, name="isl", wait_s=0) + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0, unreachable_polls=2) + spares, _ = make_spares(tmp_path, islands_spec(), [spare(3)]) + ops.add("isl", dataclasses.replace(islands_spec(), nodes=tuple(nodes), leases=leases), spares=spares) + ops.start("isl") + rec = ops.islands["isl"] + cluster.lose("b300-1") + assert wait_for(lambda: rec.job.procs[1].poll() is not None) + for _ in range(2): + ops.job_status("isl", 0) + + def failed(self, incarnation, *a, **kw): + raise RuntimeError("preflight on the spare failed") + + monkeypatch.setattr(sti.SshTrainerIslands, "launch", failed) + assert ops.relaunch(None, "isl") is None and ops.waiting_spare("isl") + assert sti._lease_record(args)["islands"]["isl"] == NAMES # back to the nodes it runs on + assert leases.picks["isl"] == NAMES and [n.name for n in rec.spec.nodes] == NAMES diff --git a/tests/test_trainer_provision.py b/tests/test_trainer_provision.py index 0031890a4..fd69c9220 100644 --- a/tests/test_trainer_provision.py +++ b/tests/test_trainer_provision.py @@ -194,7 +194,8 @@ def relaunch(self, cfg, name): ("submit", name)) or f"rid-{name}") monkeypatch.setattr(modal_runner, "ModalOps", Ops) monkeypatch.setattr(modal_runner, "ModalIslandOps", IslandOps) - monkeypatch.setattr(tp, "start_resident_ssh", lambda args, tasks, names, *rest: log.append( + ssh_kw = {} + monkeypatch.setattr(tp, "start_resident_ssh", lambda args, tasks, names, *rest, **kw: ssh_kw.update(kw) or log.append( ("ssh start", tuple(sorted(names)))) or "ssh-ops") on_call = lambda name, call_id: None # noqa: E731 specs = [ClusterSpec("aws", "us-east-1", 1, 8, "H100"), ClusterSpec("verda", None, 1, 8, "B300"), @@ -218,6 +219,7 @@ def relaunch(self, cfg, name): ("on_order", "r-l2"), ("spawn", "r-l2"), # r-l3 is adopted: kept, never spawned ("guard", "r-l4"), ("ssh start", ("r-l4",))] assert island_ops.on_call is on_call and island_ops.calls == {"r-l3": "call-kept"} + assert ssh_kw == {"island_index": {"r-l4": 4}, "num_islands": 5} # its own checkpoint keys (spare nodes) assert prov.results["r-l2"] == ("call-2", None) and prov.results["r-l3"] == ("call-kept", None) diff --git a/yeto/cli.py b/yeto/cli.py index ec70c1299..27b45553f 100644 --- a/yeto/cli.py +++ b/yeto/cli.py @@ -810,6 +810,13 @@ def int_or_auto(value: str): "tearing it down and continuing with the remaining fleet (0 tears the " "learner down on its first failure; the syncer is always recovered)", ) + infra.add_argument( + "--spare-max-wait-s", + type=float, + default=None, + help="a resident ssh: trainer island with trainer-spare nodes that lost a node waits at most this " + "long for a free spare before it is given up (default 86400: 24 h)", + ) infra.add_argument( "--controller-poll", type=int, diff --git a/yeto/cluster_cli.py b/yeto/cluster_cli.py index 30f5b9189..cd0c6a0d5 100644 --- a/yeto/cluster_cli.py +++ b/yeto/cluster_cli.py @@ -24,6 +24,10 @@ Exit 0 when every probed node is in a group and no edge is missing, 1 when a node is fabric unavailable, an edge is missing or the deadline cut the probe short, 2 on a usage or inventory error, 3 when a node is busy. + +``yeto cluster release-node --inventory --store `` gives +a node a spare-pool island quarantined back to the islands +(:mod:`yeto.cluster_release_node`). """ from __future__ import annotations @@ -92,9 +96,9 @@ def idle_sections(node: Any) -> list[tuple[str, str]]: def add_parser(sub: Any) -> argparse.ArgumentParser: doc = (__doc__ or "").split("\n\n") - p = sub.add_parser("cluster", help="the machines of an SSH node inventory: fabric groups (probe, check)", - description=doc[0]) - csub = p.add_subparsers(dest="cluster_command", metavar="{probe,check}") + p = sub.add_parser("cluster", help="the machines of an SSH node inventory: fabric groups (probe, check), " + "quarantined nodes (release-node)", description=doc[0]) + csub = p.add_subparsers(dest="cluster_command", metavar="{probe,check,release-node}") csub.required = True probe = csub.add_parser( "probe", help="group the inventory's nodes by fabric (ib_write_bw + NCCL transport between nodes)", @@ -124,6 +128,9 @@ def add_parser(sub: Any) -> argparse.ArgumentParser: check.add_argument("--inventory", required=True, help="the SSH node inventory (YAML / JSON)") check.add_argument("--nodes", default=None, help="the candidate nodes (comma-separated names; default all)") check.add_argument("--need", type=int, default=None, help="place an island of this many nodes") + from .cluster_release_node import add_parser as add_release_node # noqa: PLC0415 + + add_release_node(csub) return p @@ -138,6 +145,10 @@ def main(args: argparse.Namespace, *, ops: Any = None, log: Any = None, clock: A return probe_main(args, ops=ops, log=log, clock=clock, leases=leases) if command == "check": return check_main(args) + if command == "release-node": + from .cluster_release_node import main as release_node_main # noqa: PLC0415 + + return release_node_main(args) _say(f"[yeto] cluster: unknown command {command!r}") return 2 diff --git a/yeto/cluster_release_node.py b/yeto/cluster_release_node.py new file mode 100644 index 000000000..ab7dfed61 --- /dev/null +++ b/yeto/cluster_release_node.py @@ -0,0 +1,45 @@ +"""``yeto cluster release-node ``: give a quarantined spare-pool node back to the islands. + +A resident ``ssh:`` trainer island with spare nodes (``roles: [trainer-spare]``) quarantines +a node it lost (no answer over SSH, or node health bad twice in a row) in the run store, +``fleet/nodes//quarantine.json`` (with a ``lease_store``: also in the lease store, where +every run's pick leaves it out). The node stays out of every pick until this command: it +shows the record, runs the node's health check (``--force`` skips it, with a WARN), runs the +stops the node still owes, gives up the run's cross-run lease (a live one only after a probe +found nothing of the run on the node) and removes the record. + +Exit 0 released (or not quarantined), 1 the check, a stop or the lease release failed (the +record stays), 2 a usage or inventory error. +""" + +from __future__ import annotations + +import argparse +from typing import Any + +COMMAND = "release-node" + + +def add_parser(csub: Any) -> argparse.ArgumentParser: + """``release-node`` under the ``yeto cluster`` subcommands ``csub``.""" + doc = (__doc__ or "").split("\n\n") + p = csub.add_parser(COMMAND, help="give a quarantined spare-pool node back to the islands", + description="\n\n".join(doc[1:])) + p.add_argument("name", help="the node's name in the inventory") + p.add_argument("--inventory", required=True, help="the SSH node inventory (YAML / JSON)") + p.add_argument("--store", required=True, + help="the run store that holds the quarantine (the run's --rl-checkpoint-store)") + p.add_argument("--dry-run", action="store_true", + help="print the record and the stops that would run; no SSH, nothing removed") + p.add_argument("--force", action="store_true", help="release without the node's health check") + p.add_argument("--kill-grace-s", type=int, default=None, + help="seconds an owed stop waits after SIGTERM before SIGKILL") + return p + + +def main(args: argparse.Namespace, **kw: Any) -> int: + from .launch.island_spares import release_node_main + + return release_node_main(inventory=args.inventory, name=args.name, store=args.store, + dry_run=bool(args.dry_run), force=bool(args.force), + kill_grace_s=args.kill_grace_s, **kw) diff --git a/yeto/launch/fleet.py b/yeto/launch/fleet.py index 99eb1d0a4..35f1be93f 100644 --- a/yeto/launch/fleet.py +++ b/yeto/launch/fleet.py @@ -83,6 +83,9 @@ class _RlStrictFailure: reason: str +SPARE_RETRY_SAY_S = 900.0 # "relaunch attempt failed" while an island waits for a spare node: this often + + class RelaunchBlocked(Exception): """Raised by ``sky_ops.relaunch`` when the island must not be relaunched at all (not now, not on a later poll): e.g. its Modal app was stopped by a teardown. @@ -608,6 +611,9 @@ def _record(self, rec, state: str | None = None, **fields) -> None: if health is not None: # the source's node health checks (yeto.hw.node_health) fields.setdefault("health", health) rec["health_recorded"] = self._health_key(health) + spares = self._spares_view(rec["name"]) # an ssh: island with spare nodes (else no field) + if spares is not None: + fields.setdefault("spares", spares) self.recorder.record( rec["name"], state or self._unified_state(rec), handle=lifecycle.handle_of(ref.source, rec["name"], rec["job_id"]), @@ -665,6 +671,7 @@ def _poll_recorded(self, rec) -> None: if not self._island_stop(rec): self._poll(rec, is_syncer=False) except BaseException as error: + self._source_events(rec) if self.recorder is not None and rec["state"] != DONE: # a stopped island stays done state = lifecycle.ABANDONED if isinstance(error, FixedRosterIslandAbandoned) else lifecycle.FAILED if rec.get("decision") is None and state == lifecycle.FAILED: @@ -681,8 +688,51 @@ def _poll_recorded(self, rec) -> None: reason = rec.get("exit") if rec.get("exit") is not None else ( decision.detail if decision is not None else None) self._record(rec, reason=None if reason is None else str(reason)[:300]) + self._source_events(rec) + elif self._source_events(rec): + self._record(rec) # a spare-node event: the record shows the island's spares now self._health_events(rec) + def _source_events(self, rec) -> bool: + """The island source's own events since the last poll (``ops.island_events``: a resident + ``ssh:`` island with spare nodes writes ``island_node_lost``, ``island_waiting_spare``, + ``island_node_replaced``, ``island_replacement_limit``) into fleet.jsonl; True when + there were any. A source without them writes nothing.""" + probe = getattr(self.ops, "island_events", None) + if probe is None: + return False + try: + events = list(probe(rec["name"]) or ()) + except Exception: # noqa: BLE001 - telemetry never breaks supervision + return False + for event in events: + fields = dict(event) + kind = str(fields.pop("kind", "island_event")) + self._fleet(kind, rec["name"], **fields) + return bool(events) + + def _spares_view(self, name: str): + """The island's spare nodes as its source reports them (``ops.spares_view``), or None.""" + probe = getattr(self.ops, "spares_view", None) + if probe is None: + return None + try: + return probe(name) + except Exception: # noqa: BLE001 - a view only + return None + + def _waiting_spare(self, rec) -> bool: + """The island's source waits for a spare node (``ops.waiting_spare``): the recovery + goes on past ``recover_timeout`` (the source checks again with its own backoff and + stops the island at its replacement limit).""" + probe = getattr(self.ops, "waiting_spare", None) + if probe is None: + return False + try: + return bool(probe(rec["name"])) + except Exception: # noqa: BLE001 - unknown: the timeout applies + return False + def _island_start(self, rec) -> bool: """Island ``rec``'s START request (``yeto island start``). Its record decides, not this controller's memory (a restarted or adopting launcher acts on it too): an island the @@ -1302,6 +1352,7 @@ def _source_decision(self, rec): def _enter_recovering(self, rec, reason: str, is_syncer: bool) -> None: rec["state"] = RECOVERING rec["failed_at"] = self.ops.now() + rec.pop("spare_retry_said_at", None) # a new recovery: its first retry line is said if not is_syncer: self._fleet("island_lost", rec["name"], reason=str(reason)) text = str(reason) @@ -1383,10 +1434,18 @@ def _drive_recovery(self, rec, is_syncer: bool) -> None: if self.on_relaunch is not None: self.on_relaunch(rec["name"], attempt.result) return - print( - f"[launcher] relaunch attempt for {rec['name']} failed; will retry", - file=sys.stderr, - ) + if not is_syncer and self._waiting_spare(rec): + # waiting for a spare: its source says why at each check; this line every 15 min + said = rec.get("spare_retry_said_at") + if said is None or self.ops.now() - said >= SPARE_RETRY_SAY_S: + rec["spare_retry_said_at"] = self.ops.now() + print(f"[launcher] relaunch attempt for {rec['name']} failed (waiting for a spare node); " + "will retry", file=sys.stderr) + else: + print( + f"[launcher] relaunch attempt for {rec['name']} failed; will retry", + file=sys.stderr, + ) elapsed = self.ops.now() - rec["failed_at"] if self.fixed_roster and not is_syncer and not rec.get("left_pool"): elapsed += rec.get("recovering_s", 0.0) # this window only @@ -1395,7 +1454,16 @@ def _drive_recovery(self, rec, is_syncer: bool) -> None: return # A rejected-link relaunch has its own budget (the island never joined). timeout = WAN_RECOVERY_S if rec.get("wan_recovery") else self.recover_timeout - if timeout <= 0 or elapsed > timeout: + waiting = not is_syncer and self._waiting_spare(rec) + if not waiting: + rec.pop("spare_wait_said", None) # the next wait says so again + if timeout > 0 and elapsed > timeout and waiting: + if not rec.get("spare_wait_said"): + rec["spare_wait_said"] = True + print(f"[launcher] {rec['name']}: recovering {elapsed:.0f}s, past the recover timeout " + f"({timeout:.0f}s), while it waits for a spare node; not given up (its source checks " + "again with a backoff)", file=sys.stderr) + elif timeout <= 0 or elapsed > timeout: if is_syncer: # The syncer is never abandoned: without it no learner can # make outer progress, so keep trying and complain loudly. diff --git a/yeto/launch/island_spares.py b/yeto/launch/island_spares.py new file mode 100644 index 000000000..8e8f4f6b7 --- /dev/null +++ b/yeto/launch/island_spares.py @@ -0,0 +1,1116 @@ +"""Spare nodes of a resident ``ssh:`` trainer island (own-cluster-fleet-stability D3). + +An inventory may hold more machines than the trainer island needs: a node with the role +``trainer-spare`` (:data:`SPARE_ROLE`) is no island node (``island_nodes(..., "trainer")`` +does not match it), so the island's node count and its dry run are what they were. It is a +machine the island may take when one of its own nodes is lost. An inventory without spare +nodes (e.g. the 6 x 8 B300 K3.1 layout, whose 48 cards take every node) runs exactly as +before: a lost node fails the island and the fleet relaunches it on the same nodes. + +With spare nodes, :class:`~.ssh_resident.SshIslandOps` replaces a lost node: + +1. **lost**: a node is lost once its log stream over SSH (the heartbeat: ServerAlive + keepalives) ended and it then failed ``unreachable_polls`` SSH checks in a row, or once + its health turned bad twice in a row (``yeto.hw.node_health.HealthTracker`` returned + ``lost``). An SSH check that fails while the node's stream still flows is no loss. The + island writes ``island_node_lost`` and stops every other node (its island STOP: the + incarnation is released on every node but the lost one, which is not waited for); +2. **pick**: a spare of the same ``fabric_group`` (``fabric_groups.check_placement`` on + the new node set), whose health check passes now, that no other island of this run + holds (its claim ``fleet/nodes//claim.json`` in the run store, an exclusive + create), that is not quarantined, and whose cross-run lease (``node_lease.NodeLeases``, + when the inventory names a ``lease_store``) is free. Candidates go by node name, so the + pick is reproducible; +3. **resume**: the island is rendered again with the spare in the lost node's place + (same learner id, same layout; the rendezvous address is node 0's, so a lost rank 0 + is replaced by the spare as the new node 0) and its next incarnation starts; the + trainer resumes from the newest checkpoint of its store (:func:`latest_checkpoint_step` + names it in the event). To the syncer this is an absence of the island and its re-JOIN + under the same learner id: it catches up to the newest outer weights, then merges; +4. ``island_node_replaced`` names the old node, the new one and the resume step. The lost + node is **quarantined** (``fleet/nodes//quarantine.json`` in the run store, with + the stop it still owes; with a ``lease_store`` also ``nodes//quarantine.json`` + there, which every run's pick skips): no island picks it until ``yeto cluster + release-node `` (:func:`release_node`) checked it, ran that stop and removed the + record. Nothing lifts a quarantine on its own. + +A node whose stop is not confirmed when the island fails (rank 0 often exits first on a +power loss; the lost node's stream only ends minutes later) keeps its stream and is checked +with ``ssh true`` at every relaunch poll: ``unreachable_polls`` checks in a row without an +answer make it lost too. A lost node that still answers (a health loss) is stopped at once +in the background; when that stop is confirmed it owes nothing. + +No spare: the island waits (``waiting_spare``) and checks again after 60 s, 120 s, ... at +most 900 s, with an ``island_waiting_spare`` event (``elapsed_s``) every hour; past +``--spare-max-wait-s`` (default 24 h) the relaunch is refused and the island is given up. +The fleet controller does not give it up on ``--recover-timeout`` meanwhile; a waiting +island counts as absent for ``fleet.min_islands``. At most +:data:`MAX_REPLACEMENTS` replacements per island within :data:`REPLACEMENT_WINDOW_S`: the next +loss stops the island (its relaunch is refused) and names every node it replaced. +""" + +from __future__ import annotations + +import json +import sys +import threading +import time +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from .node_inventory import Node +from .node_quarantine import ( # noqa: F401 - the shared names here too + QUARANTINE_NAME, + RELEASE_NODE_HINT, + SHARED_NODES_DIR, + describe, + release_how, + JOURNAL_SUFFIX, + SPARE_ROLE, + shared_quarantined_names, +) + +NODES_DIR = "fleet/nodes" # under the run store +CLAIM_NAME = "claim.json" +RELEASED_NAME = "released.json" # release-node's tombstone (fleet/nodes//, and in the lease store) +SETTLED_DIR = "settled" # fleet/nodes//settled/--i.json: a stop owed no more +CLAIM_SCHEMA = "yeto.fleet.node-claim/v1" +QUARANTINE_SCHEMA = "yeto.fleet.node-quarantine/v1" +WAIT_FIRST_S = 60.0 +WAIT_MAX_S = 900.0 +MAX_REPLACEMENTS = 3 +REPLACEMENT_WINDOW_S = 24 * 3600.0 +MAX_WAIT_S = 24 * 3600.0 # --spare-max-wait-s: waiting for a spare longer gives the island up +WAIT_REPORT_S = 3600.0 # an island_waiting_spare event this often while it waits +SSH_FAILED = 255 # the exit code of ssh itself (no connection, no session) +# the inventory fields a spare must share with the island's nodes (the island's layout, +# image and device flags take it as one of them) +SAME_AS_ISLAND = ("device_family", "cpu_arch", "card", "cards_per_node", "runtime") + +# Event kinds (fleet.jsonl and the island's record) +NODE_LOST = "island_node_lost" +NODE_REPLACED = "island_node_replaced" +WAITING_SPARE = "island_waiting_spare" +REPLACEMENT_LIMIT = "island_replacement_limit" + + +class SpareError(RuntimeError): + """The spare nodes of an inventory cannot serve the island.""" + + +def spare_nodes(nodes: Iterable[Node]) -> list[Node]: + """The inventory's spare nodes of ``ssh:`` trainer islands (role :data:`SPARE_ROLE`).""" + return [n for n in nodes if SPARE_ROLE in tuple(getattr(n, "roles", ()) or ())] + + +def check_spares(island: Sequence[Node], spares: Sequence[Node]) -> None: + """Every spare must be able to take any island node's place: the same device family, CPU + architecture, card, card count and runtime (raises :class:`SpareError`).""" + if not island: + return + ref = island[0] + names = {n.name for n in island} + for node in spares: + if node.name in names: + raise SpareError(f"node {node.name} is both an island node and a {SPARE_ROLE}") + if "trainer" in node.roles: + raise SpareError(f"node {node.name}: roles trainer and {SPARE_ROLE} exclude each other") + wrong = [f"{key} {getattr(node, key)!r} (island: {getattr(ref, key)!r})" for key in SAME_AS_ISLAND + if getattr(node, key) != getattr(ref, key)] + if bool(node.store_env_file) != bool(ref.store_env_file): + wrong.append("store_env_file " + ("set" if node.store_env_file else "unset") + + f" (island: {'set' if ref.store_env_file else 'unset'})") + if wrong: + raise SpareError(f"{SPARE_ROLE} node {node.name} cannot take an island node's place: " + + "; ".join(wrong)) + + +def spares_from_args(args: Any, spec: Any, *, objects: Any = None, leases: Any = None, + log: Callable[[str], None] | None = None, island_index: int | None = None, + num_islands: int | None = None, shared: Any = None) -> IslandSpares | None: + """The :class:`IslandSpares` of the resident ``ssh:`` island ``spec`` (an + ``SshTrainerSpec``) from ``--rl-node-inventory``; None when the inventory has no spare + node, or the island's device family has no node health check (a WARN says the spares + do not apply): nothing changes then, as on main. Every spare must fit the island (:func:`check_spares`) + and the island's spec must take it in any node's place (its rendezvous address, docker + flags); raises :class:`SpareError`. ``objects``: the run store's object API (claims, + quarantine, the resume point; None: :func:`store_objects_of` ``--rl-checkpoint-store``). + ``island_index`` / ``num_islands``: the island's index among the launch's islands (its + own checkpoint keys, :func:`resume_keys`, which finds its learner id). ``shared``: the inventory's ``lease_store`` + object API (None: :func:`lease_store_objects_of`), where a quarantine is shared.""" + import dataclasses # noqa: PLC0415 + + spares = spare_nodes(getattr(args, "rl_node_inventory_nodes", None) or ()) + if not spares: + return None + check_spares(spec.nodes, spares) + for node in spares: + try: + dataclasses.replace(spec, nodes=(node, *spec.nodes[1:])) + except Exception as error: # noqa: BLE001 - SshIslandError: the spare as the island sees it + raise SpareError(f"{SPARE_ROLE} node {node.name}: {error}") from None + note = no_checker_note(spec) + if note is not None: # no spare without a health check: the island runs as on main + (log or (lambda m: print(m, file=sys.stderr, flush=True)))(note) + return None + if objects is None: + objects = store_objects_of(args) + if shared is None: + shared = lease_store_objects_of(args) + keys = resume_keys(args, island_index, num_islands) + max_wait = getattr(args, "spare_max_wait_s", None) + return IslandSpares(pool=(*spec.nodes, *spares), + records=NodeRecords(objects, run_id=str(getattr(args, "cluster_prefix", "") or spec.run_id), + log=log, shared=shared), + leases=leases, resume_probe=lambda: latest_checkpoint_step(objects, keys), + max_wait_s=float(MAX_WAIT_S if max_wait is None else max_wait)) + + +def no_checker_note(spec: Any) -> str | None: + """The one line said when an island has spare nodes but its device family has no node + health check here (``yeto.hw.node_health``): no spare is picked without one, so the + spares do not apply at all (:func:`spares_from_args` returns None).""" + family = spec.nodes[0].device_family if getattr(spec, "nodes", None) else None + if family is None or _checker_for(family) is not None: + return None + return (f"[launcher] WARN: the inventory declares {SPARE_ROLE} nodes, but device family {family} has no node " + "health check in this version (yeto.hw.node_health): the spare nodes do not apply; a failed island " + "is relaunched on its own nodes, as without spares") + + +def spare_view(args: Any, spec: Any) -> dict[str, Any] | None: + """The dry run's ``spares`` of a resident ``ssh:`` island (None: no spare node, the + record is unchanged): the spare nodes, their fabric groups and the replacement rules. + Without a health check for the island's device family it says so (:func:`no_checker_note`).""" + spares = spare_nodes(getattr(args, "rl_node_inventory_nodes", None) or ()) + if not spares: + return None + note = no_checker_note(spec) + if note is not None: + print(note, file=sys.stderr, flush=True) + return {"nodes": [n.name for n in spares], **({"note": note} if note is not None else {}), + "fabric_groups": {n.name: fabric_group(n) for n in (*spec.nodes, *spares)}, + "lost": "stream ended and no SSH answer unreachable_polls times in a row, or health bad twice", + "pick": "same fabric group, health check passed now, not held by another island of the run " + f"({NODES_DIR}//{CLAIM_NAME}), not quarantined, cross-run lease free; by name", + "quarantine": f"{NODES_DIR}//{QUARANTINE_NAME} until released by hand: {RELEASE_NODE_HINT}", + "waiting_spare_s": [WAIT_FIRST_S, WAIT_MAX_S], + "max_wait_s": float(MAX_WAIT_S if getattr(args, "spare_max_wait_s", None) is None + else args.spare_max_wait_s), + "max_replacements": {"count": MAX_REPLACEMENTS, "window_h": REPLACEMENT_WINDOW_S / 3600}} + + +def store_objects_of(args: Any) -> Any: + """The object API of the run's ``--rl-checkpoint-store`` (None: none here).""" + from .island_lifecycle import store_objects # noqa: PLC0415 + + try: + from .storage import store_client_environ # noqa: PLC0415 + + return store_objects(getattr(args, "rl_checkpoint_store", None), store_client_environ(args)) + except Exception: # noqa: BLE001 - no object API: the records stay with this launcher + return None + + +def lease_store_objects_of(args: Any) -> Any: + """The object API of the inventory's ``lease_store`` (``node_inventory.lease_store_of``; + None: not declared, or no object API here).""" + uri = getattr(getattr(args, "rl_node_inventory_nodes", None), "lease_store", None) + if not uri: + return None + try: + from .node_lease import open_objects # noqa: PLC0415 + + return open_objects(str(uri)) + except ImportError: + pass + except Exception: # noqa: BLE001 - no object API: the run store's record still holds + return None + from .island_lifecycle import store_objects # noqa: PLC0415 + + try: + from .storage import store_client_environ # noqa: PLC0415 + + return store_objects(str(uri), store_client_environ(args)) + except Exception: # noqa: BLE001 - as above + return None + + +def fabric_group(node: Node) -> str | None: + return getattr(node, "fabric_group", None) + + +# -- the dependencies of other groups (node health, fabric groups) ------------------------ +def _checker_for(family: str, **options: Any) -> Any: + """The device family's node health checker (``yeto.hw.node_health.checker_for``); None + for a family without one (its ``NullChecker``: nothing run, nothing judged).""" + from yeto.hw import node_health # noqa: PLC0415 + + checker = node_health.checker_for(family, **options) + return checker if getattr(checker, "enabled", True) else None + + +UNAVAILABLE_GROUP = "unavailable" # fabric_groups' reserved group: never a node of a multi-node island + + +def _unavailable(node: Node) -> bool: + return str(fabric_group(node) or "").lower() == UNAVAILABLE_GROUP + + +def _pick_placement(candidates: Sequence[Node], need: int, *, excluded: Mapping[str, str] | None = None, + required: Sequence[Node] = (), inventory: Sequence[Node] | None = None) -> tuple[Node | None, str]: + """``(node, why)``: the node ``fabric_groups.pick_placement`` adds to the ``required`` + ones (the island's nodes that stay: the island is never moved to other nodes); + ``excluded``: node name -> why it is out. No node: ``why`` is the + :class:`~.fabric_groups.PlacementError`'s text (it goes into the wait reason); any other + error (a ``TypeError``) is raised. A placement that drops a required node is refused.""" + from .fabric_groups import PlacementError, pick_placement # noqa: PLC0415 + + required = list(required) + names = {r.name for r in required} + pool = [*required, *(n for n in candidates if n.name not in names)] + try: + placement = pick_placement(pool, need, excluded=dict(excluded or {}), required=required, + inventory=list(candidates) if inventory is None else list(inventory)) + except PlacementError as error: + return None, str(error) + nodes = list(placement.nodes) + if any(r.name not in {n.name for n in nodes} for r in required): # the nodes that stay never move + return None, f"the placement {[n.name for n in nodes]} drops a node that stays ({sorted(names)})" + added = [n for n in nodes if n.name not in names] + return (added[0], "") if added else (None, f"the placement {[n.name for n in nodes]} adds no node") + + +def hcas_of(node: Node, env: Mapping[str, str] | None = None) -> list[str]: + """The job ports of the node as the island's health watch reads them: ``NCCL_IB_HCA`` + of the node's inventory env with the island's job ``env`` over it (the job's own + order), ``node_health.hcas_of``.""" + from yeto.hw import node_health # noqa: PLC0415 + + return node_health.hcas_of({**dict(node.env or {}), **dict(env or {})}.get("NCCL_IB_HCA")) + + +def node_check(node: Node, ops: Any, *, multi: bool, timeout: float = 120.0, + env: Mapping[str, str] | None = None) -> tuple[bool, str]: + """Whether ``node`` may take an island node's place now: its health check (one SSH + call, ``yeto.hw.node_health``) ran (``checked``) and passes for a multi-node (``multi``) + or single-node island. An answer over SSH alone is not enough: a family without a + checker, or a check that did not run, is refused. ``env``: the island's job env (its + ``NCCL_IB_HCA`` names the ports checked, as the island's own health watch does).""" + from .ssh_trainer_island import RDMA_FABRICS # noqa: PLC0415 + + checker = _checker_for(node.device_family, expect_gpus=node.cards_per_node, + fabric=node.fabric if node.fabric in RDMA_FABRICS else None) + if checker is None: + return False, f"no health check for device family {node.device_family} here (yeto.hw.node_health)" + hcas = hcas_of(node, env) if multi else [] + script = checker.script(hcas) + if not script: + return False, f"the health check of device family {node.device_family} runs nothing" + try: + done = ops.run(node, script, timeout=timeout) + except Exception as error: # noqa: BLE001 - a timeout is an unreachable node + return False, f"unreachable ({type(error).__name__})" + if done.returncode == SSH_FAILED: + return False, f"unreachable (rc {done.returncode})" # 255: ssh itself failed, no output to judge + result = checker.parse(getattr(done, "stdout", "") or "", hcas, None) + if not getattr(result, "checked", False): + return False, f"health not checked (rc {done.returncode})" + ok = result.ok_multi if multi else result.ok_single + if ok: + return True, "healthy" + return False, "unhealthy: " + ("; ".join(result.reasons) or "check failed") + + +# -- the run store's node records --------------------------------------------------------- +class NodeRecords: + """Claims and quarantine records of nodes in the run store (``fleet/nodes//``). + + A claim says which island of the run holds the node (an exclusive create, so two islands + of one run never take one spare; a store whose create is check-then-write, e.g. the OSS + relay, is refused); a quarantine record keeps a lost node out of every pick until + :func:`release_node`. ``objects``: the run store's object API; None keeps the records in + this process only (said once). ``shared``: the object API of the inventory's + ``lease_store``, where a quarantine is written too (``nodes//quarantine.json``), + so another run's pick skips the node.""" + + def __init__(self, objects: Any, *, run_id: str, log: Callable[[str], None] | None = None, + wall: Callable[[], float] = time.time, shared: Any = None) -> None: + self.objects = objects + self.shared = shared + self.run_id = str(run_id) + self.log = log or (lambda m: print(m, file=sys.stderr, flush=True)) + self.wall = wall + self._memory: dict[str, bytes] = {} + if objects is None: + self.log("[launcher] spare nodes: the run store has no object API here; node claims and " + "quarantine records are kept by this launcher only") + + @staticmethod + def key(name: str, what: str) -> str: + return f"{NODES_DIR}/{name}/{what}" + + @staticmethod + def shared_key(name: str) -> str: + return f"{SHARED_NODES_DIR}/{name}/{QUARANTINE_NAME}" + + # -- raw access + @staticmethod + def _parse(raw: bytes | None) -> dict[str, Any] | None: + if raw is None: + return None + try: + doc = json.loads(raw) + except ValueError: + doc = None + return doc if isinstance(doc, dict) else {"unreadable": True, + "reason": "quarantine record unreadable: not a JSON object"} + + def _read(self, key: str) -> dict[str, Any] | None: + return self._parse(self._memory.get(key) if self.objects is None else self.objects.read(key)) + + def _write(self, key: str, doc: Mapping[str, Any]) -> None: + data = json.dumps(dict(doc), sort_keys=True).encode() + if self.objects is None: + self._memory[key] = data + else: + self.objects.write(key, data) + + def _create(self, key: str, doc: Mapping[str, Any]) -> bool: + data = json.dumps(dict(doc), sort_keys=True).encode() + if self.objects is None: + if key in self._memory: + return False + self._memory[key] = data + return True + from yeto.rl.engine.object_store import atomic_create # noqa: PLC0415 + + refused = SpareError("the run store has no atomic exclusive create (a check-then-write store such as " + "the OSS relay, or an endpoint that refuses If-None-Match): two islands could " + "claim one spare node there; use an s3:// / r2:// store or a local directory") + if not atomic_create(self.objects): + raise refused + created = bool(self.objects.create(key, data)) + if created and not atomic_create(self.objects): # the store found out on this create + self.objects.delete(key) + raise refused + return created + + def _delete(self, key: str) -> None: + if self.objects is None: + self._memory.pop(key, None) + else: + self.objects.delete(key) + + # -- claims + def holder(self, name: str) -> str | None: + """The island of this run that holds ``name`` (None: free).""" + doc = self._read(self.key(name, CLAIM_NAME)) + if doc is None: + return None + return f"{doc.get('run')}/{doc.get('island')}" if doc.get("run") != self.run_id else str(doc.get("island")) + + def claim(self, name: str, island: str) -> str | None: + """Take ``name`` for ``island``; None when it is the island's now, else its holder. + Raises :class:`SpareError` on a store without an atomic create.""" + doc = {"schema": CLAIM_SCHEMA, "node": name, "run": self.run_id, "island": island, "at": self.wall()} + if self._create(self.key(name, CLAIM_NAME), doc): + return None + held = self.holder(name) + return None if held == island else (held or "unknown") + + def unclaim(self, name: str, island: str) -> None: + if self.holder(name) == island: + self._delete(self.key(name, CLAIM_NAME)) + + # -- quarantine + def shared_quarantined(self, name: str) -> dict[str, Any] | None: + """The node's quarantine in the lease store (any run's; None: none, or no lease store).""" + if self.shared is None: + return None + from .node_quarantine import read_record # noqa: PLC0415 + + return read_record(self.shared, name) # unreadable: a quarantine (with that reason) + + def own_quarantine(self, name: str) -> dict[str, Any] | None: + """The node's quarantine record in this run store (None: not quarantined here); its + ``owed`` leaves out every stop a :meth:`settle` marker says went through.""" + doc = self._read(self.key(name, QUARANTINE_NAME)) + if doc is None or not doc.get("owed"): + return doc + done = self._settled(name) + if not done: + return doc + return {**doc, "owed": [o for o in doc["owed"] if _owed_key(o) not in done]} + + def _settled(self, name: str) -> set[tuple[str, str, int]]: + prefix = f"{NODES_DIR}/{name}/{SETTLED_DIR}/" + out = set() + for key in self._list(prefix): + doc = self._read(key) + if doc is not None and not doc.get("unreadable"): + out.add((str(doc.get("run_id")), str(doc.get("island")), int(doc.get("incarnation", -1)))) + return out + + def _list(self, prefix: str) -> list[str]: + if self.objects is None: + return sorted(k for k in self._memory if k.startswith(prefix)) + return list(self.objects.list(prefix)) + + def quarantined(self, name: str) -> dict[str, Any] | None: + """The node's quarantine record: this run's, else another run's in the lease store.""" + return self.own_quarantine(name) or self.shared_quarantined(name) + + def quarantine(self, name: str, *, island: str, reason: str, owed: Sequence[Mapping[str, Any]] = (), + lease_holder: str | None = None) -> None: + """Keep ``name`` out of every pick; ``owed``: the stops it never got (run by release); + ``lease_holder``: who holds its cross-run lease (kept until release-node ends it).""" + earlier = self.own_quarantine(name) or {} + doc = {"schema": QUARANTINE_SCHEMA, "node": name, "run": self.run_id, "island": island, + "reason": str(reason)[:500], "at": self.wall(), + "owed": [*list(earlier.get("owed") or ()), *map(dict, owed)]} + holder = lease_holder or earlier.get("lease_holder") + if holder: + doc["lease_holder"] = str(holder) + self._write(self.key(name, QUARANTINE_NAME), doc) + self._share(name, doc) + + def _share(self, name: str, doc: Mapping[str, Any]) -> None: + if self.shared is None: + return + try: + self.shared.write(self.shared_key(name), json.dumps(dict(doc), sort_keys=True).encode()) + except Exception as error: # noqa: BLE001 - the run store's record still holds it in this run + self.log(f"[launcher] WARN: quarantine of {name} not written to the lease store ({error}): " + "another run may pick it") + + def settle(self, name: str, *, run_id: str, island: str, incarnation: int) -> None: + """The stop ``name`` owed for that incarnation is confirmed: it owes it no more (the + node stays quarantined). Written as a marker of its own (``settled/``, an exclusive + create), never into the quarantine record: a release-node that removes the record + meanwhile is never undone, here or in the lease store. A node released since the + record was written (its ``released.json``) gets no marker.""" + doc = self._read(self.key(name, QUARANTINE_NAME)) + if doc is None or doc.get("unreadable"): + return + released = self._read(self.key(name, RELEASED_NAME)) + if released is not None and float(released.get("at") or 0.0) >= float(doc.get("at") or 0.0): + return + self._create(self.settled_key(name, run_id, island, incarnation), + {"run_id": str(run_id), "island": str(island), "incarnation": int(incarnation), "at": self.wall()}) + + @staticmethod + def settled_key(name: str, run_id: str, island: str, incarnation: int) -> str: + return f"{NODES_DIR}/{name}/{SETTLED_DIR}/{run_id}-{island}-i{int(incarnation)}.json" + + def release(self, name: str) -> None: + """Remove the node's quarantine (run store and lease store) and its settle markers; + a ``released.json`` tombstone (with the time) stays in both.""" + stone = {"node": name, "run": self.run_id, "at": self.wall()} + self._write(self.key(name, RELEASED_NAME), stone) + for key in self._list(f"{NODES_DIR}/{name}/{SETTLED_DIR}/"): + self._delete(key) + self._delete(self.key(name, QUARANTINE_NAME)) + if self.shared is not None: + self.shared.write(f"{SHARED_NODES_DIR}/{name}/{RELEASED_NAME}", json.dumps(stone, sort_keys=True).encode()) + self.shared.delete(self.shared_key(name)) + + +def _owed_key(row: Mapping[str, Any]) -> tuple[str, str, int]: + return str(row.get("run_id")), str(row.get("island")), int(row.get("incarnation", -1)) + + +def owed_kill_script(run_id: str, island: str, incarnation: int, grace_s: int, container: str | None) -> str: + """The stop a lost node owes (``kill_script``). Once a stop went through, the pid file + is removed and a ``stopped`` marker written in its state dir: a later stop of that + incarnation (a release-node after a settle that failed, ``yeto cleanup``) exits 0 + without a pid, and never signals a process group whose pid was reused (a rebooted + node). The process group itself is not checked against the run: the pid file in the + run's own state dir names it.""" + from .ssh_trainer_island import ( # noqa: PLC0415 + STATE_HOME_VAR, + STOPPED_MARKER, + _pin_state_home, + kill_script, + remote_paths, + ) + + paths = remote_paths(run_id, island, int(incarnation)) + pinned = _pin_state_home(paths) + pid, sdir = pinned["pid"], pinned["dir"] + return (f"{STATE_HOME_VAR}=\"$HOME\"\n" + f"trap 'rc=$?; if [ $rc -eq 0 ] && [ -d \"{sdir}\" ]; then rm -f \"{pid}\"; " + f": > \"{sdir}/{STOPPED_MARKER}\"; fi; exit $rc' EXIT\n" + + kill_script(paths, int(grace_s), container=container or None)) + + +def lease_holder_id(leases: Any) -> str | None: + """Who this launcher's leases are held as (``NodeLeases.holder_id``, ``/@``; + an older lease API: its ``run_id``).""" + return getattr(leases, "holder_id", None) or getattr(leases, "run_id", None) + + +def release_node(records: NodeRecords, node: Node, ssh: Any, *, kill_grace_s: int | None = None, + leases: Any = None, probe: Callable[[Any, str], str | None] | None = None) -> tuple[bool, str]: + """``yeto cluster release-node``: run every stop the quarantined ``node`` still owes + (the incarnations it ran when it was lost; each confirmed stop closes its owed ledger + row), give up the cross-run lease the run kept on it while it was quarantined + (``leases.force_release`` as the holder its record names, else this launcher's: a lease + another run holds is not touched; a kept or run-out lease ends at once, a live one only + after ``probe(node, holder)`` (``node_lease.ssh_probe``) found nothing of that run on the + node, then with ``force``), then remove its quarantine record so the islands may pick it + again. + ``(ok, message)``; the record stays while a stop or the lease release fails.""" + from . import ssh_trainer_ledger # noqa: PLC0415 + from .ssh_trainer_island import KILL_GRACE_S # noqa: PLC0415 + + doc = records.quarantined(node.name) + if doc is None: + return True, f"node {node.name} is not quarantined" + grace = int(KILL_GRACE_S if kill_grace_s is None else kill_grace_s) + ledger_notes: list[str] = [] + for owed in doc.get("owed") or (): + run_id = str(owed.get("run_id") or records.run_id) + script = owed_kill_script(run_id, str(owed["island"]), int(owed["incarnation"]), grace, owed.get("container")) + try: + done = ssh.run(node, script, timeout=grace + 60.0) + except Exception as error: # noqa: BLE001 - reported, the record stays + return False, f"node {node.name}: the stop of {owed['island']} incarnation {owed['incarnation']} failed: {error}" + if done.returncode != 0: + err = (getattr(done, "stderr", "") or "").strip()[-300:] + return False, (f"node {node.name}: the stop of {owed['island']} incarnation {owed['incarnation']} " + f"ended rc {done.returncode} {err}").rstrip() + status, ledger_path = ssh_trainer_ledger.release_owed(run_id=run_id, island=str(owed["island"]), + incarnation=int(owed["incarnation"]), node=node.name) + if status != ssh_trainer_ledger.OWED_RELEASED: + ledger_notes.append(_owed_row_note(run_id, str(owed["island"]), int(owed["incarnation"]), node.name, + ledger_path)) + lease_note = "" + if leases is not None: + holder = doc.get("lease_holder") or lease_holder_id(leases) + try: + released = leases.force_release(node, holder=holder) # kept or run out + current = None if released else leases.holder(node) + if not released and current is not None and current == holder: # a live lease of that run + why = "no probe of the node" if probe is None else probe(node, holder) + if why is not None: + return False, (f"node {node.name}: its lease of {holder} still runs and the node is not " + f"confirmed free ({why}); it stays quarantined") + released = leases.force_release(node, holder=holder, force=True) + elif not released and current is not None: # another run holds it now: left alone + lease_note = f"; its lease is held by {current}, not released" + except Exception as error: # noqa: BLE001 - reported, the record stays + return False, (f"node {node.name}: its lease could not be released ({type(error).__name__}: " + f"{error}); it stays quarantined") + records.release(node.name) + return True, (f"node {node.name} released ({len(doc.get('owed') or ())} owed stop(s) run){lease_note}" + + "".join(f"; {n}" for n in ledger_notes)) + + +def _lease_plan(records: NodeRecords, node: Node, doc: Mapping[str, Any], leases: Any) -> str: + """What release-node would do with the node's cross-run lease (its dry run).""" + if leases is None: + return "no lease store: no lease to end" + holder = doc.get("lease_holder") or lease_holder_id(leases) + try: + current = leases.holder(node) + except Exception as error: # noqa: BLE001 - the dry run reads only + return f"the lease of {node.name} could not be read ({type(error).__name__}: {error})" + if current is None: + return f"no lease held on {node.name}: none to end" + if current != holder: + return f"the lease of {node.name} is held by {current}, not {holder}: it is left alone" + return (f"would end the lease of {holder} on {node.name} (a kept one at once; a live one only after a " + "probe over SSH finds nothing of that run on the node)") + + +def _owed_row_note(run_id: str, island: str, incarnation: int, node: str, path: str) -> str: + """Where the owed ledger row of a stop release-node ran lives when this machine has none open.""" + from yeto.cost.ledger import LEDGER_FILE # noqa: PLC0415 + + from . import ssh_trainer_ledger # noqa: PLC0415 + + rid = ssh_trainer_ledger.owed_id(run_id, island, incarnation, node) + return (f"WARN: its owed ledger row {rid} is not open in {path or 'any ledger here'}: the row is in the run " + f"dir of the machine that ran the launcher of run {run_id} (runs/{run_id}/{LEDGER_FILE}); the " + "launcher closes it (released elsewhere) when it picks the node again, or close it there with " + f"`yeto cleanup --run {run_id}` once the run has ended") + + +RELEASE_NODE_RUN = "yeto-cluster-release-node" # who ends a lease (its released_by) + + +def release_leases_of(nodes: Any, say: Callable[[str], None]) -> Any: + """The :class:`~.node_lease.NodeLeases` of the inventory's ``lease_store`` for release-node + (None: none declared, or it does not open).""" + from .node_inventory import lease_store_of # noqa: PLC0415 + + store = lease_store_of(nodes) + if not store: + return None + from .node_lease import NodeLeases # noqa: PLC0415 + + try: + return NodeLeases(str(store), RELEASE_NODE_RUN) + except Exception as error: # noqa: BLE001 - reported: the lease is left to its holder + say(f"[yeto] WARN: the lease store {store} does not open ({error}); the node's lease is not released") + return None + + +def release_node_main(*, inventory: str, name: str, store: str, ssh: Any = None, dry_run: bool = False, + force: bool = False, kill_grace_s: int | None = None, leases: Any = None, + objects: Any = None, shared: Any = None, say: Callable[[str], None] | None = None) -> int: + """``yeto cluster release-node `` (``inventory``: the inventory file, ``store``: the run + store): show the + node's quarantine record, check the node (its health check ran and passes; an answer + over SSH alone is not enough, and a family without a checker is refused), run the stops + it still owes and remove the record, so the islands may pick it again; its kept + cross-run lease is given up (``leases``). ``force``: release without the health check + (a WARN says so). ``dry_run``: the record and the stops that would run, no SSH, nothing + removed. Exit 0 released (or not quarantined), 1 the check, a stop or the lease release + failed (the record stays), 2 a usage error.""" + from .node_inventory import InventoryError, island_nodes, load_inventory # noqa: PLC0415 + + say = say or (lambda line: print(line, flush=True)) + try: + nodes = load_inventory(inventory) + except (InventoryError, OSError) as error: + say(f"[yeto] cluster release-node: {error}") + return 2 + node = next((n for n in nodes if n.name == name), None) + if node is None: + say(f"[yeto] cluster release-node: node {name!r} is not in {inventory}") + return 2 + if objects is None: + objects = store_objects_of(type("Args", (), {"rl_checkpoint_store": store})()) + if objects is None: + say(f"[yeto] cluster release-node: the run store {store!r} has no object API here (s3://, r2://, oss:// " + "or a local directory)") + return 2 + if leases is None: + leases = release_leases_of(nodes, say) + if shared is None and leases is not None: + shared = getattr(leases, "objects", None) + records = NodeRecords(objects, run_id="", log=say, shared=shared) + doc = records.quarantined(name) + if doc is None: + say(f"[yeto] node {name} is not quarantined in {store}") + return 0 + if doc.get("unreadable"): # a broken record: which stops the node owes is not known + say(f"[yeto] node {name}: its quarantine record is unreadable ({doc.get('reason')}): the stops it still owes " + "cannot be known") + if not force: + say(f"[yeto] node {name} stays quarantined: check it by hand for containers or processes of the run " + "(yeto--*), then release it with --force") + return 1 + say(f"[yeto] WARN: --force: node {name} is released without running any owed stop") + doc = {**doc, "owed": []} + owed = list(doc.get("owed") or ()) + if not doc.get("unreadable"): + say(f"[yeto] node {name}: quarantined by island {doc.get('island')} of run {doc.get('run')}: " + f"{doc.get('reason')}") + for row in owed: + say(f"[yeto] owes the stop of {row.get('island')} incarnation {row.get('incarnation')} (rank " + f"{row.get('rank')}" + (f", container {row['container']}" if row.get("container") else "") + ")") + if dry_run: + say(f"[yeto] dry run: would {'skip the health check of' if force else 'check'} {name}, run {len(owed)} " + f"stop(s) and remove {NODES_DIR}/{name}/{QUARANTINE_NAME}") + say(f"[yeto] would remove {records.key(name, QUARANTINE_NAME)} in the run store {store}" + + (f" and {records.shared_key(name)} in the lease store {getattr(leases, 'store_uri', '')}".rstrip() + if records.shared is not None else "")) + say(f"[yeto] {_lease_plan(records, node, doc, leases)}") + return 0 + if ssh is None: + from .ssh_trainer_island import SshOps # noqa: PLC0415 + + ssh = SshOps() + if force: + say(f"[yeto] WARN: --force: node {name} is released without its health check; an island may pick a " + "broken node") + else: + healthy, why = node_check(node, ssh, multi=len(island_nodes(nodes, "trainer")) > 1) + if not healthy: + say(f"[yeto] node {name} stays quarantined: {why} (--force releases it without the check)") + return 1 + say(f"[yeto] node {name}: {why}") + probe = None + if leases is not None: + from .node_lease import ssh_probe # noqa: PLC0415 + + probe = ssh_probe(lambda n, script: ssh.run(n, script, timeout=120.0)) + ok, message = release_node(records, node, ssh, kill_grace_s=kill_grace_s, leases=leases, probe=probe) + say(f"[yeto] {message}" if ok else f"[yeto] node {name} stays quarantined: {message}") + return 0 if ok else 1 + + +# -- the resume point ------------------------------------------------------------------- +def resume_keys(args: Any = None, island: int | None = None, num_islands: int | None = None) -> tuple[str, str]: + """Where island ``island`` (its index among the launch's islands) keeps its trainer's + newest checkpoint in the run store: ``(round cut LATEST, release LATEST.json)``. A + synced island with round cuts writes them under ``island-cuts/island/`` + (``--rl-island-cut-store``; the learner id is ``sample_roles.island_learner``'s, e.g. + ``--rl-fleet-learner-id`` of a per-island launch, not the index); a trainer whose + samplers follow it releases to its ``trainer/policy-releases/`` + (``sample_roles.island_substore``). ``island`` None: the store's top (one trainer).""" + from yeto.rl.engine.resume import LATEST # noqa: PLC0415 + from yeto.rl.quant.schemes import RELEASE_DIR # noqa: PLC0415 + + cut, release = LATEST, f"{RELEASE_DIR}/LATEST.json" + if args is None or island is None: + return cut, release + from yeto.rl.engine import sample_roles # noqa: PLC0415 + from yeto.rl.engine.cut_interval import island_cut_store_for # noqa: PLC0415 + + from .rl_ports import island_cuts_requested # noqa: PLC0415 + + islands = int(num_islands or int(island) + 1) + if island_cuts_requested(args): + try: + learners = sample_roles.syncer_learner_count(args, islands) + learner = sample_roles.island_learner(args, int(island), learners, islands)[0] + except Exception: # noqa: BLE001 - a launch without a learner layout: its index + learner = int(island) + cut = f"{island_cut_store_for('island-cuts', int(learner))}/{LATEST}" + try: + substore = sample_roles.island_substore(args, int(island), islands) + except Exception: # noqa: BLE001 - a launch without that layout: the store's top + substore = None + if substore: + release = f"{substore}/{release}" + return cut, release + + +def latest_checkpoint_step(objects: Any, keys: tuple[str, str] | None = None) -> dict[str, Any] | None: + """The newest checkpoint an island's trainer resumes from, as its store holds it at + ``keys`` (:func:`resume_keys`): its round cut (``LATEST`` of :mod:`yeto.rl.engine.resume`: + the cut's rollout) or, without round cuts, its newest BF16 policy release + (``LATEST.json``: its version). None: no checkpoint, or the store does not read.""" + from yeto.rl.engine.resume import _cut_rollout # noqa: PLC0415 + + if objects is None: + return None + cut_key, release_key = keys or resume_keys() + try: + raw = objects.read(cut_key) + if raw is not None: + doc = json.loads(raw) + step = _cut_rollout(str(doc.get("cut_id") or "")) + if step is None and doc.get("next_rollout_id") is not None: + step = int(doc["next_rollout_id"]) - 1 + if step is not None: + return {"source": "round_cut", "step": int(step), "ref": doc.get("cut_id"), "key": cut_key} + raw = objects.read(release_key) + if raw is not None: + doc = json.loads(raw) + if doc.get("version") is not None: + return {"source": "release", "step": int(doc["version"]), "ref": doc.get("path"), "key": release_key} + except Exception: # noqa: BLE001 - unknown, not a reason to stop the replacement + return None + return None + + +# -- one island's state --------------------------------------------------------------------- +@dataclass +class IslandSpares: + """What a resident ``ssh:`` island with spare nodes keeps (``SshIslandOps.add(..., + spares=...)``). ``pool``: the inventory's island and spare nodes (the candidates are the + ones not in the island); ``leases``: ``node_lease.NodeLeases`` of the inventory's + ``lease_store`` (None: no cross-run lease); ``resume_probe``: the island's newest + checkpoint (:func:`latest_checkpoint_step` of its store).""" + + pool: tuple[Node, ...] + records: NodeRecords + job_env: dict[str, str] = field(default_factory=dict) # the island's job env (SshIslandOps.add sets it) + leases: Any = None + resume_probe: Callable[[], dict[str, Any] | None] | None = None + wait_first_s: float = WAIT_FIRST_S + wait_max_s: float = WAIT_MAX_S + max_replacements: int = MAX_REPLACEMENTS + window_s: float = REPLACEMENT_WINDOW_S + max_wait_s: float = MAX_WAIT_S # --spare-max-wait-s (wall clock: a launcher restart keeps it) + report_every_s: float = WAIT_REPORT_S + # runtime + journal: Path | None = None + lost: dict[int, str] = field(default_factory=dict) # rank -> why it is lost + stream_ended: set[int] = field(default_factory=set) # ranks whose stream ended on its own + unconfirmed: set[int] = field(default_factory=set) # ranks whose stop the release did not confirm + silent: dict[int, int] = field(default_factory=dict) # rank -> failed SSH checks in a row + # (lost node, incarnation) whose own stop was confirmed: that stop is owed no more + stopped: set[tuple[str, int]] = field(default_factory=set) + stop_threads: list[Any] = field(default_factory=list, repr=False) # background stops of lost nodes + waiting: bool = False + limited: bool = False # the replacement limit was reported + wait_s: float = 0.0 + next_check: float = 0.0 + wait_reason: str | None = None + wait_since: float | None = None # wall clock of the wait's start (kept in the journal) + reported_at: float = 0.0 # wall clock of the last island_waiting_spare + replacements: list[dict[str, Any]] = field(default_factory=list) + nodes: dict[str, list[str]] = field(default_factory=dict) # incarnation -> node names + events: list[dict[str, Any]] = field(default_factory=list) + # the events' own lock: the fleet controller drains them each poll while a relaunch (its + # spare's preflight, a docker pull) may hold SshIslandOps' lock for minutes + events_lock: Any = field(default_factory=threading.Lock, repr=False) + # the owed stops' lock: the background stop of a lost node and the release that records + # what it still owes agree on it (a confirmed stop owes nothing, never a row left open) + owed_lock: Any = field(default_factory=threading.Lock, repr=False) + + def by_name(self) -> dict[str, Node]: + return {n.name: n for n in self.pool} + + # -- the journal (next to the island's jobs journal) + def load(self, path: Path) -> None: + self.journal = Path(path) + try: + doc = json.loads(self.journal.read_text(encoding="utf-8")) + except (OSError, ValueError): + return + self.nodes = {str(k): [str(n) for n in v] for k, v in dict(doc.get("nodes") or {}).items()} + self.replacements = [dict(r) for r in doc.get("replacements") or () if isinstance(r, dict)] + since = doc.get("waiting_since") + self.wait_since = None if since is None else float(since) + + def save(self) -> None: + if self.journal is None: + return + self.journal.parent.mkdir(parents=True, exist_ok=True) + tmp = self.journal.with_suffix(".tmp") + doc = {"nodes": self.nodes, "replacements": self.replacements, + **({"waiting_since": self.wait_since} if self.wait_since is not None else {})} + tmp.write_text(json.dumps(doc, indent=1, sort_keys=True), encoding="utf-8") + tmp.replace(self.journal) + + def nodes_of(self, incarnation: int | None) -> list[str] | None: + """The node names incarnation ``incarnation`` runs on (None: the newest recorded).""" + if not self.nodes: + return None + if incarnation is None: + return self.nodes[max(self.nodes, key=int)] + return self.nodes.get(str(int(incarnation))) + + def record_nodes(self, incarnation: int, names: Sequence[str]) -> None: + self.nodes[str(int(incarnation))] = list(names) + self.save() + + # -- limits and waiting + def recent(self, now_wall: float) -> list[dict[str, Any]]: + return [r for r in self.replacements if now_wall - float(r.get("at") or 0.0) < self.window_s] + + def limit_reached(self, now_wall: float) -> bool: + return len(self.recent(now_wall)) >= int(self.max_replacements) + + def wait(self, now: float, reason: str, *, wall: float | None = None) -> bool: + """Wait for a spare (the next check after the backoff); True when the wait is new or + its reason changed (worth an event). ``wall``: the wall clock (the wait's start is + kept in the journal, so a restarted launcher keeps its ``max_wait_s``).""" + self.wait_s = self.wait_first_s if not self.waiting else min(self.wait_max_s, max(self.wait_s, 1.0) * 2) + self.next_check = now + self.wait_s + fresh = not self.waiting or reason != self.wait_reason + self.waiting, self.wait_reason = True, reason + if wall is not None and self.wait_since is None: + self.wait_since = float(wall) + self.save() + if fresh and wall is not None: + self.reported_at = float(wall) + return fresh + + def waited_s(self, wall: float) -> float: + return 0.0 if self.wait_since is None else max(0.0, float(wall) - self.wait_since) + + def report_due(self, wall: float) -> bool: + """An hourly ``island_waiting_spare`` is due (True once per ``report_every_s``).""" + if not self.waiting or wall - self.reported_at < self.report_every_s: + return False + self.reported_at = float(wall) + return True + + def done_waiting(self) -> None: + self.waiting, self.wait_s, self.next_check, self.wait_reason = False, 0.0, 0.0, None + if self.wait_since is not None: + self.wait_since = None + self.save() + + def emit(self, kind: str, **fields: Any) -> dict[str, Any]: + event = {"kind": kind, **fields} + with self.events_lock: + self.events.append(event) + return event + + def take_events(self) -> list[dict[str, Any]]: + with self.events_lock: + out, self.events = self.events, [] + return out + + +@dataclass(frozen=True) +class Pick: + node: Node | None + group: str | None + skipped: dict[str, str] + unchecked: tuple[str, ...] = () # candidates left that were not health checked (check them, pick again) + placement: str = "" # why fabric_groups.pick_placement placed no spare (its PlacementError) + + def why_none(self) -> str: + where = f"fabric group {self.group}" if self.group else "the inventory" + detail = "; ".join(f"{name}: {why}" for name, why in sorted(self.skipped.items())) + return (f"{where} has no free healthy spare node" + (f" ({detail})" if detail else "") + + (f"; placement: {self.placement}" if self.placement else "")) + + +def spare_candidates(spares: IslandSpares, island: str, current: Sequence[Node], lost: Iterable[int], *, + chosen: Sequence[Node] = ()) -> tuple[list[Node], str | None, dict[str, str], bool, list[Node]]: + """``(candidates, group, skipped, multi, keep)`` of a pick for the ``lost`` ranks of ``current``: + the pool's nodes that are neither the island's other nodes nor ``chosen`` (spares picked + for other lost ranks), in the island's fabric group (a multi-node island never takes a + node of the reserved group ``unavailable``). ``skipped``: node name -> why it is out: + another fabric group (not a candidate), or quarantined (in this run or, with a + ``lease_store``, any run), held by another island of the run, leased by another run (a + candidate, in ``pick_placement``'s ``excluded`` with that reason). ``keep``: the + island's nodes that stay (``required``). No SSH.""" + lost = sorted(set(lost)) + keep = [n for r, n in enumerate(current) if r not in lost] + list(chosen) + group = (next((fabric_group(n) for n in keep if fabric_group(n)), None) + or next((fabric_group(current[r]) for r in lost if fabric_group(current[r])), None)) + grouped = any(fabric_group(n) for n in (*current, *spares.pool)) + multi = len(current) > 1 + taken = {n.name for n in keep} + skipped: dict[str, str] = {} + candidates: list[Node] = [] + for node in sorted(spares.pool, key=lambda n: n.name): + if node.name in taken: + continue + if multi and _unavailable(node): + skipped[node.name] = f"fabric group {UNAVAILABLE_GROUP} (never in a multi-node island)" + elif multi and grouped and fabric_group(node) != group: + skipped[node.name] = f"fabric group {fabric_group(node) or 'none'} (the island's is {group or 'none'})" + else: + candidates.append(node) + if (record := spares.records.own_quarantine(node.name)) is not None: + skipped[node.name] = f"quarantined ({str(record.get('reason') or '')[:120]})" + elif (record := spares.records.shared_quarantined(node.name)) is not None: # another run's + skipped[node.name] = (f"quarantined: {describe(node.name, record)}; once fixed, " + f"{release_how(node.name)}") + elif (held := spares.records.holder(node.name)) is not None and held != island: + skipped[node.name] = f"held by island {held}" + elif spares.leases is not None and (holder := spares.leases.holder(node)) is not None \ + and holder != lease_holder_id(spares.leases): + skipped[node.name] = f"leased by run {holder}" + return candidates, group, skipped, multi, keep + + +def _place(spares: IslandSpares, candidates: Sequence[Node], keep: Sequence[Node], + excluded: Mapping[str, str]) -> tuple[Node | None, str]: + """The spare ``fabric_groups.pick_placement`` adds to the island's nodes that stay + (``required``: the island is never moved to other nodes); ``excluded``: name -> why + (quarantined, held, leased, unhealthy, checked before).""" + names = {n.name for n in candidates} + return _pick_placement(candidates, len(keep) + 1, required=keep, inventory=spares.pool, + excluded={k: v for k, v in excluded.items() if k in names}) + + +def check_candidates(spares: IslandSpares, island: str, current: Sequence[Node], lost: Iterable[int], *, + ops: Any, need: int = 1, known: Iterable[str] = ()) -> dict[str, tuple[bool, str]]: + """The health checks of a pick, run before it (outside ``SshIslandOps``' lock: each is + an SSH call): the candidates in ``fabric_groups.pick_placement`` order, but ``known`` + (checked before), until ``need`` pass. Node name -> ``(ok, why)`` (:func:`node_check`).""" + candidates, _group, skipped, multi, keep = spare_candidates(spares, island, current, lost) + checked: dict[str, tuple[bool, str]] = {} + out = {**skipped, **{k: "health checked before" for k in known}} + passed = 0 + while passed < need: + node, _why = _place(spares, candidates, keep, {**out, **{k: why for k, (_ok, why) in checked.items()}}) + if node is None: + break + checked[node.name] = node_check(node, ops, multi=multi, env=spares.job_env) + passed += bool(checked[node.name][0]) + return checked + + +def pick_spare(spares: IslandSpares, island: str, current: Sequence[Node], lost: Iterable[int], *, + ops: Any = None, chosen: Sequence[Node] = (), + health: Mapping[str, tuple[bool, str]] | None = None) -> Pick: + """A spare for one of the ``lost`` ranks of ``current``: :func:`spare_candidates` (read + again now: a node may have been claimed, quarantined or leased since the checks), then + ``fabric_groups.pick_placement`` (need 1) names the spare, by node name. One whose + health check (``health``: :func:`check_candidates`' results; a node not checked there is + passed over this time; None: checked here over ``ops``), claim or lease fails is + excluded and the pick runs again. A lost node itself is a candidate again once released + from its quarantine. The pick is claimed (and its lease taken) before it is returned; + :func:`unpick` gives it back.""" + candidates, group, skipped, multi, keep = spare_candidates(spares, island, current, lost, chosen=chosen) + unchecked: list[str] = [] + while True: + node, why = _place(spares, candidates, keep, skipped) # every node tried below is in skipped, with why + if node is None: + return Pick(None, group, skipped, tuple(unchecked), placement=why) + skipped[node.name] = "tried" + verdict = node_check(node, ops, multi=multi, env=spares.job_env) if health is None else health.get(node.name) + if verdict is None: + unchecked.append(node.name) + skipped[node.name] = "health not checked yet" + continue + healthy, why = verdict + if not healthy: + skipped[node.name] = why + continue + try: + held = spares.records.claim(node.name, island) + except SpareError as error: + skipped[node.name] = f"not claimed: {error}" + continue + if held is not None: + skipped[node.name] = f"held by island {held}" + continue + if spares.leases is not None: + lease = spares.leases.acquire(node) + if not getattr(lease, "ok", False) or getattr(lease, "blocked", False): + spares.records.unclaim(node.name, island) + skipped[node.name] = (f"lease of run {getattr(lease, 'previous', None) or 'unknown'} not taken over " + "(its run may still run there)" if getattr(lease, "blocked", False) + else f"leased by run {getattr(lease, 'holder', None) or 'unknown'}") + continue + skipped.pop(node.name, None) + with spares.owed_lock: # picked again: a loss of its new incarnation owes its stop again + spares.stopped -= {k for k in spares.stopped if k[0] == node.name} + _close_owed_elsewhere(spares, node, ops) + return Pick(node, group, skipped) + + +def _close_owed_elsewhere(spares: IslandSpares, node: Node, ops: Any) -> None: + """A picked node has no quarantine record (a release-node elsewhere, a ``--force`` over + a broken record, or a run store kept in memory): the stops its open owed ledger rows + name are run on it now, and each row closes (``released elsewhere``) only once its stop + went through, so the node is billed once and nothing of the old incarnation is left.""" + from . import ssh_trainer_ledger # noqa: PLC0415 + + def stopped(row: Any) -> bool: + ok, action, _ = ssh_trainer_ledger.cleanup_release(row, ssh=ops) + if not ok: + spares.records.log(f"[launcher] node {node.name}: {action}; its owed ledger row {row.id} stays open") + return ok + + closed = ssh_trainer_ledger.release_owed_elsewhere(run_id=spares.records.run_id, node=node.name, stop=stopped) + if closed: + spares.records.log(f"[launcher] node {node.name} is picked again with no quarantine record: its owed " + f"stop(s) went through and ledger row(s) {closed} are closed (released elsewhere)") + + +def unpick(spares: IslandSpares, island: str, node: Node) -> None: + """Give a pick back (its start failed): its claim and lease.""" + spares.records.unclaim(node.name, island) + if spares.leases is not None: + try: + spares.leases.release(node) + except Exception: # noqa: BLE001 - the lease runs out on its own + pass + + +def owed_stop(run_id: str, island: str, incarnation: int, rank: int, docker: bool) -> dict[str, Any]: + """The stop a lost node still owes for incarnation ``incarnation`` (run by release_node).""" + from .ssh_trainer_island import container_name # noqa: PLC0415 + + return {"run_id": run_id, "island": island, "incarnation": int(incarnation), "rank": int(rank), + "container": container_name(run_id, island, incarnation, rank) if docker else None} + diff --git a/yeto/launch/node_quarantine.py b/yeto/launch/node_quarantine.py new file mode 100644 index 000000000..de5926c09 --- /dev/null +++ b/yeto/launch/node_quarantine.py @@ -0,0 +1,125 @@ +"""Where a quarantined node is recorded for every run of an inventory. + +A spare-pool island (:mod:`.island_spares`) quarantines a node it lost; with an inventory +``lease_store`` the record is also ``nodes//quarantine.json`` there, next to +:mod:`.node_lease`'s ``nodes//lease/`` tokens and ``nodes//events/`` (never +inside them). Every run's trainer pick leaves such a node out until ``yeto cluster +release-node``. A leaf module: the trainer pick reads it without importing the spares. +""" + +from __future__ import annotations + +import json +from collections.abc import Callable, Iterable, Mapping +from pathlib import Path +from typing import Any + +SPARE_ROLE = "trainer-spare" # an inventory node that may take a lost trainer node's place +JOURNAL_SUFFIX = "-spares.json" # next to a resident island's jobs journal: the nodes of each incarnation +QUARANTINE_NAME = "quarantine.json" +SHARED_NODES_DIR = "nodes" # under the inventory's lease_store +RELEASE_NODE_HINT = "run `yeto cluster release-node `" + + +def latest_spare_nodes(path: Any) -> list[str] | None: + """The nodes the newest incarnation of a resident island with spare nodes runs on, by + its spares journal (``-spares.json``, written before any start of that + incarnation); None without one.""" + try: + doc = json.loads(Path(path).read_text(encoding="utf-8")) + nodes = dict(doc.get("nodes") or {}) + return [str(n) for n in nodes[max(nodes, key=int)]] if nodes else None + except (OSError, ValueError, TypeError, AttributeError): + return None + + +def shared_key(name: str) -> str: + return f"{SHARED_NODES_DIR}/{name}/{QUARANTINE_NAME}" + + +def _listed(shared: Any) -> set[str]: + """The nodes with a quarantine record in the lease store (raises when it does not list).""" + out = set() + for key in shared.list(f"{SHARED_NODES_DIR}/"): # nodes//quarantine.json only + parts = str(key).split("/") + if len(parts) == 3 and parts[0] == SHARED_NODES_DIR and parts[2] == QUARANTINE_NAME: + out.add(parts[1]) + return out + + +def shared_quarantined_names(shared: Any) -> set[str]: + """The nodes quarantined in a lease store (every run's); empty when there is no store + or it does not list (:func:`shared_quarantines` reads each node's record then).""" + if shared is None: + return set() + try: + return _listed(shared) + except Exception: # noqa: BLE001 - see shared_quarantines + return set() + + +def read_record(shared: Any, name: str) -> dict[str, Any] | None: + """Node ``name``'s quarantine record in the lease store (None: none). A record that + cannot be read (the store failed: ``read_error``) or parsed counts as a quarantine: + ``{"unreadable": True, "reason": "quarantine record unreadable: ..."}``.""" + try: + raw = shared.read(shared_key(name)) + except Exception as error: # noqa: BLE001 - unknown is not free + return {"unreadable": True, "read_error": True, + "reason": f"quarantine record unreadable: {type(error).__name__}: {error}"[:300]} + if raw is None: + return None + try: + doc = json.loads(raw) + except ValueError: + doc = None + if not isinstance(doc, dict): + return {"unreadable": True, "reason": "quarantine record unreadable: not a JSON object"} + return doc + + +def shared_quarantines(shared: Any, names: Iterable[str], *, + log: Callable[[str], None] | None = None) -> dict[str, dict[str, Any]]: + """The quarantine records of ``names`` in the lease store (any run's): name -> record. + A record that cannot be read counts as one (:func:`read_record`); when the store does + not list, each node's record is read (a line says so).""" + names = set(names) + if shared is None or not names: + return {} + try: + listed = _listed(shared) & names + except Exception as error: # noqa: BLE001 - each node read below + (log or (lambda m: None))(f"[launcher] WARN: the lease store's quarantine list failed " + f"({type(error).__name__}: {error}); each node's record is read instead") + listed = names + out = {} + for name in sorted(listed): + doc = read_record(shared, name) + if doc is not None: + out[name] = doc + return out + + +def describe(name: str, doc: Mapping[str, Any]) -> str: + """`` by run R island I (reason)`` of a quarantine record.""" + if doc.get("unreadable"): + return f"{name} ({doc.get('reason') or 'quarantine record unreadable'})" + who = f"run {doc.get('run') or '?'} island {doc.get('island') or '?'}" + why = str(doc.get("reason") or "").strip()[:200] + return f"{name} by {who}" + (f" ({why})" if why else "") + + +RELEASE_HOW = " with this inventory and the run store of the run that quarantined it" + + +def release_how(name: str) -> str: + return RELEASE_NODE_HINT.replace("", name) + RELEASE_HOW + + +def quarantine_note(docs: Mapping[str, Mapping[str, Any]]) -> str | None: + """One line for a pick that leaves the nodes of ``docs`` out as quarantined: by which + run and island, why, and how to give each back (None: none).""" + if not docs: + return None + return ("quarantined, left out: " + "; ".join(describe(n, d) for n, d in sorted(docs.items())) + + ". Once a node is fixed, " + RELEASE_NODE_HINT + RELEASE_HOW) diff --git a/yeto/launch/ssh_resident.py b/yeto/launch/ssh_resident.py index 6b70b20b0..ad9696a3b 100644 --- a/yeto/launch/ssh_resident.py +++ b/yeto/launch/ssh_resident.py @@ -51,6 +51,14 @@ are given up; a launcher that ends without a release (``--keep``) leaves them to run out, and a restarted launcher of the run takes them back. +* **spare nodes** (an inventory with ``roles: [trainer-spare]`` nodes, :mod:`.island_spares`): + a lost node (its stream ended and it does not answer over SSH ``unreachable_polls`` + times in a row, or its health turned bad twice) is not waited for: the island is stopped + on its other nodes, a spare of the same fabric group takes the lost node's place and the + next incarnation resumes from the newest checkpoint (``island_node_lost`` / + ``island_node_replaced``); no spare: ``waiting_spare`` with a backoff. Without spare + nodes nothing of the above changes. + Each watch also renews the island's node leases that are due; a node whose lease another run took fails the island at once (that run may start there). @@ -72,7 +80,7 @@ from collections.abc import Callable from dataclasses import dataclass, field from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any from ..config_errors import CONFIG_ERROR_EXIT, CONFIG_ERROR_MARKER, ISLAND_STOP_EXIT, ISLAND_STOP_MARKER from ..hw import node_health @@ -92,6 +100,9 @@ ) from .trainer_island import read_jobs +if TYPE_CHECKING: + from .island_spares import IslandSpares + RESIDENT_DIR = "ssh-islands" # under the run dir UNREACHABLE_POLLS = 3 MAX_REFOLLOWS = 5 @@ -151,6 +162,12 @@ def check(args: Any, specs: Any) -> None: run_image(args, nodes) except SshIslandError as error: raise SystemExit(f"--gpu island {m} ({spec}): {error}") from None + from .island_spares import SpareError, check_spares, spare_nodes # noqa: PLC0415 + + try: + check_spares(nodes, spare_nodes(getattr(args, "rl_node_inventory_nodes", None) or ())) + except SpareError as error: + raise SystemExit(f"--gpu island {m} ({spec}): {error}") from None if code_source(args) is None: raise SystemExit(f"--gpu island {m} ({spec}): the run's code cannot reach its nodes: use an s3:// " "--rl-checkpoint-store with --rl-code-pack auto or git-patch (every node downloads " @@ -179,6 +196,15 @@ class _Island: health_lost: dict[int, list[str]] = field(default_factory=dict) # rank -> reasons (this incarnation) health_events: list[dict[str, Any]] = field(default_factory=list) # for the fleet's event log health_pending: list[tuple[int, list[str], Any]] = field(default_factory=list) # lost nodes, hook not run yet + spares: Any = None # island_spares.IslandSpares: an inventory with spare nodes (None: none) + rank_gen: dict[int, int] = field(default_factory=dict) # rank -> how often a spare took its place + # id(reading) -> (node, rank_gen) when a health reading turned lost: the hook ignores a stale one + health_stamps: dict[int, tuple[str, int]] = field(default_factory=dict) + owed_retries: dict[str, Any] = field(default_factory=dict) # node -> its owed-stop retry thread + on_line: Any = None # node 0's line sink of every incarnation + + +_RECHECK = object() # _replace: a candidate is not health checked yet (check it outside the lock) class SshIslandOps: @@ -194,7 +220,7 @@ def __init__(self, *, run_id: str, journal_dir: Path, events_dir: Path | None = kill_grace_s: int = KILL_GRACE_S, clock: Callable[[], float] = time.monotonic, health_every_s: float = HEALTH_EVERY_S, worker_exit_grace_s: float = WORKER_EXIT_GRACE_S, unreachable_polls: int = UNREACHABLE_POLLS, max_refollows: int = MAX_REFOLLOWS, - log: Callable[[str], None] | None = None) -> None: + log: Callable[[str], None] | None = None, wall: Callable[[], float] = time.time) -> None: self.run_id = str(run_id) self.journal_dir = Path(journal_dir) self.events_dir = None if events_dir is None else Path(events_dir) @@ -207,8 +233,11 @@ def __init__(self, *, run_id: str, journal_dir: Path, events_dir: Path | None = self.unreachable_polls = int(unreachable_polls) self.max_refollows = int(max_refollows) self.log = log or (lambda m: print(m, file=sys.stderr, flush=True)) + self.wall = wall # wall clock of the replacement limit (a launcher restart keeps the count) self.islands: dict[str, _Island] = {} - self._lock = threading.Lock() + # reentrant: the node health watch may call _node_health_lost from inside job_status's + # watch or from outside it; either way the hook takes this lock itself + self._lock = threading.RLock() self.reattached: set[str] = set() # islands whose start followed a running incarnation # -- registry ------------------------------------------------------------------- @@ -218,26 +247,56 @@ def owns(self, name: str) -> bool: def jobs_path(self, name: str) -> Path: return self.journal_dir / f"{name}-jobs.json" - def add(self, name: str, spec: SshTrainerSpec) -> None: - """Register island ``name`` (no SSH yet).""" + def add(self, name: str, spec: SshTrainerSpec, *, spares: IslandSpares | None = None) -> None: + """Register island ``name`` (no SSH yet). ``spares``: the inventory's spare nodes + (:mod:`.island_spares`); the island's journal of them names the nodes its newest + incarnation runs on (a restarted launcher follows it there).""" if name in self.islands: raise SshIslandError(f"ssh: island {name} is registered twice") sink = self.sink_for(name) if self.sink_for is not None else None - rec = _Island(name, spec, None) # type: ignore[arg-type] + if spares is not None: + from .island_spares import JOURNAL_SUFFIX # noqa: PLC0415 + + spares.load(self.journal_dir / f"{name}{JOURNAL_SUFFIX}") + spec = self._spec_on(spec, spares, spares.nodes_of(None)) + spares.job_env = dict(getattr(spec, "env", None) or {}) # the spares' checks read its NCCL_IB_HCA + if spares.leases is None: # the island's own node leases (inventory lease_store) + spares.leases = getattr(spec, "leases", None) + if spares.records.shared is None and spares.leases is not None: + spares.records.shared = getattr(spares.leases, "objects", None) # the shared quarantine + rec = _Island(name, spec, None, spares=spares) # type: ignore[arg-type] def on_line(line: str) -> None: rec.lines.append(line) if sink is not None: sink(line) - # node_wait_s=0: a start finds an unreachable node at once and names it; the - # fleet controller retries the relaunch every poll (a wait here would hold it) - rec.islands = SshTrainerIslands(spec, name=name, jobs_path=self.jobs_path(name), ops=self.ops, - events_dir=self.events_dir, kill_grace_s=self.kill_grace_s, - scheduled=False, tape=False, on_line=on_line, node_wait_s=0.0) + rec.on_line = on_line + rec.islands = self._islands_for(rec, spec) rec.health = self._health_watches(spec) self.islands[name] = rec + def _islands_for(self, rec: _Island, spec: SshTrainerSpec) -> SshTrainerIslands: + # node_wait_s=0: a start finds an unreachable node at once and names it; the + # fleet controller retries the relaunch every poll (a wait here would hold it) + return SshTrainerIslands(spec, name=rec.name, jobs_path=self.jobs_path(rec.name), ops=self.ops, + events_dir=self.events_dir, kill_grace_s=self.kill_grace_s, + scheduled=False, tape=False, on_line=rec.on_line, node_wait_s=0.0) + + @staticmethod + def _spec_on(spec: SshTrainerSpec, spares: Any, names: list[str] | None) -> SshTrainerSpec: + """``spec`` on the nodes ``names`` of the spares' pool (None: unchanged).""" + if not names or names == [n.name for n in spec.nodes]: + return spec + pool = spares.by_name() + missing = [n for n in names if n not in pool] + if missing or len(names) != len(spec.nodes): + raise SshIslandError(f"the island's spare journal names nodes {names}; the inventory has no " + f"{missing or 'such set of'} node(s): restore those inventory entries") + import dataclasses # noqa: PLC0415 + + return dataclasses.replace(spec, nodes=tuple(pool[n] for n in names)) + def _health_watches(self, spec: SshTrainerSpec) -> dict[int, Any]: """One :class:`~yeto.hw.node_health.HealthWatch` per rank (a family without a checker, or ``health_every_s`` 0: none). A multi-node island's job ports are its ``NCCL_IB_HCA``.""" @@ -264,9 +323,15 @@ def start(self, name: str) -> int: """Start (or reattach to) island ``name``; returns the job id (its incarnation).""" rec = self.islands[name] self._take_lock(rec) + lost = self._quarantined_ranks(rec) # spare nodes: a node lost earlier (empty without spares) + self._claim_nodes(rec, skip=lost) + self._keep_quarantined_leases(rec) + self._release_stale_leases(rec) jobs = read_jobs(self.jobs_path(name)) - if not jobs: + if not jobs and not lost: return self._launch(rec, 0) + if lost: + return self._start_without(rec, lost, max(int(k) for k in jobs) if jobs else None) last = max(int(k) for k in jobs) states = [rec.islands.node_state(last, rank) for rank in range(len(rec.spec.nodes))] silent = [rec.spec.nodes[r].name for r, st in enumerate(states) if st is None] @@ -322,10 +387,148 @@ def _reset(self, rec: _Island, job: Any, incarnation: int) -> int: return int(incarnation) def _launch(self, rec: _Island, incarnation: int) -> int: + if rec.spares is not None: # the nodes of the incarnation, before any start + rec.spares.record_nodes(incarnation, [n.name for n in rec.spec.nodes]) job = rec.islands.launch(incarnation, None) # journal and ledger row before any node starts return self._reset(rec, job, incarnation) + def _claim_nodes(self, rec: _Island, *, skip: Any = ()) -> None: + """An island with spare nodes holds its nodes in the run store (``island_spares`` + claims): no other island of the run picks them as its spare. ``skip``: ranks not + claimed (quarantined nodes).""" + if rec.spares is None: + return + from .island_spares import SpareError # noqa: PLC0415 + + for rank, node in enumerate(rec.spec.nodes): + if rank in skip: + continue + try: + held = rec.spares.records.claim(node.name, rec.name) + except SpareError as error: + raise SshIslandError(f"ssh: island {rec.name}: {error}") from None + if held is not None: + raise SshIslandError(f"ssh: island {rec.name}: node {node.name} is held by island {held} of this " + "run (fleet/nodes//claim.json); two islands cannot share a node") + + def _keep_quarantined_leases(self, rec: _Island) -> None: + """A start of an island with spare nodes and node leases: every quarantined node of + the inventory whose lease this run holds (a restarted launcher took the island's + recorded nodes back) keeps it out of the renewals until release-node + (:meth:`_mark_lost`). The island's own start takes its current nodes' leases + (``SshTrainerIslands._hold_leases``).""" + sp = rec.spares + leases = None if sp is None else sp.leases + if leases is None or not hasattr(leases, "keep_all"): + return + mine = set(leases.held()) + quarantined = [n for n in sp.pool if n.name in mine and sp.records.own_quarantine(n.name) is not None] + if quarantined: + leases.keep_all(nodes=quarantined) + + def _hold_current_leases(self, rec: _Island) -> None: + """A reattach with node leases: the island's current nodes (a spare among them) are + this run's (``_hold_leases``: another run's lease refuses it).""" + if rec.spec.leases is not None: + rec.islands._hold_leases() # noqa: SLF001 - the island's own lease step + + def _release_stale_leases(self, rec: _Island) -> None: + """Every start (a first launch, a start without a quarantined node, a reattach): a + node the leases picked for the island but that it no longer runs on (a lost node, + released, named by an older lease record) is given back, unless it is quarantined + (its lease stays kept until release-node) or another island of the run holds it + (its claim, or its own pick); the record then names the island's nodes.""" + leases = rec.spec.leases + if leases is None: + return + sp = rec.spares + picks = getattr(leases, "picks", None) + if sp is None or not isinstance(picks, dict): + return + current = [n.name for n in rec.spec.nodes] + others = {n for k, v in picks.items() if k != rec.name for n in v} + mine = set(leases.held()) + by_name = {n.name: n for n in sp.pool} + for name in sorted(set(picks.get(rec.name, ())) - set(current) - others): + held = sp.records.holder(name) + if name not in mine or name not in by_name or sp.records.quarantined(name) is not None \ + or held not in (None, rec.name): + continue + leases.release(by_name[name]) + self.log(f"[launcher] {rec.name}: node {name} is no longer one of its nodes (a spare took its place); " + "its lease is given back") + self._record_nodes(rec) + + def _record_nodes(self, rec: _Island) -> None: + """The island's current nodes into the run's lease record and the leases' picks (a + restarted launcher leases these, not a node a spare replaced).""" + leases = rec.spec.leases + if leases is None: + return + names = [n.name for n in rec.spec.nodes] + picks = getattr(leases, "picks", None) + if isinstance(picks, dict): + old = set(picks.get(rec.name, ())) + others = {n for k, v in picks.items() if k != rec.name for n in v} + picks[rec.name] = names + assigned = getattr(leases, "assigned", None) + if isinstance(assigned, set): # this island's old nodes only; another island's stay assigned + assigned -= old - set(names) - others + assigned |= set(names) + from .ssh_trainer_island import record_island_nodes # noqa: PLC0415 + + try: + record_island_nodes(rec.spec.run_id, rec.name, rec.spec.nodes) + except OSError as error: + self.log(f"[launcher] WARN: {rec.name}: its nodes {names} are not in the lease record ({error})") + + def _quarantined_ranks(self, rec: _Island) -> dict[int, str]: + """Ranks whose node is quarantined (lost earlier: by this run, or by another run in + the inventory's ``lease_store``): rank -> why. Empty without spare nodes.""" + if rec.spares is None: + return {} + out = {} + for rank, node in enumerate(rec.spec.nodes): + doc = rec.spares.records.quarantined(node.name) + if doc is not None and doc.get("read_error"): # the store did not answer: no loss of a running node + self.log(f"[launcher] WARN: {rec.name}: the quarantine record of {node.name} could not be read " + f"({doc.get('reason')}); it is not taken as lost") + continue + if doc is not None: + out[rank] = f"rank {rank} ({node.name}) is quarantined: {str(doc.get('reason') or '')[:300]}" + return out + + def _start_without(self, rec: _Island, lost: dict[int, str], last: int | None) -> int: + """A start (a restarted launcher, or a node another run quarantined) while nodes of + the island are quarantined: they are lost; the newest incarnation is released on + the other nodes and the next one starts with spares in their places. No spare yet: + the island reads as failed (its waiting continues in the fleet's recovery).""" + sp = rec.spares + names = [rec.spec.nodes[r].name for r in sorted(lost)] + self.log(f"[launcher] {rec.name}: node(s) {names} are quarantined; they are not started on " + f"({'; '.join(lost[r] for r in sorted(lost))})") + if last is not None: + live = [r for r in range(len(rec.spec.nodes)) if r not in lost] + silent = [rec.spec.nodes[r].name for r in live if rec.islands.node_state(last, r) is None] + if silent: + raise SshIslandError( + f"ssh: island {rec.name}: incarnation {last} is recorded in {self.jobs_path(rec.name)}, and " + f"nodes {silent} do not answer; refusing to start another copy on the same cards") + if not self._release(rec, last, skip=frozenset(names)): + raise SshIslandError(f"ssh: island {rec.name}: incarnation {last} could not be confirmed stopped; " + "refusing to start another copy on the same cards") + for rank, why in lost.items(): + sp.lost.setdefault(rank, why) + rec.incarnation = last + job_id = self._replace_checked(rec) + if job_id is not None: + return job_id + rec.verdict, rec.reason = "FAILED", (f"node(s) {names} quarantined; waiting for a spare node " + f"({sp.wait_reason})") + return -1 if last is None else last + def _attach(self, rec: _Island, incarnation: int) -> int: + self._hold_current_leases(rec) job = rec.islands.attach(incarnation) # its ledger row is open since its start self.reattached.add(rec.name) return self._reset(rec, job, incarnation) @@ -348,8 +551,11 @@ def cluster_up(self, name: str) -> bool: def relaunch(self, task: Any, name: str) -> int | None: """Release the failed incarnation (verified) and start the next one; None when - the release is not confirmed or the start failed (the controller retries).""" + the release is not confirmed or the start failed (the controller retries). With + spare nodes a lost node is replaced (:meth:`_relaunch_with_spares`).""" rec = self.islands[name] + if rec.spares is not None: + return self._relaunch_with_spares(rec) # takes the lock itself (not over the health checks) with self._lock: if rec.incarnation is not None and not self._release(rec, rec.incarnation): self.log(f"[launcher] {name}: incarnation {rec.incarnation} not confirmed stopped; " @@ -371,8 +577,13 @@ def down(self, name: str) -> bool: if rec.incarnation is None: # never started: nothing runs on its nodes rec.islands.release_leases() return True + self._join_owed_retries(rec) with self._lock: - ok = self._release(rec, rec.incarnation) + # a lost node is not waited for: it owes its stop (its own ledger row, release-node) + ok = self._release(rec, rec.incarnation, skip=self._lost_names(rec)) + if ok and rec.spares is not None: # its nodes are free for another island of the run + for node in rec.spec.nodes: + rec.spares.records.unclaim(node.name, rec.name) if ok: rec.islands.release_leases() if ok and rec.lock is not None: @@ -384,6 +595,7 @@ def close(self) -> None: """The launcher stops supervising (its end, ``--keep`` included): end its streams and give up the locks; the nodes are not touched.""" for rec in self.islands.values(): + self._join_owed_retries(rec) if rec.job is not None: for proc in rec.job.procs: if proc.poll() is None: @@ -465,7 +677,7 @@ def _node_event(self, rec: _Island, rank: int, state: NodeState | None, *, strea rec.unreachable[rank] = rec.unreachable.get(rank, 0) + 1 if rec.unreachable[rank] >= self.unreachable_polls: self._fail(rec, f"rank {rank} ({node}) does not answer over SSH " - f"({rec.unreachable[rank]} checks in a row)") + f"({rec.unreachable[rank]} checks in a row)", silent_rank=rank) return rec.unreachable[rank] = 0 if state.running: @@ -503,23 +715,9 @@ def _health_reading(self, rec: _Island, rank: int, reading: Any) -> None: self.log(f"[launcher] {rec.name}: {reading.event}: rank {rank} ({node}) {reading.verdict}: " f"{'; '.join(reading.result.reasons) or '-'}") if reading.event == node_health.EVENT_LOST: # it just turned lost: the hook runs once, after the lock + rec.health_stamps[id(reading)] = (node, rec.rank_gen.get(rank, 0)) rec.health_pending.append((rank, reading.result.job_reasons(len(rec.spec.nodes) > 1), reading)) - def _node_health_lost(self, rec: _Island, rank: int, reasons: list[str], reading: Any) -> None: - """Node ``rank``'s health turned lost (two bad checks in a row): called once per turn, by - :meth:`job_status` after it released the ops' lock. ``reading``: the - :class:`~yeto.hw.node_health.Reading` (its result's facts, the node's record with its - notes: ``rec.health[rank].record()``). The default: as for a node that stops - answering, the island fails at once and every node is released; the fleet's recovery - relaunches it (the unified table reads it as a lost node).""" - node = rec.spec.nodes[rank].name - with self._lock: - if rec.verdict is not None: # it ended meanwhile - return - rec.health_lost[rank] = list(reasons) - self._fail(rec, f"rank {rank} ({node}) node health bad in {node_health.BAD_CHECKS} checks in a row: " - f"{'; '.join(reasons) or 'lost'}") - def island_health(self, name: str) -> dict[str, Any] | None: """The newest health check of every node of island ``name`` (its record's ``health``); None when its family has no checker or nothing was checked yet.""" @@ -542,13 +740,438 @@ def take_health_events(self, name: str) -> list[dict[str, Any]]: out, rec.health_events = rec.health_events, [] return out - def _fail(self, rec: _Island, reason: str) -> None: + def _fail(self, rec: _Island, reason: str, *, silent_rank: int | None = None) -> None: rec.verdict, rec.reason = "FAILED", reason self.log(f"[launcher] {rec.name}: incarnation {rec.incarnation} FAILED: {reason}; stopping every node") tail = self._node_log_tail(rec, reason) if tail: self.log(tail) - self._release(rec, rec.incarnation) + if rec.spares is None: + self._release(rec, rec.incarnation) + return + # Spare nodes: which ranks' streams (their heartbeat) ended on their own, before the + # release ends the others; a silent rank whose stream ended is lost now. A node whose + # stop the release does not confirm keeps its stream and is checked at the relaunch. + sp = rec.spares + sp.stream_ended = {r for r, p in enumerate(rec.job.procs) if p.poll() is not None} if rec.job else set() + # the watch's checks without an answer count on only for a rank whose stream ended; + # a node with an open stream whose stop is not confirmed counts from the relaunch on + sp.silent = {r: c for r, c in rec.unreachable.items() if c and r in sp.stream_ended} + if silent_rank is not None and silent_rank in sp.stream_ended: + self._mark_lost(rec, silent_rank, f"{reason}; its stream ended") + self._release(rec, rec.incarnation, skip=self._lost_names(rec)) + + # -- spare nodes (island_spares) --------------------------------------------------- + def _node_health_lost(self, rec: _Island, rank: int, reasons: list[str], reading: Any) -> None: + """Rank ``rank``'s node turned lost (``node_health``: bad twice in a row; called once, + by ``job_status`` after it let go of the ops lock). ``reasons``: the check's reasons + for the island's job; ``reading``: the ``node_health.Reading`` that judged it (a + reading taken of another node than the rank's current one, or before a spare took the + rank's place, is ignored: :meth:`_health_reading` stamps it). The island fails; with spare nodes the node is lost (replaced at the + relaunch), else the relaunch runs on the same nodes as for any failure. It takes the + ops lock itself (reentrant: safe from inside the watch too) and adds nothing when the + node is already lost or the island already failed.""" + with self._lock: + if not 0 <= int(rank) < len(rec.spec.nodes) or (rec.spares is not None and rank in rec.spares.lost): + return + if rec.spares is None and rec.verdict is not None: # it ended meanwhile (as without spares on main) + return + node = rec.spec.nodes[rank].name + stamp = rec.health_stamps.get(id(reading)) + if stamp is not None and (stamp[0] != node or stamp[1] != rec.rank_gen.get(rank, 0)): + self.log(f"[launcher] {rec.name}: a health loss of {stamp[0]} for rank {rank} ignored (a spare " + f"took rank {rank}'s place since; it is {node} now)") + return # stale (again, if asked again) + rec.health_stamps.pop(id(reading), None) + reason = (f"rank {rank} ({node}) node health bad in {node_health.BAD_CHECKS} checks in a row: " + f"{'; '.join(reasons) or 'lost'}") + notes = self._health_notes(rec, rank) + if notes: + reason = f"{reason}; notes: {'; '.join(notes)}"[:500] + rec.health_lost[rank] = list(reasons) # the unified table reads it as a lost node + if rec.spares is not None: + self._mark_lost(rec, rank, reason, answers=True) + if rec.verdict is None: + self._fail(rec, reason) + + @staticmethod + def _health_notes(rec: _Island, rank: int) -> list[str]: + """The notes of the node's health record (``rec.health[rank].record()``), if any.""" + try: + record = rec.health[rank].record() # type: ignore[attr-defined] + except Exception: # noqa: BLE001 - no health record: no notes + return [] + return [str(n) for n in (record or {}).get("notes") or ()] + + def _lost_names(self, rec: _Island) -> frozenset[str]: + sp = rec.spares + return frozenset(rec.spec.nodes[r].name for r in sp.lost) if sp is not None else frozenset() + + def _mark_lost(self, rec: _Island, rank: int, reason: str, *, answers: bool = False) -> None: + """Rank ``rank``'s node is lost: quarantined (with the stop it owes), its claim given + up, its stream ended, ``island_node_lost`` written. ``answers``: it still answers over + SSH (a health loss), so it is stopped now in the background, not waited for; once that + stop is confirmed it owes nothing (:meth:`_stop_lost`).""" + from .island_spares import NODE_LOST, RELEASE_NODE_HINT, owed_stop # noqa: PLC0415 + + sp = rec.spares + if rank in sp.lost: + return + sp.lost[rank] = reason + node = rec.spec.nodes[rank] + inc = rec.incarnation + owed = [] if inc is None else [owed_stop(self.run_id, rec.name, inc, rank, rec.spec.docker)] + from .island_spares import lease_holder_id # noqa: PLC0415 + + holder = lease_holder_id(sp.leases) if sp.leases is not None else None + sp.records.quarantine(node.name, island=rec.name, reason=reason, owed=owed, lease_holder=holder) + sp.records.unclaim(node.name, rec.name) + keep = getattr(sp.leases, "keep_all", None) + if keep is not None: # its cross-run lease is held (out of the renewals) until release-node + try: + keep(nodes=[node]) + except Exception as error: # noqa: BLE001 - the quarantine still keeps this run's islands off it + self.log(f"[launcher] WARN: {rec.name}: the lease of lost node {node.name} not kept ({error})") + sp.emit(NODE_LOST, node=node.name, rank=int(rank), incarnation=inc, reason=reason[:500]) + self.log(f"[launcher] CRITICAL: {rec.name}: node {node.name} (rank {rank}) is lost: {reason}; it is " + "quarantined and the island is stopped on its other nodes (the lost node is not waited for); " + f"to give it back once fixed, {RELEASE_NODE_HINT.replace('', node.name)}") + if rec.job is not None and inc == rec.job.incarnation and rank < len(rec.job.procs): + proc = rec.job.procs[rank] + if proc.poll() is None: + proc.terminate() + if answers and inc is not None: + thread = threading.Thread(target=self._stop_lost, args=(rec, rank, node, int(inc)), daemon=True, + name=f"{rec.name}-i{inc}-stop-{node.name}") + sp.stop_threads.append(thread) + thread.start() + + def _stop_lost(self, rec: _Island, rank: int, node: Any, inc: int) -> None: + """The background stop of a lost node that still answers (no ops lock): confirmed, + it owes nothing (its quarantine record and ledger row say so); else it stays owed.""" + container = container_name(rec.spec.run_id, rec.name, inc, rank) if rec.spec.docker else None + self._run_owed_stop(rec, node, inc, container, what="lost node") + + def _still_owed(self, rec: _Island, node: Any, inc: int) -> bool: + """The node's quarantine record (read now) still lists its stop of ``inc`` (a + release-node may have run it, and removed the record, since).""" + doc = rec.spares.records.own_quarantine(node.name) + return any(str(o.get("island")) == rec.name and int(o.get("incarnation", -1)) == int(inc) + for o in (doc or {}).get("owed") or ()) + + def _run_owed_stop(self, rec: _Island, node: Any, inc: int, container: str | None, *, what: str) -> bool: + """One owed stop of ``node`` (no ops lock); True once it went through. The record is + read again before the stop (nothing to do once it is gone); a confirmed stop is + settled (:meth:`~.island_spares.NodeRecords.settle`, a marker, never the record + itself) and its owed ledger row closed, even when the marker cannot be written.""" + from . import island_spares as isp # noqa: PLC0415 + from . import ssh_trainer_ledger # noqa: PLC0415 + + sp = rec.spares + try: + if not self._still_owed(rec, node, inc): + return False + except Exception as error: # noqa: BLE001 - not read: tried at the next check + self.log(f"[launcher] {rec.name}: the quarantine record of {node.name} not read ({error})") + return False + script = isp.owed_kill_script(rec.spec.run_id, rec.name, inc, self.kill_grace_s, container) + try: + done = self.ops.run(node, script, timeout=self.kill_grace_s + 60.0) + except Exception as error: # noqa: BLE001 - owed in its quarantine record + self.log(f"[launcher] {rec.name}: stop of {what} {node.name} failed ({error}); it stays owed") + return False + if done.returncode != 0: + self.log(f"[launcher] {rec.name}: stop of {what} {node.name} ended rc {done.returncode}; it stays owed") + return False + with sp.owed_lock: # the release that records owed stops reads this under the same lock + sp.stopped.add((node.name, int(inc))) # the release owes it no row, even if the marker below fails + try: + sp.records.settle(node.name, run_id=self.run_id, island=rec.name, incarnation=inc) + except Exception as error: # noqa: BLE001 - its record still lists the stop (release-node runs it again) + self.log(f"[launcher] WARN: {rec.name}: the stop of {node.name} is not marked settled ({error})") + finally: + ssh_trainer_ledger.release_owed(run_id=rec.spec.run_id, island=rec.name, incarnation=inc, + node=node.name) + self.log(f"[launcher] {rec.name}: {what} {node.name} confirmed its stop of incarnation {inc}; it owes " + "nothing for it (it stays quarantined)") + return True + + def _retry_owed_stops(self, rec: _Island) -> None: + """At each check of a waiting island: every node this island quarantined that still + owes a stop of this run gets it tried again, in the background (no ops lock); a stop + that goes through settles it (it stays quarantined).""" + sp = rec.spares + for node in sp.pool: + doc = sp.records.own_quarantine(node.name) + rows = [dict(o) for o in (doc or {}).get("owed") or () + if str(o.get("island")) == rec.name and str(o.get("run_id") or self.run_id) == self.run_id] + running = rec.owed_retries.get(node.name) + if not rows or (running is not None and running.is_alive()): + continue + thread = threading.Thread(target=self._stop_owed, args=(rec, node, rows), daemon=True, + name=f"{rec.name}-owed-{node.name}") + rec.owed_retries[node.name] = thread + sp.stop_threads.append(thread) + thread.start() + + def _stop_owed(self, rec: _Island, node: Any, rows: list[dict[str, Any]]) -> None: + """The owed stops of ``rows`` on ``node`` (:meth:`_retry_owed_stops`), each only while + the node's record still lists it.""" + for row in rows: + if not self._run_owed_stop(rec, node, int(row["incarnation"]), row.get("container") or None, + what="quarantined node"): + return + + def _join_owed_retries(self, rec: _Island, timeout: float = 5.0) -> None: + """The island goes down or the launcher closes: its owed-stop retries get a short + while to finish; finished threads are dropped.""" + sp = rec.spares + if sp is None: + return + end = time.monotonic() + timeout + for name, thread in list(rec.owed_retries.items()): + thread.join(max(0.0, end - time.monotonic())) + if not thread.is_alive(): + rec.owed_retries.pop(name, None) + sp.stop_threads[:] = [t for t in sp.stop_threads if t.is_alive()] + + def _probe_silent(self, rec: _Island) -> list[int]: + """Ranks whose stop the release did not confirm, or whose stream ended when the island + failed, and that do not answer over SSH now (not lost yet); one answer more or less + each relaunch poll, lost at ``unreachable_polls`` in a row.""" + sp = rec.spares + silent = [] + for rank in sorted((sp.stream_ended | sp.unconfirmed) - set(sp.lost)): + node = rec.spec.nodes[rank] + try: + answered = self.ops.run(node, "true", timeout=60.0).returncode == 0 + except Exception: # noqa: BLE001 - a timeout is no answer + answered = False + if answered: + sp.silent[rank] = 0 + continue + sp.silent[rank] = sp.silent.get(rank, 0) + 1 + ended = rank in sp.stream_ended or self._stream_ended(rec, rank) + # a node whose stop is not confirmed and whose old stream still runs (sshd refusing new + # sessions while the old connection lives) is lost only after twice as many checks + limit = self.unreachable_polls if ended else 2 * self.unreachable_polls + if sp.silent[rank] >= limit: + why = "its stream ended" if ended else "its stop was not confirmed, its stream still open," + self._mark_lost(rec, rank, f"rank {rank} ({node.name}): {why} and it does not answer " + f"over SSH ({sp.silent[rank]} checks in a row)") + else: + silent.append(rank) + return silent + + @staticmethod + def _stream_ended(rec: _Island, rank: int) -> bool: + """Whether rank ``rank``'s stream of the current incarnation ended (its heartbeat).""" + job = rec.job + return (job is not None and job.incarnation == rec.incarnation and rank < len(job.procs) + and job.procs[rank].poll() is not None) + + def _relaunch_with_spares(self, rec: _Island) -> int | None: + """The relaunch of an island with spare nodes: release the failed incarnation on every + node but the lost ones, then start the next incarnation on the same nodes (nothing + lost) or with spares in the lost nodes' places (:meth:`_replace`). The spares' health + checks run outside the ops lock (:meth:`_precheck`).""" + with self._lock: + inc = rec.incarnation + if inc is not None and inc not in rec.released: + silent = self._probe_silent(rec) + if silent: + names = [rec.spec.nodes[r].name for r in silent] + self.log(f"[launcher] {rec.name}: node(s) {names} do not answer over SSH; no new start " + "this poll") + return None + if not self._release(rec, inc, skip=self._lost_names(rec)): + self.log(f"[launcher] {rec.name}: incarnation {inc} not confirmed stopped; no new start " + "this poll") + return None + if not rec.spares.lost: + nxt = 0 if inc is None else inc + 1 + try: + return self._launch(rec, nxt) + except Exception as error: # noqa: BLE001 - the controller retries next poll + self.log(f"[launcher] {rec.name}: start of incarnation {nxt} failed: {error}") + self._release(rec, nxt) + return None + if not self._replace_due(rec): + return None + return self._replace_checked(rec) + + def _replace_checked(self, rec: _Island) -> int | None: + """:meth:`_replace` with the spares' health checks outside the ops lock: check, pick + under the lock, and check the next candidates when a checked one was taken meanwhile.""" + if rec.spares.waiting: # a backoff check: a lost node back (a network partition) gets its owed stop + self._retry_owed_stops(rec) + health: dict[str, tuple[bool, str]] = {} + for _ in range(len(rec.spares.pool) + 1): # each round checks at least one more candidate + health.update(self._precheck(rec, known=health)) + with self._lock: + job_id = self._replace(rec, health) + if job_id is not _RECHECK: + return job_id + return None + + def _precheck(self, rec: _Island, known: Any = ()) -> dict[str, tuple[bool, str]]: + """The health checks of the spares a replacement would pick, but ``known`` (SSH; no + ops lock).""" + from . import island_spares as isp # noqa: PLC0415 + + sp = rec.spares + return isp.check_candidates(sp, rec.name, list(rec.spec.nodes), dict(sp.lost), ops=self.ops, + need=len(sp.lost), known=known) + + def _replace_due(self, rec: _Island) -> bool: + """Whether a replacement is tried this poll: past the replacement limit or the longest + wait (``max_wait_s``) the relaunch is refused (RelaunchBlocked: the island stops); + while it waits, an ``island_waiting_spare`` every ``report_every_s`` and nothing + before the backoff's next check.""" + from . import island_spares as isp # noqa: PLC0415 + from .fleet import RelaunchBlocked # noqa: PLC0415 + + sp = rec.spares + now, wall = self.clock(), self.wall() + lost = sorted(self._lost_names(rec)) + if sp.limit_reached(wall): + done = sp.recent(wall) + why = (f"{len(done)} node replacement(s) within {sp.window_s / 3600:.0f} h (max {sp.max_replacements}): " + + ", ".join(f"{r.get('lost')} -> {r.get('spare')}" for r in done) + + f"; node(s) {lost} lost again: the island stops") + if not sp.limited: + sp.limited = True + sp.emit(isp.REPLACEMENT_LIMIT, replaced=[dict(r) for r in done], lost=lost, reason=why[:500]) + self.log(f"[launcher] CRITICAL: {rec.name}: {why}") + raise RelaunchBlocked(why) + waited = sp.waited_s(wall) + if sp.wait_since is not None and waited >= sp.max_wait_s: + why = (f"waited {waited:.0f} s for a spare node for {lost} (max {sp.max_wait_s:.0f} s, " + f"--spare-max-wait-s): {sp.wait_reason or 'no spare'}; the island stops") + if not sp.limited: + sp.limited = True + sp.emit(isp.WAITING_SPARE, lost=lost, reason=why[:500], elapsed_s=round(waited), given_up=True) + self.log(f"[launcher] CRITICAL: {rec.name}: {why}") + raise RelaunchBlocked(why) + if sp.report_due(wall): + sp.emit(isp.WAITING_SPARE, lost=lost, reason=str(sp.wait_reason or "")[:500], elapsed_s=round(waited), + next_check_s=round(max(0.0, sp.next_check - now))) + return not (sp.waiting and now < sp.next_check) + + def _replace(self, rec: _Island, health: dict[str, tuple[bool, str]] | None = None) -> int | None: + """Spares in the lost nodes' places and the next incarnation on them; None while no + spare is there (``waiting_spare``, checked again after the backoff) or the start on + it failed. ``health``: the candidates' checks (:meth:`_precheck`); the claims, leases + and records are read again here, and :data:`_RECHECK` when a candidate left is not + checked yet (the caller checks it outside the lock and asks again). Past the + replacement limit or the longest wait the relaunch is refused (the island stops).""" + import dataclasses # noqa: PLC0415 + + from . import island_spares as isp # noqa: PLC0415 + + if not self._replace_due(rec): + return None + sp = rec.spares + now, wall = self.clock(), self.wall() + current = list(rec.spec.nodes) + picks: dict[int, Any] = {} + for rank in sorted(sp.lost): + pick = isp.pick_spare(sp, rec.name, current, sp.lost, ops=self.ops, chosen=list(picks.values()), + health=health) + if pick.node is None: + for node in picks.values(): + isp.unpick(sp, rec.name, node) + if pick.unchecked and health is not None: + return _RECHECK # type: ignore[return-value] + reason = pick.why_none() + if sp.wait(now, reason, wall=wall): + sp.emit(isp.WAITING_SPARE, lost=sorted(self._lost_names(rec)), reason=reason[:500], + group=pick.group, next_check_s=sp.wait_s, elapsed_s=round(sp.waited_s(wall))) + self.log(f"[launcher] {rec.name}: waiting for a spare node ({reason}); next check in " + f"{sp.wait_s:.0f} s") + return None + picks[rank] = pick.node + nxt = 0 if rec.incarnation is None else rec.incarnation + 1 + old_spec, old_islands = rec.spec, rec.islands + try: + new_spec = dataclasses.replace(old_spec, nodes=tuple(picks.get(r, n) for r, n in enumerate(current))) + except SshIslandError as error: # e.g. a spare without a rendezvous address + for node in picks.values(): + isp.unpick(sp, rec.name, node) + sp.records.quarantine(node.name, island=rec.name, reason=f"cannot take a node's place: {error}") + sp.wait(now, f"spare refused: {error}", wall=wall) + self.log(f"[launcher] {rec.name}: spare(s) {[n.name for n in picks.values()]} refused: {error}") + return None + old_health = rec.health + for rank in picks: # a health reading of the node it had is stale from now on + rec.rank_gen[rank] = rec.rank_gen.get(rank, 0) + 1 + rec.spec, rec.islands = new_spec, self._islands_for(rec, new_spec) + rec.health = self._health_watches(new_spec) # one watch per rank of the new node set + self._record_nodes(rec) # before any start: a launcher gone meanwhile leases the spare, not the lost node + try: + job_id = self._launch(rec, nxt) # every node's preflight first: the spare's image, cards, scratch + except Exception as error: # noqa: BLE001 - back to the old nodes; checked again after the backoff + self.log(f"[launcher] {rec.name}: start of incarnation {nxt} on spare(s) " + f"{[n.name for n in picks.values()]} failed: {error}") + if str(nxt) in read_jobs(self.jobs_path(rec.name)): + rec.islands.release_incarnation(nxt) + for node in picks.values(): + isp.unpick(sp, rec.name, node) + if node.name in str(error): + sp.records.quarantine(node.name, island=rec.name, reason=f"its start as a spare failed: {error}") + rec.spec, rec.islands, rec.health = old_spec, old_islands, old_health + self._record_nodes(rec) # back to the nodes it runs on + sp.nodes.pop(str(nxt), None) + sp.save() + sp.wait(now, f"the start on the spare node(s) failed: {error}", wall=wall) + return None + resume = sp.resume_probe() if sp.resume_probe is not None else None + step = None if resume is None else resume.get("step") + for rank, node in sorted(picks.items()): + row = {"at": wall, "island": rec.name, "rank": int(rank), "lost": current[rank].name, "spare": node.name, + "incarnation": int(nxt), "reason": sp.lost[rank][:300], "resume_step": step} + sp.replacements.append(row) + sp.emit(isp.NODE_REPLACED, **{k: v for k, v in row.items() if k != "at"}, + resume=resume, group=isp.fabric_group(node)) + self.log(f"[launcher] {rec.name}: node {current[rank].name} (rank {rank}) replaced by spare {node.name}; " + f"incarnation {nxt} resumes from the newest checkpoint" + + (f" (step {step}, {resume.get('source')})" if resume else " (none in the store yet)")) + sp.save() + sp.lost.clear() + sp.stream_ended.clear() + sp.unconfirmed.clear() + sp.silent.clear() + sp.done_waiting() + return job_id + + # -- what the fleet controller reads of the spares ------------------------------------ + def waiting_spare(self, name: str) -> bool: + """The island waits for a spare node (the controller does not give it up on its + recover timeout meanwhile).""" + rec = self.islands.get(name) + return bool(rec is not None and rec.spares is not None and rec.spares.waiting) + + def island_events(self, name: str) -> list[dict[str, Any]]: + """The island's spare-node events since the last call (``island_node_lost``, ...).""" + rec = self.islands.get(name) + if rec is None or rec.spares is None: + return [] + return rec.spares.take_events() # its own lock: never waits for a relaunch in flight + + def spares_view(self, name: str) -> dict[str, Any] | None: + """The island record's ``spares`` (None: an island without spare nodes).""" + rec = self.islands.get(name) + sp = None if rec is None else rec.spares + if sp is None: + return None + current = [n.name for n in rec.spec.nodes] + last = sp.replacements[-1] if sp.replacements else None + return {"nodes": current, "spare_nodes": sorted(n.name for n in sp.pool if n.name not in current), + "lost": sorted(self._lost_names(rec)), "waiting_spare": bool(sp.waiting), + "wait_reason": sp.wait_reason, "waiting_since": sp.wait_since if sp.waiting else None, + "replacements": len(sp.replacements), + "replacements_window": len(sp.recent(self.wall())), "max_replacements": int(sp.max_replacements), + "last_replaced_at": None if last is None else last.get("at")} def _node_log_tail(self, rec: _Island, reason: str, lines: int = 20) -> str: """The last lines of the failed rank's local log copy (rank > 0).""" @@ -566,19 +1189,43 @@ def _node_log_tail(self, rec: _Island, reason: str, lines: int = 20) -> str: return "" # -- release ---------------------------------------------------------------------- - def _release(self, rec: _Island, incarnation: int) -> bool: + def _release(self, rec: _Island, incarnation: int, *, skip: frozenset[str] = frozenset()) -> bool: if incarnation in rec.released: return True - if rec.job is not None and rec.job.incarnation == incarnation: - ok = rec.islands.release(rec.job) + sp = rec.spares + if sp is None: + if rec.job is not None and rec.job.incarnation == incarnation: + ok = rec.islands.release(rec.job) + else: + ok = rec.islands.release_incarnation(incarnation) else: - ok = rec.islands.release_incarnation(incarnation) + # spare nodes: a lost node is not waited for and owes its stop (its own ledger row) + # unless that stop was confirmed (owed_lock: never a row left open after it); a node + # whose stop is not confirmed keeps its stream (the relaunch checks it) + with sp.owed_lock: + owed = frozenset(n for n in skip + if (n, int(incarnation)) not in sp.stopped and self._owes(rec, n, incarnation)) + if rec.job is not None and rec.job.incarnation == incarnation: + ok = rec.islands.release(rec.job, skip=skip, owed=owed, keep_unconfirmed=True) + else: + ok = rec.islands.release_incarnation(incarnation, skip=skip, owed=owed) + failed = rec.islands.unconfirmed.get(int(incarnation), frozenset()) + sp.unconfirmed = {r for r, n in enumerate(rec.spec.nodes) if n.name in failed} if ok: rec.released.add(incarnation) # SshTrainerIslands closed its ledger row else: self.log(f"[launcher] {rec.name}: release of incarnation {incarnation} NOT confirmed on every node") return ok + def _owes(self, rec: _Island, name: str, incarnation: int) -> bool: + """Whether lost node ``name`` still owes its stop of ``incarnation`` (its quarantine + record in this run lists it; a node another run quarantined never ran it).""" + doc = rec.spares.records.own_quarantine(name) + if doc is None: + return False + return any(str(o.get("island")) == rec.name and int(o.get("incarnation", -1)) == int(incarnation) + for o in doc.get("owed") or ()) + # -- tape recovery ---------------------------------------------------------------- def recover_tape(self, name: str, collector: Any) -> bool: """Complete ``collector`` from node 0's own log (the echo's source) of the current @@ -723,10 +1370,14 @@ def dry_run_record(args: Any, spec: SshTrainerSpec, name: str, *, mode: str = "r "image itself must hold the yeto checkout there") break health = node_health_summary(spec) + from .island_spares import spare_view # noqa: PLC0415 + + spares = spare_view(args, spec) return { "mode": mode, **({"node_health": health} if health is not None else {}), "warnings": warnings, + **({"spares": spares} if spares is not None else {}), "code": code, "journal": str(runs.run_dir(spec.run_id) / RESIDENT_DIR / f"{name}-jobs.json") if mode == "resident" else None, "env_order": "fabric defaults < inventory node env < --island-env and the island task env" diff --git a/yeto/launch/ssh_trainer_island.py b/yeto/launch/ssh_trainer_island.py index c9980d3df..344c2d1d6 100644 --- a/yeto/launch/ssh_trainer_island.py +++ b/yeto/launch/ssh_trainer_island.py @@ -745,6 +745,10 @@ def _write_files(files: Sequence[tuple[int, str, str]], paths: Mapping[str, str] return out +# In an incarnation's state dir: its owed stop went through and removed the pid file. +STOPPED_MARKER = "stopped" + + def kill_script(paths: Mapping[str, str], grace_s: int = KILL_GRACE_S, *, container: str | None = None) -> str: """TERM the island's process group, KILL it after ``grace_s``; exit 0 when it is gone. ``container``: stop and remove that docker container first (a killed @@ -754,7 +758,8 @@ def kill_script(paths: Mapping[str, str], grace_s: int = KILL_GRACE_S, *, contai The pid file is read from the login HOME, where :func:`start_script` pins the state dir. No pid file: a warning, and exit 0 only when the state dir does not exist either (this incarnation never started on the node); a state dir with no - pid file exits 3, so a release cannot report ok while the island may still run.""" + pid file exits 3, so a release cannot report ok while the island may still run, + unless an owed stop already went through there (its ``stopped`` marker).""" remove = "" if container: c = shlex.quote(container) @@ -777,6 +782,8 @@ def kill_script(paths: Mapping[str, str], grace_s: int = KILL_GRACE_S, *, contai remove + f"{STATE_HOME_VAR}=\"$HOME\"\n" + f"if ! pid=$(cat \"{paths['pid']}\" 2>/dev/null) || [ -z \"$pid\" ]; then\n" + # an owed stop went through already (``island_spares.owed_kill_script``) + + f" [ -e \"{paths['dir']}/{STOPPED_MARKER}\" ] && exit 0\n" + f" if [ -d \"{paths['dir']}\" ]; then\n" + f" echo \"[yeto] kill: no pid in {paths['pid']} but the state dir exists; the island may " "still run\" >&2; exit 3\n" @@ -910,6 +917,7 @@ def __init__(self, spec: SshTrainerSpec, *, name: str, jobs_path: Path, ops: Ssh self.checked = False self.unreleased: set[int] = set() # incarnations not confirmed stopped on every node self.started: set[int] = set() # incarnations started and not (yet) confirmed stopped + self.unconfirmed: dict[int, frozenset[str]] = {} # incarnation -> nodes whose last stop is not confirmed # -- preflight ---------------------------------------------------------------- def preflight(self) -> None: @@ -1178,19 +1186,27 @@ def finish_leases(self) -> None: if not leases.held(): # no other island of the process holds a lease: the keeper is done leases.stop_keeper() - def release(self, job: _SshJob) -> bool: - ok = self._kill(job.incarnation) - for proc in job.procs: - if proc.poll() is None: + def release(self, job: _SshJob, *, skip: frozenset[str] = frozenset(), owed: frozenset[str] | None = None, + keep_unconfirmed: bool = False) -> bool: + """Stop ``job`` on every node. ``skip``: lost nodes (names) not waited for: the + others must confirm; the stop such a node owes gets a ledger row of its own + (``owed``: the skipped nodes that owe it, default all; a lost node whose stop was + confirmed owes nothing). ``keep_unconfirmed``: the streams of the nodes whose stop + is not confirmed (:attr:`unconfirmed`) stay open (their heartbeat).""" + ok = self._kill(job.incarnation, skip=skip, owed=owed) + keep = self.unconfirmed.get(int(job.incarnation), frozenset()) if keep_unconfirmed else frozenset() + for rank, proc in enumerate(job.procs): + if proc.poll() is None and self.spec.nodes[rank].name not in keep: proc.terminate() return ok - def release_incarnation(self, incarnation: int) -> bool: + def release_incarnation(self, incarnation: int, *, skip: frozenset[str] = frozenset(), + owed: frozenset[str] | None = None) -> bool: if str(int(incarnation)) not in read_jobs(self.jobs_path): print(f"[launcher] trainer incarnation {incarnation}: no SSH start recorded; nothing to release", flush=True) return False - return self._kill(incarnation) + return self._kill(incarnation, skip=skip, owed=owed) def start_events(self) -> list[Mapping[str, Any]]: return [e for job in self.jobs for e in job.events.all] @@ -1259,15 +1275,22 @@ def _stop_unreleased(self, incarnation: int) -> None: "stopped on every node; not starting another over it") print(f"[launcher] trainer incarnation {earlier}: stopped on every node now", flush=True) - def _kill(self, incarnation: int) -> bool: - ok = self._kill_nodes(incarnation) + def _kill(self, incarnation: int, *, skip: frozenset[str] = frozenset(), + owed: frozenset[str] | None = None) -> bool: + ok = self._kill_nodes(incarnation, skip=skip) + owed = skip if owed is None else owed & skip + if ok and owed: # the lost nodes not waited for: each owes its stop in a row of its own + for rank, node in enumerate(self.spec.nodes): + if node.name in owed: + ssh_trainer_ledger.record_owed(**self._ledger_key(incarnation), node=node, rank=rank, + docker=self.spec.docker, kill_grace_s=self.kill_grace_s) if ok: # every node confirmed: the ledger row closes (else a cleanup retries it) ssh_trainer_ledger.record("released", **self._ledger_key(incarnation)) self.started.discard(int(incarnation)) - self._fetch_outputs(incarnation) + self._fetch_outputs(incarnation, skip=skip) return ok - def _fetch_outputs(self, incarnation: int) -> None: + def _fetch_outputs(self, incarnation: int, *, skip: frozenset[str] = frozenset()) -> None: """Copy each node's ``~/yeto-output`` of this incarnation into ``/-i-output/node/`` (ssh_node_storage); a failure is a warning, never a failed release. Nothing without an events dir.""" @@ -1276,6 +1299,8 @@ def _fetch_outputs(self, incarnation: int) -> None: paths = _pin_state_home(remote_paths(self.spec.run_id, self.name, incarnation)) base = Path(self.events_dir) / f"{self.name}-i{int(incarnation)}-output" for rank, node in enumerate(self.spec.nodes): + if node.name in skip: + continue remote = ssh_node_storage.output_dir(node, paths["dir"]) script = f"{STATE_HOME_VAR}=\"$HOME\"\n" + ssh_node_storage.output_fetch_script(remote) try: @@ -1289,14 +1314,19 @@ def _fetch_outputs(self, incarnation: int) -> None: f"from {node.name} ({type(error).__name__}: {error}); it stays on the node", flush=True) - def _kill_nodes(self, incarnation: int) -> bool: + def _kill_nodes(self, incarnation: int, *, skip: frozenset[str] = frozenset()) -> bool: paths = remote_paths(self.spec.run_id, self.name, incarnation) ok = True + failed: set[str] = set() for rank, node in enumerate(self.spec.nodes): + if node.name in skip: # a lost node: not waited for (its stop is owed, island_spares) + continue script = kill_script(paths, self.kill_grace_s, container=self._container(incarnation, rank)) try: done = self.ops.run(node, script, timeout=self.kill_grace_s + 60.0) ok &= done.returncode == 0 + if done.returncode != 0: + failed.add(node.name) err = (getattr(done, "stderr", "") or "").strip() if done.returncode != 0: # rc 0 + stderr is ssh banner noise print(f"[launcher] stop of trainer incarnation {incarnation} on {node.name}: " @@ -1305,6 +1335,8 @@ def _kill_nodes(self, incarnation: int) -> bool: print(f"[launcher] stop of trainer incarnation {incarnation} on {node.name} failed: {error}", flush=True) ok = False + failed.add(node.name) + self.unconfirmed[int(incarnation)] = frozenset(failed) if ok: self.unreleased.discard(int(incarnation)) else: @@ -1459,6 +1491,13 @@ def _lease_record(args: Any) -> dict[str, Any]: return doc if isinstance(doc, dict) else {} +def record_island_nodes(run_id: str, name: str, nodes: Sequence[Node]) -> None: + """Island ``name`` of run ``run_id`` runs on ``nodes`` now (a spare took a lost node's + place): the run dir's lease record (:data:`NODE_LEASE_FILE`) says so, so a restarted + launcher leases these nodes again, not the lost one. Raises OSError.""" + _record_island_nodes(type("Args", (), {"cluster_prefix": run_id})(), name, nodes) + + def _record_island_nodes(args: Any, name: str, nodes: Sequence[Node]) -> None: path = _lease_record_path(args) doc = _lease_record(args) @@ -1504,7 +1543,8 @@ def lease_trainer_nodes(args: Any, trainers: Sequence[Node], need: int, leases: ran on: those nodes, every one leased again; one another run holds refuses the launch (:class:`SshIslandError`: the island is not moved to other nodes). * Otherwise: the recorded nodes and the nodes this run holds first, then free ones; - held nodes are skipped; too few free nodes: wait (a line every 5 minutes, a + held nodes and nodes quarantined in the lease store (``island_spares``) are + skipped; too few free nodes: wait (a line every 5 minutes, a ``node_lease_waiting`` event, the run's STOP flag ends it) up to ``wait_s`` (default ``--rl-node-lease-wait-s``, 3600 s), then :class:`SshIslandError`. @@ -1514,16 +1554,23 @@ def lease_trainer_nodes(args: Any, trainers: Sequence[Node], need: int, leases: from yeto import runs from .node_lease import NodeLeased, pick_nodes + from .node_quarantine import JOURNAL_SUFFIX, SPARE_ROLE, latest_spare_nodes key = name or f"island-{len(leases.picks)}" by_name = {n.name: n for n in trainers} + # a recorded node may be a spare that took a lost node's place (island_spares) + known = {**{n.name: n for n in (getattr(args, "rl_node_inventory_nodes", None) or ()) + if SPARE_ROLE in (getattr(n, "roles", None) or ())}, **by_name} if key in leases.picks: - return tuple(by_name[n] for n in leases.picks[key]) - recorded = [n for n in (_lease_record(args).get("islands") or {}).get(key, ()) if n in by_name] + return tuple(known[n] for n in leases.picks[key]) + # the nodes it runs on: its spares journal's newest incarnation (written before any start), + # else the lease record + journal = latest_spare_nodes(runs.run_dir(args.cluster_prefix) / "ssh-islands" / f"{key}{JOURNAL_SUFFIX}") + recorded = [n for n in (journal or (_lease_record(args).get("islands") or {}).get(key, ())) if n in known] if recorded and len(recorded) == need and _journal_incarnation(args, key): held = {} for node in recorded: - got = leases.acquire(by_name[node]) + got = leases.acquire(known[node]) if not got.ok: held[node] = leases.same_run_conflict(got.holder) or got.blocked or f"run {got.holder}" if held: @@ -1534,7 +1581,7 @@ def lease_trainer_nodes(args: Any, trainers: Sequence[Node], need: int, leases: f"ssh: island {key}: its last incarnation ran on {recorded} (the jobs journal); " + ", ".join(f"{n} is held by {h}" for n, h in sorted(held.items())) + ": not moving the island to other nodes (free them, or start a new run)") - picked = [by_name[n] for n in recorded] + picked = [known[n] for n in recorded] else: flag = getattr(args, "rl_node_lease_wait_s", None) limit = wait_s if wait_s is not None else float(DEFAULT_NODE_LEASE_WAIT_S if flag is None else flag) @@ -1543,11 +1590,25 @@ def lease_trainer_nodes(args: Any, trainers: Sequence[Node], need: int, leases: def stop() -> str | None: return f"the run's STOP flag {stop_flag}" if stop_flag.exists() else None + # a node quarantined by any run of the inventory (a lost node, island_spares: its record + # in the lease store, nodes//quarantine.json) is no candidate until release-node + from .node_quarantine import quarantine_note, shared_quarantines + + docs = shared_quarantines(getattr(leases, "objects", None), by_name, + log=lambda line: print(line, file=sys.stderr, flush=True)) + quarantined = set(docs) # an unreadable record counts as one + note = quarantine_note(docs) + if note: # said once, and on every waiting line: not just "no free node" + print(f"[launcher] node leases: island {key}: {note}", file=sys.stderr, flush=True) + + def log(line: str) -> None: + print(line + (f"; {note}" if note else ""), file=sys.stderr, flush=True) + try: picked = pick_nodes(list(trainers), need, leases, wait_s=limit, prefer=recorded, stop=stop, - excluded=leases.assigned, place=place) + excluded=set(leases.assigned) | quarantined, place=place, log=log) except NodeLeased as error: - raise SshIslandError(f"ssh: island {key}: {error}") from None + raise SshIslandError(f"ssh: island {key}: {error}" + (f"; {note}" if note else "")) from None leases.picks[key] = [n.name for n in picked] leases.assigned |= {n.name for n in picked} try: diff --git a/yeto/launch/ssh_trainer_ledger.py b/yeto/launch/ssh_trainer_ledger.py index 175dfa152..6b5d590c6 100644 --- a/yeto/launch/ssh_trainer_ledger.py +++ b/yeto/launch/ssh_trainer_ledger.py @@ -12,7 +12,11 @@ run id, the island name, the incarnation, each node's SSH target and jump host, whether the nodes run docker, the kill grace; * ``released`` once every node confirmed the stop (``SshTrainerIslands.release`` - / ``release_incarnation``); an unconfirmed stop stays open for the cleanup; + / ``release_incarnation``); an unconfirmed stop stays open for the cleanup. A lost node + that is not waited for (an island with spare nodes, ``island_spares``) gets its own row + (:func:`record_owed`: that node and its rank only) once the other nodes confirmed; + the incarnation's row closes. A lost node whose own stop was confirmed owes nothing; a + confirmed owed stop later (:func:`release_owed`) closes that row; * :func:`cleanup_release` (``yeto cleanup``, the reaper) runs the same kill script on every node, then ends the run's node leases there (inventory ``lease_store``: the row records the lease store and holder); @@ -59,6 +63,79 @@ def record(op: str, *, run_id: str, island: str, incarnation: int, attrs: dict[s record_safely(op, KIND, rid, f"{island}-i{int(incarnation)}", **dict(attrs or {})) +def record_owed(*, run_id: str, island: str, incarnation: int, node: Node, rank: int, docker: bool, + kill_grace_s: int) -> None: + """The row of the stop a lost node still owes for an incarnation (``cleanup_release`` + stops it there, at its own rank); priced as that node only.""" + from yeto.cost.ledger import record_safely + + rid = owed_id(run_id, island, incarnation, node.name) + attrs = created_attrs(run_id=run_id, island=island, incarnation=incarnation, nodes=[node], docker=docker, + kill_grace_s=kill_grace_s) + record_safely("created", KIND, rid, f"{island}-i{int(incarnation)}-owed-{node.name}", ranks=[int(rank)], + **attrs) + + +def owed_id(run_id: str, island: str, incarnation: int, node: str) -> str: + return f"{resource_id(run_id, island, incarnation)}-owed-{node}" + + +OWED_RELEASED = "released" # release_owed: the row closed +OWED_ABSENT = "absent" # not open in this ledger (never recorded, closed, or the ledger is elsewhere) +OWED_NO_LEDGER = "no-ledger" + + +def _run_ledger(run_id: str) -> Any: + from yeto.cost.ledger import ResourceLedger, current + + return current() or ResourceLedger.for_run(str(run_id)) + + +def release_owed(*, run_id: str, island: str, incarnation: int, node: str) -> tuple[str, str]: + """The owed stop of ``node`` for that incarnation is confirmed (its own stop in the + background, or ``yeto cluster release-node``): its row closes. The run's ledger is + ``$YETO_RESOURCE_LEDGER``, else the run's own (a ``release-node`` outside the run). + ``(status, ledger path)``: :data:`OWED_RELEASED`, :data:`OWED_ABSENT` (a ``release-node`` + on a machine without the run dir finds no row: the caller says where it is) or + :data:`OWED_NO_LEDGER`.""" + from yeto.cost.ledger import record_safely + + try: + ledger = _run_ledger(run_id) + except Exception as error: # noqa: BLE001 - printed, the row stays for yeto cleanup + print(f"[cost] WARNING: no resource ledger for run {run_id} ({error}); the owed row of {node} stays " + "open for `yeto cleanup`", flush=True) + return OWED_NO_LEDGER, "" + rid = owed_id(run_id, island, incarnation, node) + if not any(r.id == rid for r in ledger.open_resources()): + return OWED_ABSENT, str(ledger.path) # never recorded (the stop came first), closed, or elsewhere + record_safely("released", KIND, rid, f"{island}-i{int(incarnation)}-owed-{node}", ledger=ledger) + return OWED_RELEASED, str(ledger.path) + + +def release_owed_elsewhere(*, run_id: str, node: str, stop: Any = None) -> list[str]: + """``node`` is picked again and has no quarantine record: its owed stops were run + elsewhere (``yeto cluster release-node`` on a machine without this run's ledger), so + the run's open owed rows of that node close (``reason: released elsewhere``) and it is + not billed twice. ``stop(row)``: run the row's stop first, the row closes only when it + returns True. Returns the rows closed.""" + from yeto.cost.ledger import record_safely + + try: + ledger = _run_ledger(run_id) + rows = [r for r in ledger.open_resources() + if r.kind == KIND and str(r.id).startswith(f"{run_id}/") and str(r.id).endswith(f"-owed-{node}")] + except Exception: # noqa: BLE001 - no ledger: nothing billed here + return [] + closed = [] + for row in rows: + if stop is not None and not stop(row): + continue + record_safely("released", KIND, row.id, getattr(row, "name", None), ledger=ledger, reason="released elsewhere") + closed.append(str(row.id)) + return closed + + class _LedgerNode: """The SSH reach of a node as the ledger row keeps it (``SshOps`` needs only this).""" @@ -97,7 +174,8 @@ def cleanup_release(resource: Any, ops: Any = None, dry_run: bool = False, paths = remote_paths(run_id, island, incarnation) ssh = ssh or getattr(ops, "ssh_ops", None) or SshOps() failed: list[str] = [] - for rank, node in enumerate(nodes): + ranks = [int(r) for r in attrs.get("ranks") or range(len(nodes))] # an owed row: the lost node's rank + for rank, node in zip(ranks, nodes): container = container_name(run_id, island, incarnation, rank) if attrs.get("docker") else None try: done = ssh.run(node, kill_script(paths, grace, container=container), timeout=grace + 60.0) diff --git a/yeto/launch/trainer_provision.py b/yeto/launch/trainer_provision.py index 781776554..6ca3d6c78 100644 --- a/yeto/launch/trainer_provision.py +++ b/yeto/launch/trainer_provision.py @@ -369,7 +369,8 @@ def start(self, prov): if prov.guard_order is not None: # a start that is no reattach orders the island's processes prov.guard_order(",".join(sorted(names))) return start_resident_ssh(prov.args, tasks, names, prov.results, prov.errors, prov.events_dir, - prov.collectors) + prov.collectors, island_index={n: prov.islands[n].m for n in names}, + num_islands=len(prov.specs)) _SOURCES: list[Source] = [SshSource(), ModalSource(), VerdaSource(), SkySource()] @@ -418,9 +419,11 @@ def resident_ssh_names(args, names: list[str], specs: list[ClusterSpec]) -> set[ return {n for m, (n, s) in enumerate(zip(names, specs)) if is_resident(args, s, m, len(specs))} -def start_resident_ssh(args, tasks, names, results, errors, events_dir, collectors): +def start_resident_ssh(args, tasks, names, results, errors, events_dir, collectors, *, island_index=None, + num_islands=None): """Start (or reattach to) every resident ``ssh:`` island; returns their ops. Node 0's - lines go to the launcher log and the island's echo tape collector.""" + lines go to the launcher log and the island's echo tape collector. ``island_index``: each + island's index among the launch's islands (its own checkpoint keys when it has spares).""" from .. import runs from ..rl.event_echo import TapeCollector as EventCollector from .ssh_resident import RESIDENT_DIR, SshIslandOps @@ -436,10 +439,15 @@ def sink(line: str) -> None: collector.feed(line) return sink + from .island_spares import spares_from_args + ops = SshIslandOps(run_id=args.cluster_prefix, journal_dir=runs.run_dir(args.cluster_prefix) / RESIDENT_DIR, events_dir=events_dir, sink_for=sink_for) for name in sorted(names): - ops.add(name, tasks[name]) + # an inventory with trainer-spare nodes: a lost node is replaced (island_spares); else None + spares = spares_from_args(args, tasks[name], island_index=(island_index or {}).get(name), + num_islands=num_islands) + ops.add(name, tasks[name], spares=spares) try: results[name] = (ops.start(name), None) except Exception as e: # noqa: BLE001 - reported with the other launch errors diff --git a/yeto/modal_runner.py b/yeto/modal_runner.py index 84c8c958e..a8bc7f642 100644 --- a/yeto/modal_runner.py +++ b/yeto/modal_runner.py @@ -2469,6 +2469,21 @@ def take_health_events(self, name): take = getattr(self._for(name), "take_health_events", None) return take(name) if take else [] + def island_events(self, name): + """The source's own events of the island (resident ``ssh:`` islands with spare nodes).""" + probe = getattr(self._for(name), "island_events", None) + return probe(name) if probe else [] + + def spares_view(self, name): + """The island's spare nodes (resident ``ssh:`` islands with spare nodes); None otherwise.""" + probe = getattr(self._for(name), "spares_view", None) + return probe(name) if probe else None + + def waiting_spare(self, name): + """The island waits for a spare node (resident ``ssh:`` islands with spare nodes).""" + probe = getattr(self._for(name), "waiting_spare", None) + return bool(probe(name)) if probe else False + def now(self): return self.sky_ops.now() diff --git a/yeto/rl/fleet.py b/yeto/rl/fleet.py index fad2edb8e..4549a65f9 100644 --- a/yeto/rl/fleet.py +++ b/yeto/rl/fleet.py @@ -128,8 +128,12 @@ DISPENSE_DIR = f"{FLEET_DIR}/dispense" # the fleet's task ledger root (store_dispense.FLEET_DISPENSE_DIR) DISPENSE_MODES = ("fleet", "island") FLEET_KEYS = frozenset({"trainer_argv", "dispense", "step_s", "sandbox_usd_per_h", "fixed_roster", "min_islands", - "island_lease_s", "launch", "max_islands"}) + "island_lease_s", "launch", "max_islands", "waiting_absent_after_s"}) DEFAULT_MIN_ISLANDS = 1 +# fleet.waiting_absent_after_s: an island waiting for a spare node (a resident ssh: island +# that lost a node, yeto.launch.island_spares) counts as running for fleet.min_islands this +# long, then as absent (its own give-up is --spare-max-wait-s, 24 h) +DEFAULT_WAITING_ABSENT_AFTER_S = 3600.0 LEGACY_PLAN = "a plan written before fleet.fixed_roster" # its launch had the fixed roster # fleet.launch: how the trainers start. synced_group (default): one yeto launch of every # trainer and the syncer. per_island: one yeto launch of the syncer and one per trainer @@ -285,6 +289,13 @@ class FleetPlan: roster_reason: str | None = None # why the roster is fixed (fleet.fixed_roster, or the pool's precondition) launch: str = LAUNCH_SYNCED_GROUP # fleet.launch max_islands: int | None = None # per_island: the syncer's learner id limit (fleet.max_islands) + waiting_absent_after_s: float | None = None # fleet.waiting_absent_after_s (None: the default) + + @property + def absent_after_s(self) -> float: + """How long an island waiting for a spare node still counts for ``min_islands``.""" + return float(DEFAULT_WAITING_ABSENT_AFTER_S if self.waiting_absent_after_s is None + else self.waiting_absent_after_s) @property def per_island(self) -> bool: @@ -296,7 +307,9 @@ def to_json(self) -> dict[str, Any]: "syncer": {"usd_per_h": self.syncer_usd_per_h, **({"placement": dict(self.syncer_placement)} if self.syncer_placement else {})}, "roster": {"fixed": self.fixed_roster, "min_islands": self.min_islands, - "lease_s": self.island_lease_s, "reason": self.roster_reason}, + "lease_s": self.island_lease_s, "reason": self.roster_reason, + **({"waiting_absent_after_s": self.waiting_absent_after_s} + if self.waiting_absent_after_s is not None else {})}, "islands": [i.to_json() for i in self.islands]} if self.per_island: # a synced-group plan stays byte for byte what it was out.update(launch=self.launch, max_islands=self.max_islands) @@ -385,7 +398,8 @@ def from_json(cls, doc: dict[str, Any]) -> FleetPlan: fixed_roster=bool(roster.get("fixed", False)), min_islands=int(roster.get("min_islands") or DEFAULT_MIN_ISLANDS), island_lease_s=roster.get("lease_s"), roster_reason=roster.get("reason"), - launch=str(doc.get("launch") or LAUNCH_SYNCED_GROUP), max_islands=doc.get("max_islands")) + launch=str(doc.get("launch") or LAUNCH_SYNCED_GROUP), max_islands=doc.get("max_islands"), + waiting_absent_after_s=roster.get("waiting_absent_after_s")) def plan_of(cfg: dict[str, Any]) -> FleetPlan | None: @@ -556,6 +570,19 @@ def roster_options(cfg: dict[str, Any]) -> tuple[bool, int, float | None]: return fixed, int(minimum), lease +def waiting_absent_after_s(cfg: dict[str, Any]) -> float | None: + """``fleet.waiting_absent_after_s`` as given (None: unset, the default + :data:`DEFAULT_WAITING_ABSENT_AFTER_S`): an island waiting for a spare node counts as + running for ``fleet.min_islands`` this long after its wait began, then as absent.""" + section = cfg.get("fleet") if isinstance(cfg.get("fleet"), dict) else {} + raw = section.get("waiting_absent_after_s") + if raw is None: + return None + if isinstance(raw, bool) or not isinstance(raw, (int, float)): + raise _err(f"fleet.waiting_absent_after_s must be a number of seconds > 0 (got {raw!r})") + return _seconds(raw, "fleet.waiting_absent_after_s") + + def membership_flags() -> frozenset[str]: """The ``yeto launch`` membership options (``yeto.launch.syncer`` island pool): any one set puts the islands in the syncer's dynamic membership.""" @@ -1335,7 +1362,7 @@ def compile_fleet(cfg: dict[str, Any], *, strict_breakers: bool = True) -> tuple syncer_placement=syncer_placement(argv).to_json(), fixed_roster=roster.fixed, min_islands=roster.min_islands, island_lease_s=roster.lease_s, roster_reason=roster.reason, - launch=launch, max_islands=max_islands) + launch=launch, max_islands=max_islands, waiting_absent_after_s=waiting_absent_after_s(cfg)) out = copy.deepcopy({k: v for k, v in cfg.items() if k != PLAN_KEY}) out["trainer"] = {"argv": argv, "usd_per_h": None if all(p is None for p in prices) else float(sum(p or 0.0 for p in prices))} diff --git a/yeto/rl/up.py b/yeto/rl/up.py index 815a4437a..793614818 100644 --- a/yeto/rl/up.py +++ b/yeto/rl/up.py @@ -3880,11 +3880,16 @@ def fleet_stop(self, reason: str, poll_s: float = 30.0) -> None: rows = (self.state.get("fleet_stops") or {}).get("islands") or () stopped = [r for r in rows if r.get("stop_reason")] + # islands waiting for a spare node count as absent (up_fleet_runtime.waiting_spare) + waiting = self.fleet_rt().waiting_spare() if self.fleet_plan() is not None else {} + absent = [*stopped, *({"index": k, "name": self.fleet_plan().islands[k].name, + "stop_reason": f"waiting for a spare node ({why})"} + for k, why in sorted(waiting.items()))] minimum = int(getattr(self.fleet_plan(), "min_islands", 1) or 1) head = ("every island stopped" if len(stopped) == len(rows) - else f"{len(rows) - len(stopped)} island(s) run, fewer than fleet.min_islands {minimum}") + else f"{len(rows) - len(absent)} island(s) run, fewer than fleet.min_islands {minimum}") why = head + " (" + ", ".join(f"island {r['index']} ({r['name']}): {r['stop_reason']}" - for r in stopped) + ")" + for r in absent) + ")" event = "fleet_all_islands_stopped" if len(stopped) == len(rows) else "fleet_min_islands_stopped" self.flag_stop(reason.removeprefix(STOP_REASON_PREFIX), "fleet_stop", event, why, grace_s=self.starvation_config.stop_grace_s, poll_s=poll_s, diff --git a/yeto/rl/up_fleet_runtime.py b/yeto/rl/up_fleet_runtime.py index 95355df85..7bf2e9aef 100644 --- a/yeto/rl/up_fleet_runtime.py +++ b/yeto/rl/up_fleet_runtime.py @@ -28,7 +28,12 @@ (``fleet/trainers//state.json``) shows it given up or failed, ``run.trainer_silence`` when its event tape stops growing. The run's STOP flag (the whole launch) is kept for the fleet-wide stops: ``run.budget``, ``run.wall_clock`` and fewer islands running than -``fleet.min_islands`` (default 1: every island stopped). An island without an event tape +``fleet.min_islands`` (default 1: every island stopped); an island whose record shows it +waiting for a spare node (``spares.waiting_spare``: a resident ``ssh:`` island that lost a +node, :mod:`yeto.launch.island_spares`) still counts there for +``fleet.waiting_absent_after_s`` (default 1 h) after its wait began, then as absent (a spare +usually comes within minutes; a fleet whose islands wait longer stops, its samplers with +it). The island's own give-up is ``--spare-max-wait-s`` (24 h), a separate matter. An island without an event tape (a sky / Verda / fetchable SSH island, a launch without records) keeps the run's own silence over the launcher log (:meth:`FleetRuntime.judges_every_trainer`). A fixed roster (``plan.fixed_roster``) keeps the path before the island STOP: no island STOP is written @@ -285,14 +290,52 @@ def trip_island(self, k: int, name: str, *, value: float | None, limit: float | self.stop_island(k, name, why) return True + MIN_ISLANDS_REASON = "fleet.min_islands" + + def waiting_spare(self, now: float | None = None) -> dict[int, str]: + """The running islands whose record shows them waiting for a spare node + (``spares.waiting_spare``) for longer than ``fleet.waiting_absent_after_s`` + (``plan.absent_after_s``; a record without the wait's start counts from when this + runtime first saw it wait): island -> why. They count as absent for ``min_islands``.""" + import time # noqa: PLC0415 + + now = time.time() if now is None else float(now) + active = self.active() + if not active: + return {} + try: + records = self.trainer_records(now) + except Exception: # noqa: BLE001 - unknown: not waiting + return {} + seen = self.__dict__.setdefault("_waiting_seen", {}) + limit = float(getattr(self.plan, "absent_after_s", 3600.0)) + out = {} + for k in active: + spares = (records.get(k) or {}).get("spares") + if not (isinstance(spares, dict) and spares.get("waiting_spare")): + seen.pop(k, None) + continue + since = spares.get("waiting_since") + since = float(since) if isinstance(since, (int, float)) else seen.setdefault(k, now) + waited = now - since + if waited > limit: + out[k] = (f"{str(spares.get('wait_reason') or 'no free spare node')[:300]}; waiting {waited:.0f} s, " + f"past fleet.waiting_absent_after_s {limit:.0f} s") + return out + def all_stopped(self) -> str | None: """The fleet's stop reason once fewer islands run than ``fleet.min_islands`` (default 1: every island stopped by a trip), else None: the first stopped island's reason (a - fleet-scoped trip's when there was one).""" + fleet-scoped trip's when there was one). An island waiting for a spare node counts + as absent (:meth:`waiting_spare`; reason :data:`MIN_ISLANDS_REASON`).""" stops = self.stops() running = stops.running() - if len(running) >= max(1, int(getattr(self.plan, "min_islands", 1) or 1)): - return None + minimum = max(1, int(getattr(self.plan, "min_islands", 1) or 1)) + if len(running) >= minimum: + waiting = self.waiting_spare() + if len(running) - len(waiting) >= minimum: + return None + return self.MIN_ISLANDS_REASON if stops.fleet_stop_reason is not None: return stops.fleet_stop_reason first = next((i.index for i in self.plan.islands if stops.stop_reason(i.index) is not None), None)