diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index a7766513a..89fad9a04 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -701,13 +701,42 @@ 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 +(`fleet/nodes//settled/`), and once the marker is written the launcher reads the +record again; if the record no longer lists that stop (the node was released, or +quarantined anew), it removes the marker. A stop the launcher confirms during or after +the release therefore leaves nothing behind. The release removes the record before +the markers. No clocks are compared, so a launcher and a release-node whose clocks +disagree behave the same. The release also leaves `fleet/nodes//released.json` +(who released the node, and when) in the run store. The launcher reads the record +again before each stop it retries, and skips a stop the record no longer owes. When the +store cannot list the markers, every stop the record lists counts as owed (a stop is +safe to run twice); when it cannot read the record, the launcher runs the stop, does not +write over the record, and release-node exits 1 asking to be run again later. 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. +A candidate spare with open owed rows (it was released elsewhere) has their stops run +during its checks, outside the launcher's lock and before any island starts on it; one +whose stop fails, or whose run ledger cannot be read, is passed over this round, with +the reason. One stop runs per node at a time. These stops run one after another and have +no overall deadline: with 8 spares whose stops each fail after the kill grace, one check +can take about half an hour (the other islands are not held up meanwhile). + +A spare whose start failed is given back to the pool only once its stop of that start is +confirmed. If that stop is not confirmed, the spare is treated as a lost node: it is +quarantined with the stop it owes, that stop gets a ledger row of its own (open until +the stop is confirmed), its lease is kept, and no island of this or another run picks +it until `yeto cluster release-node`. A failed start keeps its incarnation number: the +next try starts the next one, after stopping the failed one on any node where its stop +was not confirmed. `down()` also stops it there first; while that stop is not confirmed, +the island keeps its leases, claims and ledger rows (down reports a release not +confirmed). + +If the store refuses a quarantine record (a lost node, or such a spare), the launcher +keeps the quarantine in memory: the node owes its stop in a ledger row of its own, this +island does not pick it, the island's claim keeps the run's other islands off it, and +every check (and `down()`) writes the record again. Once it is written, the claim is +given up and the node is released as any quarantined node. ### Known limits diff --git a/tests/test_ssh_island_spares_recovery.py b/tests/test_ssh_island_spares_recovery.py index 36e62b6d3..e8436fe59 100644 --- a/tests/test_ssh_island_spares_recovery.py +++ b/tests/test_ssh_island_spares_recovery.py @@ -1320,19 +1320,67 @@ def run(node, script, *, timeout=300.0): assert not store.list("fleet/nodes/b300-1/settled/") -def test_a_settle_after_the_release_tombstone_writes_nothing(tmp_path): +@pytest.mark.parametrize("skew_s", [-3600.0, 3600.0]) +def test_a_settle_compares_no_clock(tmp_path, skew_s): + """REV-885e L1: release-node's clock is an hour ahead of or behind the launcher's. The + node is released, picked again and lost again (incarnation 1); its confirmed stop is + settled either way, so it owes no row (no second bill) and nothing is stopped twice.""" + store, clock = DirectoryObjectStore(tmp_path / "store"), Clock() + clock.t = 1_000_000.0 + launcher = NodeRecords(store, run_id="run1", log=lambda m: None, wall=clock) + cli = NodeRecords(store, run_id="", log=lambda m: None, wall=lambda: clock.t + skew_s) + launcher.quarantine("b300-1", island="isl", reason="lost", owed=[isp.owed_stop("run1", "isl", 0, 1, False)]) + clock.t += 10 + cli.release("b300-1") + clock.t += 10 + launcher.quarantine("b300-1", island="isl", reason="lost again", owed=[isp.owed_stop("run1", "isl", 1, 1, False)]) + launcher.settle("b300-1", run_id="run1", island="isl", incarnation=1) + assert launcher.own_quarantine("b300-1")["owed"] == [] + assert len(store.list("fleet/nodes/b300-1/settled/")) == 1 + + +def test_a_release_between_the_marker_and_the_second_read_leaves_no_marker(tmp_path): + """REV-885e L2: release-node runs after the settle created its marker and before it read + the record again (its listing of the markers missed this one): the settle removes it.""" 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.quarantine("b300-1", island="isl", reason="lost", owed=[isp.owed_stop("run1", "isl", 0, 1, False)]) + cli = NodeRecords(store, run_id="", log=lambda m: None) + real = records._create + + def create(key, doc): + made = real(key, doc) + cli.release("b300-1") # its marker listing ran before this create; its record delete after + return made + + records._create = create 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/") - records.settle("b300-2", run_id="run1", island="isl", incarnation=0) # no record: nothing either - assert not store.list("fleet/nodes/b300-2/") + + +def test_a_settle_keeps_its_marker_when_the_record_only_gained_a_stop(tmp_path): + store = DirectoryObjectStore(tmp_path / "store") + records = NodeRecords(store, run_id="run1", log=lambda m: None) + records.quarantine("b300-1", island="isl", reason="lost", owed=[isp.owed_stop("run1", "isl", 0, 1, False)]) + real = records._create + + def create(key, doc): + made = real(key, doc) + records.quarantine("b300-1", island="isl", reason="lost again", owed=[isp.owed_stop("run1", "isl", 1, 1, False)]) + return made + + records._create = create + records.settle("b300-1", run_id="run1", island="isl", incarnation=0) + assert [o["incarnation"] for o in records.own_quarantine("b300-1")["owed"]] == [1] + + +def test_settle_markers_of_different_stops_never_share_a_name(): + keys = {NodeRecords.settled_key("b300-1", run, island, k) + for run, island, k in [("a-b", "c", 1), ("a", "b-c", 1), ("a.b", "c", 1), ("a", "b.c", 1), + ("a", "b", 11), ("a-b-c", "i1", 1)]} + assert len(keys) == 6 + assert all(k.startswith("fleet/nodes/b300-1/settled/") and k.endswith(".json") for k in keys) # ------------------------------------------------------------------ REV-885d M2: a launcher gone mid-replacement @@ -1789,3 +1837,800 @@ def failed(self, incarnation, *a, **kw): 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 + + +# ------------------------------------------------------------------ REV-885e +def test_a_release_writes_no_tombstone_into_the_lease_store(tmp_path): + store, shared = DirectoryObjectStore(tmp_path / "store"), DirectoryObjectStore(tmp_path / "leases") + records = NodeRecords(store, run_id="run1", log=lambda m: None, shared=shared) + records.quarantine("b300-1", island="isl", reason="lost") + assert shared.read("nodes/b300-1/quarantine.json") is not None + records.release("b300-1") + assert not shared.list("nodes/b300-1/") # nothing left there: no one reads a tombstone in the lease store + + +class _FailingDeletes(DirectoryObjectStore): + def delete(self, key): + raise OSError("store unavailable") + + +def test_release_node_reports_a_store_that_fails_with_exit_1_and_no_traceback(tmp_path): + store = _FailingDeletes(tmp_path / "store") + NodeRecords(store, run_id="run1", log=lambda m: None).quarantine("b300-1", island="isl", reason="lost") + inv = _inventory(tmp_path, [*islands_spec().nodes, spare(3)]) + said: list[str] = [] + code = isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), + ssh=Cluster([*NAMES, "b300-3"]), objects=store, kill_grace_s=1, say=said.append) + assert code == 1 + assert any("stays quarantined" in line and "could not be removed" in line and "OSError" in line for line in said) + + +class _UnlistedStore(DirectoryObjectStore): + def list(self, prefix): + if "/settled/" in prefix: + raise OSError("list refused") + return super().list(prefix) + + +def test_a_spare_whose_start_failed_is_quarantined_with_the_lease_holder(tmp_path): + leases = FakeLeases() + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3), spare(4)], leases=leases) + 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 json.loads(store.read("fleet/nodes/b300-3/quarantine.json"))["lease_holder"] == leases.holder_id + + +class _LeaseStoreDown(FakeLeases): + def acquire(self, node): + if node.name == "b300-3": + raise OSError("lease store unavailable") + return super().acquire(node) + + +def test_a_pick_whose_lease_step_raises_gives_its_claim_back_and_takes_the_next(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3), spare(4)], leases=_LeaseStoreDown()) + assert ops.relaunch(None, "isl") == 1 + assert [n.name for n in ops.islands["isl"].spec.nodes] == ["b300-0", "b300-4", "b300-2"] + assert store.read("fleet/nodes/b300-3/claim.json") is None + + +def test_the_picks_so_far_are_given_back_when_a_later_pick_raises(tmp_path, monkeypatch): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3), spare(4)]) + spares.lost[2] = "lost too" + real, calls = isp.pick_spare, [] + + def pick_spare(*a, **kw): + calls.append(1) + if len(calls) == 2: + raise RuntimeError("the run store went away") + return real(*a, **kw) + + monkeypatch.setattr(isp, "pick_spare", pick_spare) + with pytest.raises(RuntimeError): + ops._replace(ops.islands["isl"], {"b300-3": (True, "healthy"), "b300-4": (True, "healthy")}) + assert store.read("fleet/nodes/b300-3/claim.json") is None and store.read("fleet/nodes/b300-4/claim.json") is None + + +def test_a_stale_lease_of_a_quarantined_node_is_kept(tmp_path): + 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"] + 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)]) + spares.records.quarantine("b300-3", island="isl", reason="lost") + ops.add("isl", s, spares=spares) + ops._release_stale_leases(ops.islands["isl"]) + assert "b300-3" in leases.held() or leases.holder(spare(3)) == leases.holder_id + assert leases.holder(spare(3)) == leases.holder_id # its lease stays this run's until release-node + + +def test_the_owed_stop_quotes_its_trap_for_any_island_name(tmp_path): + import os + import subprocess + + from yeto.launch.ssh_trainer_island import STATE_DIR + + home = tmp_path / "home" + sdir = home / STATE_DIR / "run1" / "is'l-i0" + sdir.mkdir(parents=True) + 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") + script = isp.owed_kill_script("run1", "is'l", 0, 5, None) + done = subprocess.run(["bash", "-c", script], env={**os.environ, "HOME": str(home)}, timeout=30, + capture_output=True, text=True) + assert done.returncode == 0, done.stderr + assert not (sdir / "pgid").exists() and (sdir / "stopped").exists() + finally: + try: + os.kill(pid, 0) + except ProcessLookupError: + pass + else: + import signal + + os.kill(pid, signal.SIGKILL) + + +def test_run_store_quarantines_and_the_trainer_pick_exclusions(tmp_path): + from yeto.launch import node_quarantine as nq + + run_store, lease_store = DirectoryObjectStore(tmp_path / "store"), DirectoryObjectStore(tmp_path / "leases") + NodeRecords(run_store, run_id="run1", log=lambda m: None).quarantine("b300-1", island="isl", reason="lost") + run_store.write("fleet/nodes/b300-2/quarantine.json", b"{broken") + lease_store.write("nodes/b300-0/quarantine.json", json.dumps({"run": "run9", "island": "x", "reason": "r"}).encode()) + docs = nq.run_store_quarantines(run_store, NAMES) + assert set(docs) == {"b300-1", "b300-2"} and docs["b300-2"]["unreadable"] + excluded, both, note = nq.trainer_pick_excluded(NAMES + ["b300-3"], lease_objects=lease_store, + run_objects=run_store, assigned={"b300-3"}) + assert excluded == {"b300-0", "b300-1", "b300-2", "b300-3"} and set(both) == {"b300-0", "b300-1", "b300-2"} + assert "b300-0 by run run9 island x" in note and "release-node" in note + assert nq.trainer_pick_excluded(NAMES) == (set(), {}, None) + + class Unlisted(DirectoryObjectStore): + def list(self, prefix): + raise OSError("no list") + + lines: list[str] = [] + docs = nq.run_store_quarantines(Unlisted(tmp_path / "store"), NAMES, log=lines.append) + assert set(docs) == {"b300-1", "b300-2"} and "each node's record is read" in lines[0] + + class Unread(DirectoryObjectStore): + def read(self, key): + raise OSError("no read") + + assert nq.run_store_quarantines(Unread(tmp_path / "store"), ["b300-1"])["b300-1"]["read_error"] + + +def test_a_spare_that_cannot_take_the_place_is_quarantined_with_the_lease_holder(tmp_path, monkeypatch): + from yeto.launch import ssh_trainer_island as sti + + leases = FakeLeases() + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)], leases=leases) + real = sti.rendezvous_address + + def address(node): + if node.name == "b300-3": + raise sti.SshIslandError("node b300-3: no rendezvous address") + return real(node) + + monkeypatch.setattr(sti, "rendezvous_address", address) + assert ops.relaunch(None, "isl") is None + doc = json.loads(store.read("fleet/nodes/b300-3/quarantine.json")) + assert "cannot take a node's place" in doc["reason"] and doc["lease_holder"] == leases.holder_id + + +def test_a_release_and_a_new_quarantine_between_the_marker_and_the_second_read_leave_no_marker(tmp_path): + store = DirectoryObjectStore(tmp_path / "store") + records = NodeRecords(store, run_id="run1", log=lambda m: None) + records.quarantine("b300-1", island="isl", reason="lost", owed=[isp.owed_stop("run1", "isl", 0, 1, False)]) + cli = NodeRecords(store, run_id="", log=lambda m: None) + real = records._create + + def create(key, doc): + made = real(key, doc) + cli.release("b300-1") # released, picked again and lost again in incarnation 1 + records.quarantine("b300-1", island="isl", reason="lost again", owed=[isp.owed_stop("run1", "isl", 1, 1, False)]) + return made + + records._create = create + records.settle("b300-1", run_id="run1", island="isl", incarnation=0) + assert not store.list("fleet/nodes/b300-1/settled/") # the old stop's marker is not left behind + assert [o["incarnation"] for o in records.own_quarantine("b300-1")["owed"]] == [1] + + +def test_a_settle_of_a_stop_the_record_never_listed_leaves_no_marker(tmp_path): + store = DirectoryObjectStore(tmp_path / "store") + records = NodeRecords(store, run_id="run1", log=lambda m: None) + records.quarantine("b300-1", island="isl", reason="lost", owed=[isp.owed_stop("run1", "isl", 0, 1, False)]) + records.settle("b300-1", run_id="run1", island="isl", incarnation=5) + records.settle("b300-2", run_id="run1", island="isl", incarnation=0) # no record at all + assert not store.list("fleet/nodes/b300-1/settled/") and not store.list("fleet/nodes/b300-2/") + + +class _Unread(DirectoryObjectStore): + def read(self, key): + if key.endswith("quarantine.json"): + raise OSError("read refused") + return super().read(key) + + +def test_release_node_reports_a_ledger_that_fails_with_exit_1_and_no_traceback(tmp_path, monkeypatch): + from yeto.launch import ssh_trainer_ledger + + store = DirectoryObjectStore(tmp_path / "store") + NodeRecords(store, run_id="run1", log=lambda m: None).quarantine( + "b300-1", island="isl", reason="lost", owed=[isp.owed_stop("run1", "isl", 0, 1, False)]) + + def broken(**kw): + raise OSError("ledger not writable") + + monkeypatch.setattr(ssh_trainer_ledger, "release_owed", broken) + inv = _inventory(tmp_path, [*islands_spec().nodes, spare(3)]) + said: list[str] = [] + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), + ssh=Cluster([*NAMES, "b300-3"]), objects=store, kill_grace_s=1, say=said.append) == 1 + assert any("stays quarantined" in line and "ledger not writable" in line for line in said) + assert store.read("fleet/nodes/b300-1/quarantine.json") is not None + + +# ------------------------------------------------------------------ REV-920 +def _rollback_unstopped(tmp_path, *, unstopped="b300-3", extra=None): + """b300-1 lost; spare b300-3 takes rank 1; incarnation 1 starts on b300-0 and b300-3, + then its start on b300-2 fails; the stop of incarnation 1 on ``unstopped`` ends rc 1.""" + leases = FakeLeases() + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=extra or [spare(3), spare(4)], leases=leases) + real = cluster.start + + def start(node, script): + if node.name == "b300-2" and "setsid bash -c" in script and cluster._k(script) == 1: + raise RuntimeError("ssh start refused on rank 2") + return real(node, script) + + cluster.start = start + cluster.kill_rc[unstopped] = 1 + assert ops.relaunch(None, "isl") is None + cluster.start = real + return SimpleNamespace(cluster=cluster, ops=ops, spares=spares, store=store, clock=clock, leases=leases) + + +def test_a_spare_whose_rollback_stop_is_not_confirmed_is_lost_owing_that_stop(tmp_path): + run = _rollback_unstopped(tmp_path) + doc = run.spares.records.own_quarantine("b300-3") + assert doc is not None and [(o["island"], o["incarnation"]) for o in doc["owed"]] == [("isl", 1)] + assert doc["lease_holder"] == run.leases.holder_id and "b300-3" in getattr(run.leases, "kept", []) + assert run.spares.records.holder("b300-3") is None # M1: the record keeps every island off it, not a claim + import dataclasses + + sb = dataclasses.replace(islands_spec(), nodes=(b300(4), b300(5), b300(6))) + other, _ = make_spares(tmp_path, sb, [spare(3)]) + pick = isp.pick_spare(other, "isb", list(sb.nodes), {1: "lost"}, ops=run.cluster, + health={"b300-3": (True, "healthy")}) + assert pick.node is None and "quarantined" in pick.skipped["b300-3"] + + +def test_a_lost_rollback_spare_is_pickable_again_once_released(tmp_path): + """REV-920 P1: the spare recovers, release-node runs its owed stop, the island goes down: + another island of the run takes it.""" + import dataclasses + + run = _rollback_unstopped(tmp_path) + run.cluster.kill_rc.clear() + inv = _inventory(tmp_path, [*islands_spec().nodes, spare(3), spare(4)]) + assert isp.release_node_main(inventory=inv, name="b300-3", store=str(tmp_path / "store"), ssh=run.cluster, + objects=run.store, kill_grace_s=1, say=lambda m: None, leases=run.leases) == 0 + run.ops.down("isl") + sb = dataclasses.replace(islands_spec(), nodes=(b300(4), b300(5), b300(6))) + other, _ = make_spares(tmp_path, sb, [spare(3)]) + pick = isp.pick_spare(other, "isb", list(sb.nodes), {1: "lost"}, ops=run.cluster, + health={"b300-3": (True, "healthy")}) + assert pick.node is not None and pick.node.name == "b300-3" + + +def test_a_lost_rollback_spare_keeps_a_ledger_row_until_its_stop_is_confirmed(tmp_path): + """REV-920 P11: the spare's stop of incarnation 1 is in a row of its own; the + incarnation's row closed (its other nodes confirmed); down() leaves the spare's row open; + release-node, its stop confirmed, closes it.""" + run = _rollback_unstopped(tmp_path) + assert "run1/isl-i1-owed-b300-3" in open_rows(tmp_path) and "run1/isl-i1" not in open_rows(tmp_path) + run.ops.down("isl") + assert [r for r in open_rows(tmp_path) if "b300-3" in r] == ["run1/isl-i1-owed-b300-3"] + run.cluster.kill_rc.clear() + inv = _inventory(tmp_path, [*islands_spec().nodes, spare(3), spare(4)]) + assert isp.release_node_main(inventory=inv, name="b300-3", store=str(tmp_path / "store"), ssh=run.cluster, + objects=run.store, kill_grace_s=1, say=lambda m: None, leases=run.leases) == 0 + assert not [r for r in open_rows(tmp_path) if "b300-3" in r] + + +def test_a_failed_start_keeps_its_incarnation_number_and_an_old_node_stops_it_before_the_next(tmp_path): + """REV-920 P2 (M5): the stop of incarnation 1 is not confirmed on b300-0 (it stays an old + node of the island). The next try starts incarnation 2, after stopping 1 on b300-0.""" + run = _rollback_unstopped(tmp_path, unstopped="b300-0") + assert run.spares.records.own_quarantine("b300-3") is None # its stop went through: back in the pool + run.cluster.kill_rc.clear() + run.clock.t += 61 + assert run.ops.relaunch(None, "isl") == 2 + calls = run.cluster.calls + assert calls.index(("kill", "b300-0", 1), calls.index(("kill", "b300-0", 1)) + 1) < calls.index(("start", "b300-0", 2)) + assert "run1/isl-i1" not in open_rows(tmp_path) # stopped on every node now: closed + + +class _SettledUnlisted(DirectoryObjectStore): + def list(self, prefix): + if "/settled/" in prefix: + raise OSError("list refused") + return super().list(prefix) + + +def test_a_settled_listing_failure_leaves_every_stop_owed(tmp_path): + """REV-920 P5 (M3): the markers cannot be listed: the record comes back unfiltered, each + stop counts as owed (each is idempotent), the node stays quarantined at a start, and + release-node asks to be run again later (not --force).""" + store = _SettledUnlisted(tmp_path / "store") + records = NodeRecords(store, run_id="run1", log=lambda m: None) + records.quarantine("b300-1", island="isl", reason="lost", owed=[isp.owed_stop("run1", "isl", 0, 1, False)]) + store.write(NodeRecords.settled_key("b300-1", "run1", "isl", 0), json.dumps( + {"run_id": "run1", "island": "isl", "incarnation": 0}).encode()) # it was settled + doc = records.own_quarantine("b300-1") + assert doc["read_error"] and not doc.get("unreadable") and len(doc["owed"]) == 1 + records.quarantine("b300-1", island="isl", reason="lost again", owed=[isp.owed_stop("run1", "isl", 1, 1, False)]) + raw = json.loads(DirectoryObjectStore(tmp_path / "store").read("fleet/nodes/b300-1/quarantine.json")) + assert [o["incarnation"] for o in raw["owed"]] == [0, 1] # the second quarantine kept the first stop + inv = _inventory(tmp_path, [*islands_spec().nodes, spare(3)]) + said: list[str] = [] + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), + ssh=Cluster([*NAMES, "b300-3"]), objects=store, kill_grace_s=1, say=said.append) == 1 + assert any("again later" in line for line in said) and not any("--force" in line for line in said) + + +def test_a_start_takes_a_node_whose_markers_cannot_be_listed_as_quarantined(tmp_path): + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, health_every_s=0) + s = islands_spec() + store = _SettledUnlisted(tmp_path / "store") + records = NodeRecords(store, run_id="run1", log=lambda m: None) + spares = IslandSpares(pool=(*s.nodes, spare(3)), records=records, resume_probe=lambda: None) + records.quarantine("b300-1", island="isl", reason="lost", owed=[isp.owed_stop("run1", "isl", 0, 1, False)]) + ops.add("isl", s, spares=spares) + assert 1 in ops._quarantined_ranks(ops.islands["isl"]) + + +class _QuarantineUnread(DirectoryObjectStore): + fail = False + + def read(self, key): + if self.fail and key.endswith("quarantine.json"): + raise OSError("read refused") + return super().read(key) + + +def test_a_record_that_cannot_be_read_owes_its_stops_and_is_not_written_over(tmp_path): + """REV-920 P8 (M3): the store fails to read the record: an owed stop is run (not skipped), + a new quarantine refuses to write over it, release-node asks to be run again later.""" + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[]) + assert ops.relaunch(None, "isl") is None + bad = _QuarantineUnread(tmp_path / "store") + spares.records.objects = bad + bad.fail = True + rec, node = ops.islands["isl"], spares.pool[1] + cluster.unreachable.discard("b300-1") + assert ops._still_owed(rec, node, 0) and ops._owes(rec, "b300-1", 0) + ops._run_owed_stop(rec, node, 0, None, what="quarantined node") + assert ("kill", "b300-1", 0) in cluster.calls + with pytest.raises(isp.SpareError, match="not written over"): + spares.records.quarantine("b300-1", island="isl", reason="again") + bad.fail = False + assert json.loads(bad.read("fleet/nodes/b300-1/quarantine.json"))["owed"] # still there + bad.fail = True + inv = _inventory(tmp_path, [*islands_spec().nodes]) + said: list[str] = [] + assert isp.release_node_main(inventory=inv, name="b300-1", store=str(tmp_path / "store"), ssh=cluster, + objects=bad, kill_grace_s=1, say=said.append) == 1 + assert any("again later" in line for line in said) and not any("--force" in line for line in said) + + +def test_a_loss_whose_quarantine_cannot_be_written_keeps_the_claim(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + rec = ops.islands["isl"] + + def refuse(*a, **kw): + raise isp.SpareError("store unavailable") + + spares.records.quarantine = refuse + spares.lost.pop(2, None) + ops._mark_lost(rec, 2, "XID 79") + assert spares.records.holder("b300-2") == "isl" # the run's other islands still cannot take it + + +def test_a_failed_step_after_the_pick_gives_the_spare_back(tmp_path, monkeypatch): + """REV-920 P9 (L2): the new health watches fail after the pick: the spare's claim and + lease go back and the island is on its old nodes.""" + leases = FakeLeases() + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)], leases=leases) + + def broken(spec): + raise RuntimeError("health watch setup failed") + + monkeypatch.setattr(ops, "_health_watches", broken) + assert ops.relaunch(None, "isl") is None + assert store.read("fleet/nodes/b300-3/claim.json") is None and "b300-3" not in leases.holders + assert [n.name for n in ops.islands["isl"].spec.nodes] == NAMES + + +def test_an_owed_stop_elsewhere_ends_before_the_island_starts_on_the_node(tmp_path): + """REV-920 P10 (M4): b300-1, released elsewhere, is a candidate again: the stop of its + old incarnation begins and ends before incarnation 2 starts on it, outside the ops lock.""" + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + assert ops.relaunch(None, "isl") == 1 + cluster.unreachable.discard("b300-1") + store.delete("fleet/nodes/b300-1/quarantine.json") # released elsewhere: no record here, its row open + real, locked = cluster.run, [] + + def run(node, script, *, timeout=300.0): + if node.name == "b300-1" and "kill -TERM" in script and cluster._k(script) == 0: + cluster.calls.append(("begin", "b300-1", 0)) + locked.append(ops._lock._is_owned()) + done = real(node, script, timeout=timeout) + cluster.calls.append(("end", "b300-1", 0)) + return done + return real(node, script, timeout=timeout) + + cluster.run = run + 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) + assert ops.relaunch(None, "isl") == 2 + c = cluster.calls + assert c.index(("begin", "b300-1", 0)) < c.index(("end", "b300-1", 0)) < c.index(("start", "b300-1", 2)) + assert locked == [False] and "run1/isl-i0-owed-b300-1" not in open_rows(tmp_path) + + +def test_two_checks_of_one_candidate_stop_its_old_incarnation_once(tmp_path): + import time as _time + + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + assert ops.relaunch(None, "isl") == 1 + cluster.unreachable.discard("b300-1") + store.delete("fleet/nodes/b300-1/quarantine.json") + real = cluster.run + + def run(node, script, *, timeout=300.0): + if "kill -TERM" in script: + _time.sleep(0.2) + return real(node, script, timeout=timeout) + + cluster.run = run + node = spares.pool[1] + results = [] + threads = [threading.Thread(target=lambda: results.append(isp.close_owed_elsewhere(spares, node, cluster))) + for _ in range(2)] + for t in threads: + t.start() + for t in threads: + t.join(10) + assert len(results) == 2 and all(ok for ok, _why in results) + assert cluster.calls.count(("kill", "b300-1", 0)) == 1 # the second check found its row closed + + +def test_a_candidate_whose_owed_stop_fails_is_passed_over_with_why(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + assert ops.relaunch(None, "isl") == 1 + cluster.unreachable.discard("b300-1") + store.delete("fleet/nodes/b300-1/quarantine.json") + cluster.kill_rc["b300-1"] = 1 + checked = isp.check_candidates(spares, "isl", list(ops.islands["isl"].spec.nodes), {1: "lost"}, ops=cluster) + assert checked["b300-1"][0] is False and "owed stop" in checked["b300-1"][1] + assert "run1/isl-i0-owed-b300-1" in open_rows(tmp_path) + + +def test_release_removes_the_record_before_the_markers(tmp_path): + store = DirectoryObjectStore(tmp_path / "store") + records = NodeRecords(store, run_id="run1", log=lambda m: None) + records.quarantine("b300-1", island="isl", reason="lost", owed=[isp.owed_stop("run1", "isl", 0, 1, False)]) + records.settle("b300-1", run_id="run1", island="isl", incarnation=0) + order, real = [], records._delete + + def delete(key): + order.append(key.rsplit("/", 2)[-2] if "/settled/" in key else key.rsplit("/", 1)[-1]) + real(key) + + records._delete = delete + records.release("b300-1") + assert order == ["quarantine.json", "settled"] + + +def test_a_settle_whose_second_read_fails_removes_its_marker(tmp_path): + store = DirectoryObjectStore(tmp_path / "store") + records = NodeRecords(store, run_id="run1", log=lambda m: None) + records.quarantine("b300-1", island="isl", reason="lost", owed=[isp.owed_stop("run1", "isl", 0, 1, False)]) + real, reads = records._read, [] + + def read(key): + if key.endswith("quarantine.json"): + reads.append(key) + if len(reads) == 1: + raise OSError("read refused") + return real(key) + + records._read = read + with pytest.raises(OSError): + records.settle("b300-1", run_id="run1", island="isl", incarnation=0) + assert not store.list("fleet/nodes/b300-1/settled/") + + +@pytest.mark.parametrize("island", ['is"l', "is$(touch PWNED)l", "is`touch PWNED`l", "is'l"]) +def test_the_owed_stop_trap_expands_nothing_in_a_name(tmp_path, island): + import os + import subprocess + + from yeto.launch.ssh_trainer_island import STATE_DIR + + script = isp.owed_kill_script("run1", island, 0, 5, None) + head = "\n".join(script.splitlines()[:2]) + "\nexit 0\n" # the trap alone: it runs at the exit + assert subprocess.run(["bash", "-n", "-c", head], timeout=30).returncode == 0 + home = tmp_path / "home" + sdir = home / STATE_DIR / "run1" / f"{island}-i0" + sdir.mkdir(parents=True) + (sdir / "pgid").write_text("1\n") + done = subprocess.run(["bash", "-c", head], env={**os.environ, "HOME": str(home)}, cwd=tmp_path, timeout=30, + capture_output=True, text=True) + assert done.returncode == 0, done.stderr + assert not (tmp_path / "PWNED").exists() + assert not (sdir / "pgid").exists() and (sdir / "stopped").exists() + + +def test_a_stale_pick_not_held_by_this_launcher_is_not_released(tmp_path): + """REV-920 L5: the stale pick b300-3's lease is not held by this object (another launcher + of the run holds it): nothing is released, nothing said.""" + 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) + other = NodeLeases(LEASE_STORE, "run1/trainer", identity="bbbb", objects=objects, clock=clock, monotonic=clock) + for n in NAMES: + assert leases.acquire(n).ok + assert other.acquire("b300-3").ok + leases.picks["isl"] = [*NAMES, "b300-3"] + released, lines = [], [] + real = leases.release + leases.release = lambda node: (released.append(getattr(node, "name", node)), real(node)) + cluster = Cluster([*NAMES, "b300-3"]) + ops = make_ops(tmp_path, cluster, clock=clock, health_every_s=0) + ops.log = lines.append + s = dataclasses.replace(islands_spec(), leases=leases) + spares, _ = make_spares(tmp_path, s, [spare(3)]) + ops.add("isl", s, spares=spares) + ops._release_stale_leases(ops.islands["isl"]) + assert released == [] and not [ln for ln in lines if "given back" in ln] + assert other.held() == ["b300-3"] + + +def test_the_trainer_pick_leaves_out_a_node_quarantined_in_the_run_store(tmp_path, monkeypatch): + """REV-920 L4: a node the run's own island quarantined in its run store (the lease store + copy missing, e.g. its write failed) is no candidate of the run's trainer pick.""" + 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() + NodeRecords(DirectoryObjectStore(tmp_path / "store"), run_id="run2", log=lambda m: None).quarantine( + "b300-0", island="isl", reason="lost") + 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) + args = SimpleNamespace(cluster_prefix=f"oc-f-{tmp_path.name}", rl_checkpoint_store=str(tmp_path / "store")) + picked = sti.lease_trainer_nodes(args, [b300(i) for i in range(3)], 2, leases, name="isl", wait_s=0) + assert [n.name for n in picked] == ["b300-1", "b300-2"] + + +# ------------------------------------------------------------------ REV-920b +def test_down_stops_an_earlier_incarnation_an_old_node_did_not_confirm_or_keeps_the_island(tmp_path): + """REV-920b M-a: after a rollback whose stop of incarnation 1 b300-0 did not confirm, + down() stops 1 there first; while it is not confirmed, down() is False and the island keeps + its leases, claims and the row of 1; once confirmed, all of it goes.""" + run = _rollback_unstopped(tmp_path, unstopped="b300-0") + assert 1 in run.ops.islands["isl"].islands.unreleased + before = run.cluster.calls.count(("kill", "b300-0", 1)) + assert run.ops.down("isl") is False + assert run.cluster.calls.count(("kill", "b300-0", 1)) == before + 1 + rec = run.ops.islands["isl"] + assert run.spares.records.holder("b300-0") == "isl" and rec.lock is not None + assert "run1/isl-i1" in open_rows(tmp_path) + run.cluster.kill_rc.clear() + assert run.ops.down("isl") is True + assert run.spares.records.holder("b300-0") is None and rec.lock is None + assert "run1/isl-i1" not in open_rows(tmp_path) + + +def test_a_rollback_with_an_unconfirmed_old_node_keeps_the_incarnation_row_open(tmp_path): + """REV-920b L-c (m01): b300-0 and the spare both leave incarnation 1 unconfirmed: the + spare owes its own row, and the row of 1 stays open for b300-0.""" + leases = FakeLeases() + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3), spare(4)], leases=leases) + real = cluster.start + + def start(node, script): + if node.name == "b300-2" and "setsid bash -c" in script and cluster._k(script) == 1: + raise RuntimeError("ssh start refused on rank 2") + return real(node, script) + + cluster.start = start + cluster.kill_rc.update({"b300-0": 1, "b300-3": 1}) + assert ops.relaunch(None, "isl") is None + rows = open_rows(tmp_path) + assert "run1/isl-i1" in rows and "run1/isl-i1-owed-b300-3" in rows + assert 1 in ops.islands["isl"].islands.unreleased + + +def _refusing(records, *names): + real = records.quarantine + state = {"down": True} + + def quarantine(name, **kw): + if state["down"] and name in names: + raise isp.SpareError("store write refused (503)") + return real(name, **kw) + + records.quarantine = quarantine + return state + + +def test_a_loss_whose_quarantine_the_store_refuses_owes_a_row_and_is_written_once_the_store_is_back(tmp_path): + """REV-920b M-b: _mark_lost with a store that refuses the write: the node owes its stop in a + ledger row, this island does not pick it again, its claim keeps the run's other islands off + it; once the store answers, a check writes the record and gives the claim up.""" + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + store_state = None + rec = ops.islands["isl"] + lines: list[str] = [] + ops.log = lines.append + store_state = _refusing(spares.records, "b300-2") + spares.lost.pop(2, None) + ops._mark_lost(rec, 2, "XID 79") + assert "run1/isl-i0-owed-b300-2" in open_rows(tmp_path) + assert spares.records.holder("b300-2") == "isl" and "b300-2" in spares.pending + assert ops._owes(rec, "b300-2", 0) and ops._still_owed(rec, spares.pool[2], 0) + assert any("CRITICAL" in ln and "holds its claim and owes its stops" in ln for ln in lines) + _c, _g, skipped, _m, _k = isp.spare_candidates(spares, "isl", list(rec.spec.nodes), [1, 2]) + assert "not written to the store yet" in skipped["b300-2"] # this island leaves it out too + store_state["down"] = False + ops._replace_checked(rec) # a check: the record is written now + assert spares.records.own_quarantine("b300-2") is not None and "b300-2" not in spares.pending + assert spares.records.holder("b300-2") is None + + +def test_a_rollback_spare_whose_quarantine_was_refused_is_pickable_once_written_and_released(tmp_path): + """REV-920b M-b / L-c (m04): the rollback spare's quarantine is refused: its claim stays + with isl; the store comes back, down() writes the record and gives the claim up; once its + stop goes through and release-node runs, isb takes it.""" + import dataclasses + + leases = FakeLeases() + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3), spare(4)], leases=leases) + state = _refusing(spares.records, "b300-3") + real = cluster.start + + def start(node, script): + if node.name == "b300-2" and "setsid bash -c" in script and cluster._k(script) == 1: + raise RuntimeError("ssh start refused on rank 2") + return real(node, script) + + cluster.start, cluster.kill_rc["b300-3"] = start, 1 + assert ops.relaunch(None, "isl") is None + cluster.start = real + assert spares.records.own_quarantine("b300-3") is None and spares.records.holder("b300-3") == "isl" + assert "run1/isl-i1-owed-b300-3" in open_rows(tmp_path) + sb = dataclasses.replace(islands_spec(), nodes=(b300(5), b300(6), b300(7))) + other, _ = make_spares(tmp_path, sb, [spare(3)]) + pick = isp.pick_spare(other, "isb", list(sb.nodes), {1: "lost"}, ops=cluster, health={"b300-3": (True, "healthy")}) + assert pick.node is None and "held by island isl" in pick.skipped["b300-3"] + state["down"] = False + assert ops.down("isl") + assert spares.records.own_quarantine("b300-3") is not None and spares.records.holder("b300-3") is None + cluster.kill_rc.clear() + inv = _inventory(tmp_path, [*islands_spec().nodes, spare(3), spare(4)]) + assert isp.release_node_main(inventory=inv, name="b300-3", store=str(tmp_path / "store"), ssh=cluster, + objects=store, kill_grace_s=1, say=lambda m: None, leases=leases) == 0 + pick = isp.pick_spare(other, "isb", list(sb.nodes), {1: "lost"}, ops=cluster, health={"b300-3": (True, "healthy")}) + assert pick.node is not None and pick.node.name == "b300-3" + assert not [r for r in open_rows(tmp_path) if "b300-3" in r] + + +def test_a_confirmed_stop_of_a_node_whose_quarantine_was_refused_owes_nothing_more(tmp_path): + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + rec = ops.islands["isl"] + _refusing(spares.records, "b300-2") + spares.lost.pop(2, None) + ops._mark_lost(rec, 2, "XID 79", answers=True) # still answers: stopped in the background + join_stops(spares) + assert ("kill", "b300-2", 0) in cluster.calls + assert spares.pending["b300-2"]["owed"] == [] and not ops._owes(rec, "b300-2", 0) + assert "run1/isl-i0-owed-b300-2" not in open_rows(tmp_path) + + +def test_a_candidate_whose_ledger_cannot_be_read_is_passed_over(tmp_path, monkeypatch): + """REV-920b L-a (m09): the run's ledger cannot be read: the candidate's owed rows are not + known, so it is not a candidate this round.""" + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + assert ops.relaunch(None, "isl") == 1 + cluster.unreachable.discard("b300-1") + store.delete("fleet/nodes/b300-1/quarantine.json") # released elsewhere, its owed row open + + def broken(self): + raise OSError("ledger unreadable") + + monkeypatch.setattr(ResourceLedger, "open_resources", broken) + ok, why = isp.close_owed_elsewhere(spares, spares.pool[1], cluster) + assert not ok and "the ledger could not be read" in why + assert not [c for c in cluster.calls if c[0] == "kill" and c[1] == "b300-1" and c[2] == 0] + + +def test_a_rollback_whose_only_unconfirmed_stop_is_a_lost_spare_owes_its_incarnation_nowhere_else(tmp_path): + """REV-920b (m02): only the lost spare b300-3 did not confirm the stop of incarnation 1: its + own row and record owe that stop, so the island does not carry 1 as unreleased and down() + stops it on no old node again.""" + run = _rollback_unstopped(tmp_path) + rec = run.ops.islands["isl"] + assert 1 not in rec.islands.unreleased + before = [c for c in run.cluster.calls if c[0] == "kill" and c[2] == 1] + assert run.ops.down("isl") + after = [c for c in run.cluster.calls if c[0] == "kill" and c[2] == 1] + assert after == before + + +def test_an_unhealthy_candidate_does_not_run_its_owed_stops(tmp_path): + """REV-920b (m08): an unhealthy candidate is no candidate: its owed stop is not run in + the checks and its row stays open.""" + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + assert ops.relaunch(None, "isl") == 1 + cluster.unreachable.discard("b300-1") + store.delete("fleet/nodes/b300-1/quarantine.json") # released elsewhere, its owed row open + cluster.sick.add("b300-1") + checked = isp.check_candidates(spares, "isl", list(ops.islands["isl"].spec.nodes), {1: "lost"}, ops=cluster) + assert checked["b300-1"][0] is False and checked["b300-1"][1].startswith("unhealthy") + assert ("kill", "b300-1", 0) not in cluster.calls + assert "run1/isl-i0-owed-b300-1" in open_rows(tmp_path) + + +def test_a_candidate_whose_owed_stop_raises_is_passed_over(tmp_path, monkeypatch): + """REV-920b (m09): the owed stop raises (not a ledger read error): not known whether the + old incarnation still runs there, so the candidate is passed over and its row stays open.""" + from yeto.launch import ssh_trainer_ledger + + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + assert ops.relaunch(None, "isl") == 1 + cluster.unreachable.discard("b300-1") + store.delete("fleet/nodes/b300-1/quarantine.json") + + def boom(row, ops=None, dry_run=False, ssh=None): + raise RuntimeError("ssh agent gone") + + monkeypatch.setattr(ssh_trainer_ledger, "cleanup_release", boom) + ok, why = isp.close_owed_elsewhere(spares, spares.pool[1], cluster) + assert not ok and why.startswith("its owed stops not run (RuntimeError: ssh agent gone") + assert "run1/isl-i0-owed-b300-1" in open_rows(tmp_path) + + +def test_two_refused_quarantines_of_one_node_owe_both_stops(tmp_path): + """REV-920b M-b: a second quarantine of a node whose first one the store refused adds its + stop to the one kept in memory; once written, the record lists both.""" + cluster, ops, spares, store, clock = lost_island(tmp_path, extra=[spare(3)]) + rec = ops.islands["isl"] + state = _refusing(spares.records, "b300-2") + node = spares.pool[2] + for inc in (0, 1): + assert not ops._quarantine(rec, node, reason=f"lost at {inc}", + owed=[isp.owed_stop("run1", "isl", inc, 2, False)]) + assert ops._owes(rec, "b300-2", 0) and ops._owes(rec, "b300-2", 1) + state["down"] = False + ops._flush_pending(rec) + doc = spares.records.own_quarantine("b300-2") + assert sorted(int(o["incarnation"]) for o in doc["owed"]) == [0, 1] diff --git a/yeto/launch/island_spares.py b/yeto/launch/island_spares.py index 8e8f4f6b7..e4b507b0d 100644 --- a/yeto/launch/island_spares.py +++ b/yeto/launch/island_spares.py @@ -51,7 +51,9 @@ from __future__ import annotations +import base64 import json +import shlex import sys import threading import time @@ -62,20 +64,22 @@ from .node_inventory import Node from .node_quarantine import ( # noqa: F401 - the shared names here too + JOURNAL_SUFFIX, QUARANTINE_NAME, RELEASE_NODE_HINT, + RUN_NODES_DIR, SHARED_NODES_DIR, + SPARE_ROLE, describe, release_how, - JOURNAL_SUFFIX, - SPARE_ROLE, shared_quarantined_names, + unreadable, ) -NODES_DIR = "fleet/nodes" # under the run store +NODES_DIR = RUN_NODES_DIR # 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 +RELEASED_NAME = "released.json" # release-node's record of the release (fleet/nodes//; nothing reads it) +SETTLED_DIR = "settled" # fleet/nodes//settled/.json (settled_key): a stop owed no more CLAIM_SCHEMA = "yeto.fleet.node-claim/v1" QUARANTINE_SCHEMA = "yeto.fleet.node-quarantine/v1" WAIT_FIRST_S = 60.0 @@ -436,11 +440,20 @@ def shared_quarantined(self, name: str) -> dict[str, Any] | None: 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)) + ``owed`` leaves out every stop a :meth:`settle` marker says went through. A record the + store fails to read is ``unreadable`` (with ``read_error``); when only its markers cannot + be listed, the record comes back unfiltered (every stop it lists owed) with ``read_error``.""" + try: + doc = self._read(self.key(name, QUARANTINE_NAME)) + except Exception as error: # noqa: BLE001 - unknown is not free + return unreadable(error) if doc is None or not doc.get("owed"): return doc - done = self._settled(name) + try: + done = self._settled(name) + except Exception as error: # noqa: BLE001 - every listed stop counts as owed (each is idempotent) + return {**doc, "read_error": True, + "settled_unread": f"its settled stops not listed: {type(error).__name__}: {error}"[:300]} if not done: return doc return {**doc, "owed": [o for o in doc["owed"] if _owed_key(o) not in done]} @@ -468,9 +481,16 @@ def quarantine(self, name: str, *, island: str, reason: str, owed: Sequence[Mapp """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 {} + if earlier.get("unreadable") and earlier.get("read_error"): # its owed stops would be lost + raise SpareError(f"node {name}: its quarantine record could not be read ({earlier.get('reason')}); " + "not written over") 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)]} + if earlier.get("unreadable"): # a broken record: what it held is not known + doc["earlier_unreadable"] = str(earlier.get("reason") or "")[:300] + self.log(f"[launcher] WARN: node {name}: its quarantine record was broken ({earlier.get('reason')}); " + "written anew, the stops it listed are not known (check the node for the run's containers)") holder = lease_holder or earlier.get("lease_holder") if holder: doc["lease_holder"] = str(holder) @@ -489,33 +509,48 @@ def _share(self, name: str, doc: Mapping[str, Any]) -> None: 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()}) + create), never into the quarantine record, so a release-node that removes the record + meanwhile is never undone, here or in the lease store. The record is read again after + the marker is created: once it no longer lists that stop (released meanwhile, maybe + quarantined anew), the marker is removed, so none is left behind. No clock is + compared: a launcher and a release-node whose clocks disagree settle alike. A node whose + record never listed that stop gets no marker either.""" + mine = (str(run_id), str(island), int(incarnation)) + + def lists() -> bool: + doc = self._read(self.key(name, QUARANTINE_NAME)) + return (doc is not None and not doc.get("unreadable") + and any(_owed_key(o) == mine for o in doc.get("owed") or ())) + + marker = self.settled_key(name, run_id, island, incarnation) + if not self._create(marker, {"run_id": mine[0], "island": mine[1], "incarnation": mine[2], + "at": self.wall()}): + return # settled already + try: + listed = lists() + except BaseException: # not known whether the record still lists it: no marker left behind + self._delete(marker) + raise + if not listed: + self._delete(marker) @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" + """``fleet/nodes//settled/...json``, each field urlsafe base64 + (no ``.`` in it): two stops never share a marker, whatever their names hold.""" + parts = (str(run_id), str(island), str(int(incarnation))) + enc = ".".join(base64.urlsafe_b64encode(p.encode()).decode().rstrip("=") for p in parts) + return f"{NODES_DIR}/{name}/{SETTLED_DIR}/{enc}.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)) + """Remove the node's quarantine (run store and lease store) and its settle markers; a + ``released.json`` (who, when) stays in the run store. Raises when the store fails.""" + self._write(self.key(name, RELEASED_NAME), {"node": name, "run": self.run_id, "at": self.wall()}) + self._delete(self.key(name, QUARANTINE_NAME)) # first: a settle from now on removes its own marker 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)) + for key in self._list(f"{NODES_DIR}/{name}/{SETTLED_DIR}/"): + self._delete(key) def _owed_key(row: Mapping[str, Any]) -> tuple[str, str, int]: @@ -539,10 +574,18 @@ def owed_kill_script(run_id: str, island: str, incarnation: int, grace_s: int, c paths = remote_paths(run_id, island, int(incarnation)) pinned = _pin_state_home(paths) - pid, sdir = pinned["pid"], pinned["dir"] + var = "$" + STATE_HOME_VAR + + def word(path: str) -> str: # the state home expands at the trap, the rest is literal + if path.startswith(var): + return f'"{var}"' + shlex.quote(path[len(var):]) + return shlex.quote(path) + + sdir = word(pinned["dir"]) + body = (f"rc=$?; if [ $rc -eq 0 ] && [ -d {sdir} ]; then rm -f {word(pinned['pid'])}; " + f": > {word(pinned['dir'] + '/' + STOPPED_MARKER)}; fi; exit $rc") 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" + f"trap {shlex.quote(body)} EXIT\n" # one word: a name with quotes, $(...) or `...` expands nothing + kill_script(paths, int(grace_s), container=container or None)) @@ -604,7 +647,11 @@ def release_node(records: NodeRecords, node: Node, ssh: Any, *, kill_grace_s: in 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) + try: + records.release(node.name) + except Exception as error: # noqa: BLE001 - reported (exit 1): its record may stay, run it again + return False, (f"node {node.name}: its owed stops ran and its lease is given up, but its quarantine record " + f"could not be removed ({type(error).__name__}: {error}); run release-node again") 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)) @@ -694,10 +741,15 @@ def release_node_main(*, inventory: str, name: str, store: str, ssh: Any = None, 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) + doc = records.quarantined(name) # a store that fails to read: unreadable (needs --force) if doc is None: say(f"[yeto] node {name} is not quarantined in {store}") return 0 + if doc.get("read_error"): # the store did not answer: nothing is known, nothing is forced + say(f"[yeto] node {name}: its quarantine records could not be read " + f"({doc.get('settled_unread') or doc.get('reason')}): the store did not answer; run " + "`yeto cluster release-node` again later") + return 1 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") @@ -740,7 +792,10 @@ def release_node_main(*, inventory: str, name: str, store: str, ssh: Any = 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) + try: + ok, message = release_node(records, node, ssh, kill_grace_s=kill_grace_s, leases=leases, probe=probe) + except Exception as error: # noqa: BLE001 - a store or ledger failure: reported, no traceback + ok, message = False, f"node {name}: release failed ({type(error).__name__}: {error})" say(f"[yeto] {message}" if ok else f"[yeto] node {name} stays quarantined: {message}") return 0 if ok else 1 @@ -840,6 +895,9 @@ class IslandSpares: # (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 + # node -> the quarantine (island, reason, owed, lease_holder) the store refused: kept out of + # this island's picks and owing its stops here until the record is written (each check tries) + pending: dict[str, dict[str, Any]] = field(default_factory=dict) waiting: bool = False limited: bool = False # the replacement limit was reported wait_s: float = 0.0 @@ -987,7 +1045,10 @@ def spare_candidates(spares: IslandSpares, island: str, current: Sequence[Node], 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: + if node.name in spares.pending: # its record not written yet: this launcher keeps it out + skipped[node.name] = (f"quarantined ({str(spares.pending[node.name].get('reason') or '')[:120]}; " + "its record not written to the store yet)") + elif (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, " @@ -1014,7 +1075,9 @@ def check_candidates(spares: IslandSpares, island: str, current: Sequence[Node], 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`).""" + (checked before), until ``need`` pass. Node name -> ``(ok, why)`` (:func:`node_check`). + A healthy candidate's open owed stops (:func:`close_owed_elsewhere`) run here too; one + whose stop fails is not a candidate this round (``why`` says so).""" 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}} @@ -1023,8 +1086,12 @@ def check_candidates(spares: IslandSpares, island: str, current: Sequence[Node], 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]) + ok, why = node_check(node, ops, multi=multi, env=spares.job_env) + if ok: # the stops it owes from a release elsewhere, before any island starts on it + ok, owed_why = close_owed_elsewhere(spares, node, ops) + why = why if ok else owed_why + checked[node.name] = (ok, why) + passed += bool(ok) return checked @@ -1038,7 +1105,9 @@ def pick_spare(spares: IslandSpares, island: str, current: Sequence[Node], lost: 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.""" + :func:`unpick` gives it back. A claim whose lease step fails (refused, or the lease store + raised) is given back before the next candidate is tried. The stops a candidate still + owes from a release elsewhere ran in :func:`check_candidates`, outside the ops lock.""" candidates, group, skipped, multi, keep = spare_candidates(spares, island, current, lost, chosen=chosen) unchecked: list[str] = [] while True: @@ -1064,7 +1133,12 @@ def pick_spare(spares: IslandSpares, island: str, current: Sequence[Node], lost: skipped[node.name] = f"held by island {held}" continue if spares.leases is not None: - lease = spares.leases.acquire(node) + try: + lease = spares.leases.acquire(node) + except Exception as error: # noqa: BLE001 - its claim given back, the next candidate tried + spares.records.unclaim(node.name, island) + skipped[node.name] = f"lease not taken ({type(error).__name__}: {error})"[:300] + continue 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 " @@ -1074,27 +1148,51 @@ def pick_spare(spares: IslandSpares, island: str, current: Sequence[Node], lost: 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.""" +_OWED_LOCKS: dict[tuple[str, str], threading.Lock] = {} # (run, node): one owed stop at a time +_OWED_LOCKS_GUARD = threading.Lock() + + +def _owed_lock(run_id: str, node: str) -> threading.Lock: + with _OWED_LOCKS_GUARD: + return _OWED_LOCKS.setdefault((str(run_id), str(node)), threading.Lock()) + + +def close_owed_elsewhere(spares: IslandSpares, node: Node, ops: Any) -> tuple[bool, str]: + """A candidate with no quarantine record (a release-node elsewhere, a ``--force`` over a + broken record, or a run store kept in memory) and open owed ledger rows of this run: the + stops they name run on it now (SSH; no ops lock), and each row closes (``released + elsewhere``) only once its stop went through, so the node is billed once and nothing of + the old incarnation runs when an island starts there. One stop per node at a time (two + islands' checks of one candidate stop it once). ``(ok, why)``: ok when no row is left open.""" from . import ssh_trainer_ledger # noqa: PLC0415 + failed: list[str] = [] + def stopped(row: Any) -> bool: ok, action, _ = ssh_trainer_ledger.cleanup_release(row, ssh=ops) if not ok: + failed.append(f"{row.id}: {action}") 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) + run_id = spares.records.run_id + try: + with _owed_lock(run_id, node.name): + closed = ssh_trainer_ledger.release_owed_elsewhere(run_id=run_id, node=node.name, stop=stopped, + strict=True) + except ssh_trainer_ledger.LedgerUnread as error: # its owed rows not known: owed, not a candidate now + return False, f"the ledger could not be read ({error})"[:300] + except Exception as error: # noqa: BLE001 - not known whether it still runs: not a candidate now + return False, f"its owed stops not run ({type(error).__name__}: {error})"[:300] 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)") + if failed: + return False, ("an owed stop of an earlier incarnation failed there (" + "; ".join(failed) + ")")[:300] + return True, "no owed stop left" def unpick(spares: IslandSpares, island: str, node: Node) -> None: diff --git a/yeto/launch/node_quarantine.py b/yeto/launch/node_quarantine.py index de5926c09..b1cb47ffb 100644 --- a/yeto/launch/node_quarantine.py +++ b/yeto/launch/node_quarantine.py @@ -18,6 +18,7 @@ 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 +RUN_NODES_DIR = "fleet/nodes" # under a run store: fleet/nodes//quarantine.json (island_spares) RELEASE_NODE_HINT = "run `yeto cluster release-node `" @@ -37,13 +38,19 @@ 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).""" +def run_key(name: str) -> str: + return f"{RUN_NODES_DIR}/{name}/{QUARANTINE_NAME}" + + +def _listed(shared: Any, base: str = SHARED_NODES_DIR) -> set[str]: + """The nodes with a quarantine record under ``base`` (``nodes`` in a lease store, + ``fleet/nodes`` in a run store); raises when the store does not list.""" out = set() - for key in shared.list(f"{SHARED_NODES_DIR}/"): # nodes//quarantine.json only + depth = base.count("/") + 1 + for key in shared.list(f"{base}/"): # //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]) + if len(parts) == depth + 2 and "/".join(parts[:depth]) == base and parts[-1] == QUARANTINE_NAME: + out.add(parts[depth]) return out @@ -58,15 +65,22 @@ def shared_quarantined_names(shared: Any) -> set[str]: 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: +def unreadable(error: BaseException | str) -> dict[str, Any]: + """The record of a node whose quarantine could not be read (the store failed): it counts + as quarantined.""" + what = error if isinstance(error, str) else f"{type(error).__name__}: {error}" + return {"unreadable": True, "read_error": True, "reason": f"quarantine record unreadable: {what}"[:300]} + + +def read_record(shared: Any, name: str, *, key: str | None = None) -> dict[str, Any] | None: + """Node ``name``'s quarantine record in the lease store (``key``: another place, e.g. + :func:`run_key` in a run 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)) + raw = shared.read(key or 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]} + return unreadable(error) if raw is None: return None try: @@ -100,6 +114,50 @@ def shared_quarantines(shared: Any, names: Iterable[str], *, return out +def run_store_quarantines(objects: Any, names: Iterable[str], *, + log: Callable[[str], None] | None = None) -> dict[str, dict[str, Any]]: + """The quarantine records of ``names`` in a run store (``fleet/nodes//quarantine.json``, + this run's islands): name -> record, as :func:`shared_quarantines` reads a lease store. + 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 objects is None or not names: + return {} + try: + listed = _listed(objects, RUN_NODES_DIR) & names + except Exception as error: # noqa: BLE001 - each node read below + (log or (lambda m: None))(f"[launcher] WARN: the run 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(objects, name, key=run_key(name)) + if doc is not None: + out[name] = doc + return out + + +def trainer_pick_excluded(names: Iterable[str], *, lease_objects: Any = None, run_objects: Any = None, + assigned: Iterable[str] = (), log: Callable[[str], None] | None = None, + ) -> tuple[set[str], dict[str, dict[str, Any]], str | None]: + """What a trainer pick among ``names`` leaves out: ``(excluded, quarantines, note)``. + + ``excluded``: ``assigned`` (nodes this process gave other islands already) and every + node quarantined in the lease store (``lease_objects``: any run's, :func:`shared_quarantines`) + or in the run store (``run_objects``: this run's, :func:`run_store_quarantines`); an + unreadable record counts. ``quarantines``: name -> record; ``note``: + :func:`quarantine_note` (None: none). The launch's trainer pick + (``ssh_trainer_island.lease_trainer_nodes``) calls it with the run's ``NodeLeases`` + (``lease_objects=leases.objects``, ``assigned=leases.assigned``, ``run_objects``: the + object API of the run's ``--rl-checkpoint-store``, ``ssh_trainer_island._run_store_objects``); + a prediction of that pick calls it with the same arguments.""" + names = set(names) + docs = dict(shared_quarantines(lease_objects, names, log=log)) + for name, doc in run_store_quarantines(run_objects, names, log=log).items(): + docs.setdefault(name, doc) + return set(assigned) | set(docs), docs, quarantine_note(docs) + + def describe(name: str, doc: Mapping[str, Any]) -> str: """`` by run R island I (reason)`` of a quarantine record.""" if doc.get("unreadable"): diff --git a/yeto/launch/ssh_resident.py b/yeto/launch/ssh_resident.py index ad9696a3b..5ab01434d 100644 --- a/yeto/launch/ssh_resident.py +++ b/yeto/launch/ssh_resident.py @@ -490,7 +490,7 @@ def _quarantined_ranks(self, rec: _Island) -> dict[int, str]: 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 + if doc is not None and doc.get("unreadable") and doc.get("read_error"): # the store did not answer 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 @@ -570,7 +570,9 @@ def relaunch(self, task: Any, name: str) -> int | None: return None def down(self, name: str) -> bool: - """Release the island's current incarnation; True once every node confirmed it.""" + """Release the island's current incarnation, and any earlier one not confirmed stopped + on a node; True once every node confirmed them (else its leases, claims and ledger + rows are kept).""" rec = self.islands.get(name) if rec is None: return True @@ -579,8 +581,15 @@ def down(self, name: str) -> bool: return True self._join_owed_retries(rec) with self._lock: + self._flush_pending(rec) + lost = self._lost_names(rec) + # an earlier incarnation not confirmed stopped on a node (a failed start on spares): + # stopped first; not confirmed, the island stays held (leases, claims, its ledger row) + earlier_ok = True + for k in sorted(set(rec.islands.unreleased) - {int(rec.incarnation)}): + earlier_ok &= rec.islands.release_incarnation(k, skip=lost, owed=frozenset()) # 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)) + ok = self._release(rec, rec.incarnation, skip=lost) and earlier_ok 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) @@ -824,8 +833,13 @@ def _mark_lost(self, rec: _Island, rank: int, reason: str, *, answers: bool = Fa 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) + if self._quarantine(rec, node, reason=reason, owed=owed, lease_holder=holder): + sp.records.unclaim(node.name, rec.name) # not written: the claim keeps the run's islands off it + elif inc is not None: # no record to owe it in: its stop is in a ledger row of its own now + from . import ssh_trainer_ledger # noqa: PLC0415 + + ssh_trainer_ledger.record_owed(run_id=rec.spec.run_id, island=rec.name, incarnation=inc, node=node, + rank=rank, docker=rec.spec.docker, kill_grace_s=self.kill_grace_s) 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: @@ -855,10 +869,21 @@ def _stop_lost(self, rec: _Island, rank: int, node: Any, inc: int) -> None: 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).""" + if self._pending_owes(rec, node.name, inc): + return True doc = rec.spares.records.own_quarantine(node.name) + if doc is not None and doc.get("unreadable"): # not known: owed (a stop is idempotent) + return True return any(str(o.get("island")) == rec.name and int(o.get("incarnation", -1)) == int(inc) for o in (doc or {}).get("owed") or ()) + @staticmethod + def _pending_owes(rec: _Island, name: str, inc: int) -> bool: + """A quarantine the store refused (``spares.pending``) lists that stop of ``name``.""" + held = rec.spares.pending.get(name) + return held is not None and any(str(o.get("island")) == rec.name and int(o.get("incarnation", -1)) == int(inc) + for o in held.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 @@ -885,6 +910,10 @@ def _run_owed_stop(self, rec: _Island, node: Any, inc: int, container: str | Non 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 + held = sp.pending.get(node.name) + if held is not None: # a quarantine not written yet owes it no more either + held["owed"] = [o for o in held.get("owed") or () + if not (str(o.get("island")) == rec.name and int(o.get("incarnation", -1)) == int(inc))] 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) @@ -896,6 +925,116 @@ def _run_owed_stop(self, rec: _Island, node: Any, inc: int, container: str | Non "nothing for it (it stays quarantined)") return True + def _next_incarnation(self, rec: _Island) -> int: + """One past the newest incarnation the island ran or tried (its jobs journal): a start + that failed after it was recorded keeps its number, its state dirs and its ledger row.""" + used = [int(k) for k in read_jobs(self.jobs_path(rec.name))] + if rec.incarnation is not None: + used.append(int(rec.incarnation)) + return max(used) + 1 if used else 0 + + def _roll_back(self, rec: _Island, picks: dict[int, Any], nxt: int, error: Any, old_spec: Any, + old_islands: Any, old_health: Any) -> None: + """A start on spares failed: incarnation ``nxt`` is stopped where it began; a spare + whose stop is not confirmed is lost (:meth:`_quarantine_unstopped`), the others go back + to the pool (a spare named in the error is quarantined); the island is back on its old + nodes, which remember an incarnation not stopped on every node.""" + from . import island_spares as isp # noqa: PLC0415 + from . import ssh_trainer_ledger # noqa: PLC0415 + + sp = rec.spares + new_islands = rec.islands if rec.islands is not old_islands else None + unstopped: frozenset[str] = frozenset() + if new_islands is not None and str(nxt) in read_jobs(self.jobs_path(rec.name)) \ + and not new_islands.release_incarnation(nxt): + unstopped = new_islands.unconfirmed.get(int(nxt), frozenset()) + lost = set() + for rank, node in sorted(picks.items()): + if node.name in unstopped: # it may still run incarnation nxt: lost, owing that stop + self._quarantine_unstopped(rec, node, rank, nxt, error) + lost.add(node.name) + continue + isp.unpick(sp, rec.name, node) + if node.name in str(error): + self._quarantine(rec, node, reason=f"its start as a spare failed: {error}", + lease_holder=self._lease_holder(sp)) + if new_islands is not None: + if unstopped and set(unstopped) <= lost: # the rest confirmed: each lost spare owes its own row + ssh_trainer_ledger.record("released", run_id=rec.spec.run_id, island=rec.name, incarnation=nxt) + new_islands.unreleased.discard(int(nxt)) + old_islands.unreleased |= set(new_islands.unreleased) + rec.spec, rec.islands, rec.health = old_spec, old_islands, old_health + try: + self._record_nodes(rec) # back to the nodes it runs on + except Exception as warn: # noqa: BLE001 - the next pick records them again + self.log(f"[launcher] WARN: {rec.name}: its lease record not put back ({warn})") + + def _quarantine(self, rec: _Island, node: Any, **kw: Any) -> bool: + """``NodeRecords.quarantine``; False when the store refused it (e.g. a record it could + not read, whose owed stops would be written over): the quarantine is kept in memory + (``spares.pending``: out of this island's picks, its stops owed), the caller keeps the + node's claim (the run's other islands), and each check writes it again + (:meth:`_flush_pending`).""" + sp = rec.spares + try: + sp.records.quarantine(node.name, island=rec.name, **kw) + return True + except Exception as error: # noqa: BLE001 - kept in memory, written again at each check + held = sp.pending.get(node.name) or {} + sp.pending[node.name] = {**held, **kw, "owed": [*(held.get("owed") or ()), *map(dict, kw.get("owed") or ())]} + self.log(f"[launcher] CRITICAL: {rec.name}: node {node.name} is not quarantined in the store ({error}); " + "this launcher keeps it out of its picks, holds its claim and owes its stops, and writes " + "the record again at each check") + return False + + def _flush_pending(self, rec: _Island) -> None: + """Write the quarantines the store refused before (:meth:`_quarantine`); once one is + written, the node's claim is given up (its record keeps every island off it).""" + sp = rec.spares + if sp is None or not sp.pending: + return + for name, kw in list(sp.pending.items()): + try: + sp.records.quarantine(name, island=rec.name, **kw) + except Exception as error: # noqa: BLE001 - tried again at the next check + self.log(f"[launcher] {rec.name}: the quarantine of {name} still not written ({error})") + continue + sp.pending.pop(name, None) + sp.records.unclaim(name, rec.name) # a lost node or a lost spare: its record holds it now + self.log(f"[launcher] {rec.name}: the quarantine of {name} is written to the store now") + + @staticmethod + def _lease_holder(sp: Any) -> str | None: + """Who holds the spares' cross-run leases (a quarantine names it, so release-node ends it).""" + from .island_spares import lease_holder_id # noqa: PLC0415 + + return lease_holder_id(sp.leases) if sp.leases is not None else None + + def _quarantine_unstopped(self, rec: _Island, node: Any, rank: int, incarnation: int, error: Any) -> None: + """A spare whose start failed and whose stop of that incarnation is not confirmed: it + is lost, as a lost node is: quarantined with the stop it owes (the record keeps every + island of every run off it), that stop in a ledger row of its own (priced as that node, + open until the stop is confirmed), its claim given up and its lease kept.""" + from . import ssh_trainer_ledger # noqa: PLC0415 + from .island_spares import owed_stop # noqa: PLC0415 + + sp = rec.spares + if self._quarantine(rec, node, + reason=f"its start as a spare failed ({error}) and its stop is not confirmed", + owed=[owed_stop(self.run_id, rec.name, incarnation, rank, rec.spec.docker)], + lease_holder=self._lease_holder(sp)): + sp.records.unclaim(node.name, rec.name) + ssh_trainer_ledger.record_owed(run_id=rec.spec.run_id, island=rec.name, incarnation=incarnation, node=node, + rank=rank, docker=rec.spec.docker, kill_grace_s=self.kill_grace_s) + keep = getattr(sp.leases, "keep_all", None) + if keep is not None: + try: + keep(nodes=[node]) + except Exception as warn: # noqa: BLE001 - the quarantine still keeps the islands off it + self.log(f"[launcher] WARN: {rec.name}: the lease of {node.name} not kept ({warn})") + self.log(f"[launcher] CRITICAL: {rec.name}: spare {node.name} may still run incarnation {incarnation} (its stop " + "is not confirmed): it is quarantined and owes that stop") + 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 @@ -1003,6 +1142,8 @@ def _relaunch_with_spares(self, rec: _Island) -> int | None: 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.""" + with self._lock: + self._flush_pending(rec) # quarantines the store refused before 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]] = {} @@ -1076,8 +1217,13 @@ def _replace(self, rec: _Island, health: dict[str, tuple[bool, str]] | None = No 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) + try: + pick = isp.pick_spare(sp, rec.name, current, sp.lost, ops=self.ops, chosen=list(picks.values()), + health=health) + except BaseException: # the picks so far are not taken: their claims and leases go back + for node in picks.values(): + isp.unpick(sp, rec.name, node) + raise if pick.node is None: for node in picks.values(): isp.unpick(sp, rec.name, node) @@ -1091,36 +1237,34 @@ def _replace(self, rec: _Island, health: dict[str, tuple[bool, str]] | None = No f"{sp.wait_s:.0f} s") return None picks[rank] = pick.node - nxt = 0 if rec.incarnation is None else rec.incarnation + 1 + nxt = self._next_incarnation(rec) # never one a failed start used (its dirs, its ledger row) 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}") + self._quarantine(rec, node, reason=f"cannot take a node's place: {error}", + lease_holder=self._lease_holder(sp)) 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: + new_islands = self._islands_for(rec, new_spec) + # an earlier incarnation not confirmed stopped on a node (a failed start): stopped + # there first (SshTrainerIslands._stop_unreleased), never started over + new_islands.unreleased |= set(old_islands.unreleased) + rec.spec, rec.islands = new_spec, new_islands + 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 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 + self._roll_back(rec, picks, nxt, error, old_spec, old_islands, old_health) sp.nodes.pop(str(nxt), None) sp.save() sp.wait(now, f"the start on the spare node(s) failed: {error}", wall=wall) @@ -1220,9 +1364,13 @@ def _release(self, rec: _Island, incarnation: int, *, skip: frozenset[str] = fro 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).""" + if self._pending_owes(rec, name, incarnation): + return True doc = rec.spares.records.own_quarantine(name) if doc is None: return False + if doc.get("unreadable"): # not known: owed (its own row; a stop is idempotent) + return True return any(str(o.get("island")) == rec.name and int(o.get("incarnation", -1)) == int(incarnation) for o in doc.get("owed") or ()) diff --git a/yeto/launch/ssh_trainer_island.py b/yeto/launch/ssh_trainer_island.py index 344c2d1d6..4ecea74bd 100644 --- a/yeto/launch/ssh_trainer_island.py +++ b/yeto/launch/ssh_trainer_island.py @@ -1592,12 +1592,11 @@ def stop() -> str | 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 + from .node_quarantine import trainer_pick_excluded - 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) + excluded, _docs, note = trainer_pick_excluded( # an unreadable record counts as one + by_name, lease_objects=getattr(leases, "objects", None), run_objects=_run_store_objects(args), + assigned=leases.assigned, log=lambda line: print(line, file=sys.stderr, flush=True)) 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) @@ -1606,7 +1605,7 @@ def log(line: str) -> None: try: picked = pick_nodes(list(trainers), need, leases, wait_s=limit, prefer=recorded, stop=stop, - excluded=set(leases.assigned) | quarantined, place=place, log=log) + excluded=excluded, place=place, log=log) except NodeLeased as error: raise SshIslandError(f"ssh: island {key}: {error}" + (f"; {note}" if note else "")) from None leases.picks[key] = [n.name for n in picked] @@ -1618,6 +1617,21 @@ def log(line: str) -> None: return tuple(picked) +def _run_store_objects(args: Any) -> Any: + """The object API of the run's ``--rl-checkpoint-store``, where its islands quarantine + lost nodes (``fleet/nodes//quarantine.json``); None: none, or no object API here.""" + store = getattr(args, "rl_checkpoint_store", None) + if not store: + return None + try: + from .island_lifecycle import store_objects # noqa: PLC0415 + from .store_env import store_client_environ # noqa: PLC0415 + + return store_objects(store, store_client_environ(args)) + except Exception: # noqa: BLE001 - the lease store's records still hold every quarantine + return None + + _TRAINER_LEASES: dict[tuple[str, str], Any] = {} # (lease store, holder): one per process and run diff --git a/yeto/launch/ssh_trainer_ledger.py b/yeto/launch/ssh_trainer_ledger.py index 6144a2d39..a6485e180 100644 --- a/yeto/launch/ssh_trainer_ledger.py +++ b/yeto/launch/ssh_trainer_ledger.py @@ -117,19 +117,26 @@ def release_owed(*, run_id: str, island: str, incarnation: int, node: str) -> tu return OWED_RELEASED, str(ledger.path) -def release_owed_elsewhere(*, run_id: str, node: str, stop: Any = None) -> list[str]: +class LedgerUnread(RuntimeError): + """The run's ledger could not be read (:func:`release_owed_elsewhere` with ``strict``).""" + + +def release_owed_elsewhere(*, run_id: str, node: str, stop: Any = None, strict: bool = False) -> 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.""" + returns True. Returns the rows closed. A ledger that cannot be read closes nothing; with + ``strict`` it raises :class:`LedgerUnread` (its rows are not known; a missing file has none).""" 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 + except Exception as error: # noqa: BLE001 - no ledger: nothing billed here + if strict: + raise LedgerUnread(f"{type(error).__name__}: {error}") from error return [] closed = [] for row in rows: