diff --git a/docs/OWN_CLUSTERS.md b/docs/OWN_CLUSTERS.md index a7766513a..57e401047 100644 --- a/docs/OWN_CLUSTERS.md +++ b/docs/OWN_CLUSTERS.md @@ -930,3 +930,167 @@ example: When it falls back to the default, the line names the closest records and why they do not fit. A configuration that names its image prints nothing new and runs exactly as before. + +## Islands that lag, join or leave + +A fleet of `ssh:` trainer islands on your own machines uses the same fleet mechanisms as any +other island fleet ([FLEET_TRAINER_ISLANDS.md](FLEET_TRAINER_ISLANDS.md)). This section +covers what is specific to `ssh:` islands: how a slow or stuck island is reported, and what +happens when one leaves. + +### An island that lags + +An island can fall behind or stop pushing while its process and its connection stay up: a +slow node, a hung collective, a trainer that waits on something. The syncer does not wait +for it. When a round's quorum deadline passes, the syncer merges the pushes that arrived and +records the silent island as absent. Later rounds do not wait for it either. Once the island +delivers again, its late push is carried into a later round with a discount, or refused when +it lags past `--rl-sync-max-base-lag`. The island then catches up to the newest merged +weights and answers rounds again. The other islands keep merging the whole time. + +The island's fleet controller reports such an island. It reads the syncer's merges, and +when none of the island's pushes was merged in `N` merge cycles it writes: + +- `island_straggler` in the launch's `fleet.jsonl`, with `missed_cycles`, `merges`, + `fragments`, `last_merged_step`, `newest_step`, `absent` and `action`; +- the same fields under `straggler` in the island's record (`fleet/trainers//state.json`, + shown by `yeto island status`). + +A merge cycle is one outer step of every fragment, so with 4 fragments and `N = 3` the +island is reported after 12 merges without it. A push the syncer refused does not count as +merged. Counting starts when the island joins the syncer: + +- A launch counts only what the syncer records after the launch started: it reads each + syncer tape from its end at the launch's start. A relaunched or moved island's new launch + never counts the merges an earlier launch of it missed. No clock is compared for that, + so a syncer host whose clock is off is counted as usual. Only a syncer tape found later + is read from its start; there, records stamped more than 10 minutes before the launch + started are skipped (the clocks may differ up to 10 minutes before it does). +- An island also counts as joined once a merge lists it `absent`: the syncer expects it. An + island that a restarted launcher adopted joined before that launcher started, and is + counted this way. +- Only the island's controller restarts the count. When the island stops running (its + controller relaunches it, or it is stopped), its count starts again once it runs again: at + its next join after a relaunch, so the time it takes to start is not counted. The same + launch back from recovering is counted again at once. +- A new launch catches up before it pushes: a large model's catch-up can take many merge + cycles. A new launch is an island relaunched by its controller (on new machines, on a spare + node, after a move) or a new island whose join the controller read. It is not counted until + its first push is merged, for at most the controller's recover timeout + (`--recover-timeout`, counted from when the controller holds the new launch running; 20 + minutes when relaunch is off: `--no-island-relaunch` or `--modal-retries 0`). Once + a push of it is merged, it is counted as usual. If none is merged by the end of the recover + timeout, it is counted from then on and reported `N` merge cycles later; its report's + `reason` says that the catch-up grace ran out. An island that a restarted launcher adopted + is not a new launch and has no grace. Each launch gets the grace once; a reconnect's join + neither starts it nor extends it. +- A reconnect of the same trainer, or a syncer that takes over, writes a new join to the + syncer's tape. That join keeps the count and the report: an island whose link keeps + dropping and that never delivers is still reported. + +The report is written once per stretch. `island_straggler_cleared` closes the stretch, and its +`reason` says why: a push of the island is merged again, it is `recovering`, it was +`relaunched` (running again as a new launch), it was stopped or removed (island STOP), it +is no longer running, or `controller restarted`. The last one is written by a launcher that +starts, or adopts the island, while its record still holds a report from an earlier +launcher; the new launcher then judges the island again. If that record does not read, it +is read again at each poll until it does. The record's `straggler` is set back to `null` at +the same time. + +The dashboard shows both events in its event stream. While the island is reported, its +trainer card carries a `straggler` badge and its row in "Islands now" says `straggler`. + +`action` is what the controller does about it. The default is `wait`: nothing is stopped or +relaunched, because the syncer already merges without the island. A lost or unhealthy node +is handled by the island's own launch, not by this report. + +An island that loses a node (see [Spare nodes](#spare-nodes)) is recovering, not running. The +poll that finds the loss clears its report (`recovering`), and the island is not counted while +it waits for a spare. On the spare it is a new launch: it is not counted until its first push +is merged, for at most its recover timeout from when it runs on the spare, then as above. + +Set `N` in `fleet.trainer_argv`, so every island launch gets the same value: + +```json +"trainer_argv": ["...", "--rl-island-straggler-cycles", "3"] +``` + +`3` is the default. `0` turns the report off. The value must be a whole number of 0 or more; +`yeto launch --dry-run` refuses anything else. + +The controller reads the syncer's tape in one of two places: + +- from the syncer's own file, when the syncer runs on the same host as the controller + (`--controller head`); +- otherwise, in a fleet launched island by island (`fleet.launch: per_island`), from its + copy in the run store, `tapes/syncer//.jsonl`. The syncer launch + uploads it every 30 s (`YETO_RL_TAPE_UPLOAD_S`) when `--rl-checkpoint-store` is an + `s3://` store. Each island launch reads it every 30 s. Its first read keeps the end of + every syncer incarnation there. No incarnation is picked as the current one: each read + lists the known incarnations after the last chunk it read (those that grew last time + first, the others in turn), and reads the new chunks of those that grew, one chunk of each + before a second of any. A restarted syncer is read whatever its step or term. + +How late the report can be, with the store copy: + +- Normally one upload interval and one read interval after the merges it counts (about + 1 minute). +- One read takes at most 16 chunks, about 8 minutes of tape. A backlog left by a store + outage is read in about one fifteenth of the outage's length: 1 hour of outage is caught + up in about 4 minutes. +- A restarted syncer writes to a new incarnation. The launch finds it at its next full + listing, which comes every 10 reads (about 5 minutes), and reads it from its start. Each + read lists the incarnations it knows within half of its 5 s budget; with many stopped + syncers, they take turns. +- If the first read fails, or does not finish within its budget, the next reads go on with + it. Until it is done nothing is read, and the syncer's earlier records are never read. + +Known limits of the store copy: + +- A join written before the first read finished is not read. A new island that joined then + is counted like an adopted one: from the first merge that lists it absent, with no + catch-up grace. +- An uploader that rewrites a chunk it already uploaded (a retry under the same key) adds + lines the launch does not read when it already read that chunk. +- Only a syncer incarnation found after the first read is filtered by its clock (records + stamped more than 10 minutes before the launch started are skipped). If that syncer's + clock runs more than 10 minutes behind, its records are skipped, and the launch reports + the tape silent (`island_straggler_unavailable`) instead of the stragglers. + +When the report cannot work, the launch prints `island straggler watch off` and writes +`island_straggler_unavailable` once, with the `reason`, in `fleet.jsonl`. Nothing is +reported then, and training is not affected. This happens: + +- with `--rl-island-straggler-cycles 0`; +- in a per-island fleet whose run store is not an object store, or with the upload off + (`YETO_RL_TAPE_UPLOAD_S=0`); +- in a fleet launched as one launch (`fleet.launch: synced_group`) whose syncer runs on a VM + of its own (any `--controller` other than `head`). That syncer's tape stays on its VM: + the launch does not upload it to the run store, so the controller has nothing to read. + Run the syncer on the controller's host (`--controller head`) or launch the fleet island + by island to get the report. +- when the launch reads no syncer record for two of the syncer's longest rounds plus two + upload intervals, and at least 5 minutes (the store copy is missing or stale). A round + ends at `--rl-sync-soft-deadline-s` only once enough pushes arrived; otherwise it runs to + its quorum timeout (`--rl-elastic-quorum-timeout-s`, else the syncer's default quorum + timeout of 900 s). The longest round is the larger of the two: with the defaults, the + window is 31 minutes. This is counted only after the first record about + the launch's islands, so a fleet whose trainers are still starting is not reported. Once + records are read again, the launch writes `island_straggler_available`. + +### Removing an island + +```bash +yeto fleet island remove --config run.json --name north --dry-run +yeto fleet island remove --config run.json --name north +``` + +The trainer worker writes the island's STOP. The island's controller drains it, stops the +trainer on every node (and checks that each container is gone), and records the island +`done`. Its incarnation is closed in the run's resource ledger. The syncer sees the island's +connection drop. The round it was asked for waits one island lease and then merges over the +islands left. The island's nodes are free for another island afterwards. + +In a fleet launched as one launch (`fleet.launch: synced_group`), islands cannot be added +while it trains. One island can be stopped and started again by its learner id, for example +island 1 with `yeto island stop 1 --config run.json` and `yeto island start 1 --config run.json`. diff --git a/tests/test_dashboard_island_straggler.py b/tests/test_dashboard_island_straggler.py new file mode 100644 index 000000000..e50d5549f --- /dev/null +++ b/tests/test_dashboard_island_straggler.py @@ -0,0 +1,203 @@ +"""A trainer island the syncer has merged no push of for N merge cycles (``island_straggler`` +in fleet.jsonl, ``straggler`` in its record) on the dashboard: the event stream shows the +straggler events, the trainer card carries a straggler badge until it is cleared, and the +events leave the island's lifecycle state alone.""" + +from __future__ import annotations + +import json +import re +import shutil +import subprocess +from pathlib import Path + +import pytest +from test_dashboard_diloco import SMOKE +from test_dashboard_fleet_islands import T0, fleet_reducer + +from yeto.dashboard.export import export_html +from yeto.launch import island_straggler as st + +# the topology page's smoke, also printing the event stream +LEGEND = 'legend: mk("topoLg").innerHTML' +EV_SMOKE = SMOKE.replace(LEGEND, LEGEND + ', events: mk("evs").innerHTML') +assert EV_SMOKE != SMOKE + + +def _flagged(k: int = 1, at: float = T0 + 50) -> dict: + return {"event": st.EVENT, "time_unix": at, "island": f"fleet-qa-l{k}-modal", "island_id": k, + "action": st.WAIT, "missed_cycles": 3, "merges": 12, "fragments": 4, "newest_step": 40, + "last_merged_step": 28, "absent": True} + + +def _cleared(k: int = 1, at: float = T0 + 60) -> dict: + return {"event": st.CLEARED_EVENT, "time_unix": at, "island": f"fleet-qa-l{k}-modal", "island_id": k, + "missed_cycles": 0, "reason": "a push of it is merged again"} + + +def _reducer(*extra: dict): + r = fleet_reducer() + for rec in extra: + r.feed(rec) + return r + + +def _smoke(tmp: Path, r) -> dict: + node = shutil.which("node") + if node is None: + pytest.skip("node not installed") + tmp.mkdir(parents=True, exist_ok=True) + page = export_html(r, tmp / "p.html", generated_at=r.max_ts) + (tmp / "smoke.js").write_text(EV_SMOKE) + res = subprocess.run([node, str(tmp / "smoke.js"), str(page), "1200"], capture_output=True, text=True, + timeout=60, check=False) + assert res.returncode == 0, res.stderr + return json.loads(res.stdout) + + +def _cards(r) -> dict: + return {c["id"]: c for c in r.overview(now=r.max_ts)["islands"]} + + +def test_a_straggler_event_marks_the_card_and_keeps_its_lifecycle_state(): + plain = _cards(_reducer()) + flagged = _cards(_reducer(_flagged())) + assert flagged["1"]["straggler"] == {"action": "wait", "missed_cycles": 3, "newest_step": 40, + "last_merged_step": 28, "at": T0 + 50} + assert flagged["0"]["straggler"] is None and plain["1"]["straggler"] is None + assert flagged["1"]["status"] == plain["1"]["status"] # not a lifecycle state + assert _cards(_reducer(_flagged(), _cleared()))["1"]["straggler"] is None + + +def test_an_unavailable_watch_is_no_mark(): + rec = {"event": st.UNAVAILABLE_EVENT, "time_unix": T0 + 50, "island": "fleet-qa-l1-modal", "island_id": 1, + "reason": "the run store is not an object store"} + cards = _cards(_reducer(_flagged(), rec)) + assert cards["1"]["straggler"]["missed_cycles"] == 3 # still flagged: unavailable says nothing of it + + +def test_the_trainer_card_draws_a_straggler_badge_until_cleared(tmp_path): + flagged = _smoke(tmp_path / "a", _reducer(_flagged())) + assert "straggler" in flagged["texts"] # the topology's trainer card + # Islands now: trainer 1's row says straggler in warn colour in place of "ok", once + assert flagged["nodes"].count('straggler') == 1 + shown = re.sub(r"<[^>]+>", "", flagged["nodes"]) # the row's visible text + assert "H100 × 2 · straggler" in shown and "ok · straggler" not in shown + assert "straggler" not in flagged["matrix"] # not in the Fragments rows + for r in (_reducer(), _reducer(_flagged(), _cleared())): + out = _smoke(tmp_path / str(len(r.fleet_records)), r) + assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] + + +def test_the_island_record_s_mark_wins_over_the_events(tmp_path): + """A per-island fleet: the island's record says what the controller holds now.""" + from test_dashboard_trainer_islands import _state + + from yeto.dashboard import fleet_islands + + r = _reducer(_flagged()) + state = _state(tmp_path) + rec = {**state["trainers"][1]["record"], "launch_state": "running", "life_state": "running", + "straggler": None} + state["trainers"][1].update(record=rec, now=fleet_islands.island_state(rec, state["trainers"][1])) + r.load_fleet_state(state) + assert _cards(r)["1"]["island_now"]["straggler"] is None + out = _smoke(tmp_path / "rec", r) + assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] + + +def test_the_controller_s_mark_reaches_the_card_through_the_island_records(tmp_path): + """The production path: the controller writes the mark to the island's record in the run + store, ``read_fleet_state`` reads it back (``_trainer_records``) and the card shows it.""" + from test_island_straggler import _controller, _join, _step + + from yeto.dashboard import fleet_islands + from yeto.rl.engine.object_store import DirectoryObjectStore + + ctl, _ops, _store, tape, _log = _controller(tmp_path) + tape.pending += [_join(0), _join(1), _step(1, [0, 1], fragments=1), _step(2, [0], fragments=1, absent=[1])] + ctl._poll_stragglers() # island 1 missed one cycle: reported, its record carries the mark + + def card_of(): # a fresh read of the run store, as the dashboard's poll does + r = _reducer() # no island_straggler event: only the record can tell + assert r.load_fleet_state(fleet_islands.read_fleet_state(DirectoryObjectStore(str(tmp_path / "store")))) + return r, _cards(r)["1"] + + r, card = card_of() + mark = card["island_now"]["straggler"] + assert mark["action"] == st.WAIT and mark["missed_cycles"] == 1 and mark["last_merged_step"] == 1 + assert mark["newest_step"] == 2 and mark["absent"] is True and isinstance(mark["at"], float) + assert (_cards(r)["0"]["island_now"] or {}).get("straggler") is None # island 0: no mark + out = _smoke(tmp_path / "flagged", r) + assert out["nodes"].count('straggler') == 1 + tape.pending.append(_step(3, [0, 1], fragments=1)) + ctl._poll_stragglers() # a push of it is merged again: cleared in its record + r, card = card_of() + assert card["island_now"]["straggler"] is None + out = _smoke(tmp_path / "cleared", r) + assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] + + +def _mark_of(r, k="1"): + return _cards(r)[k]["straggler"] + + +def test_straggler_events_out_of_order_across_sources_end_as_the_newest_says(): + """A host's store copy read after the other host's file (#910): the clear arrives before + the report it closes, or a report before a later clear. The newest by time decides, the + replay of the island's lifecycle leaves the mark alone, and the same event twice counts once.""" + r = _reducer() + end = r.max_ts + r.feed(_cleared(at=end + 60), source="new-host") + r.feed(_flagged(at=end + 50), source="old-host") # older: read late + assert _mark_of(r) is None # not reported for good after its clear + r.feed({"event": "island_lost", "time_unix": end + 40, "island": "fleet-qa-l1-modal", "island_id": 1}, + source="old-host") # an older lifecycle record: the island's lifecycle is replayed + assert _mark_of(r) is None + r.feed(_flagged(at=end + 70), source="old-host") + r.feed(_flagged(at=end + 70), source="new-host") # the same report from both copies + assert _mark_of(r)["missed_cycles"] == 3 + r.feed(_cleared(at=end + 65), source="new-host") # a clear older than the report + assert _mark_of(r)["missed_cycles"] == 3 + page = r.overview(now=r.max_ts) + assert [i["id"] for i in page["islands"]].count("1") == 1 + + +def test_a_source_whose_clock_steps_back_folds_its_marks_in_write_order(): + """One file: a report, then its clear stamped earlier (the host's clock stepped back). + The file's order decides, as for its lifecycle records.""" + r = _reducer() + end = r.max_ts + r.feed(_flagged(at=end + 50), source="fleet.jsonl") + r.feed(_cleared(at=end + 20), source="fleet.jsonl") # written after, stamped before + assert _mark_of(r) is None + r.feed(_flagged(at=end + 30), source="fleet.jsonl") # and reported again after it + assert _mark_of(r)["missed_cycles"] == 3 + + +def test_the_mark_is_the_island_of_its_learner_id_not_of_its_launch_index(tmp_path): + """#910: an island launch of a per-island fleet runs its island as island 0 of its + launch, and fleet.jsonl names it by its learner id. The controller's straggler event + lands on that learner's card.""" + from yeto.dashboard.fleet import from_env + + log = from_env(tmp_path / "fleet.jsonl", {"r-i1-l0-trainer": "task"}, learner_ids={"r-i1-l0-trainer": 1}) + log.event(st.EVENT, "r-i1-l0-trainer", **st.signal_fields( + st.Straggler(island=1, cleared=False, missed_cycles=3, merges=12, fragments=4, cycles=3, newest_step=40, + last_merged_step=28, absent=True, reason="no push merged"), st.WAIT)) + (row,) = [json.loads(line) for line in (tmp_path / "fleet.jsonl").read_text().splitlines()] + assert row["island_id"] == 1 # not the -l0 index of its name + r = _reducer() + r.feed(dict(row, time_unix=r.max_ts + 10)) + assert _mark_of(r, "1")["missed_cycles"] == 3 and not _cards(r)["0"].get("straggler") + + +def test_the_event_stream_shows_the_straggler_events(tmp_path): + end = fleet_reducer().max_ts # the newest events: the stream shows the latest 15 + events = _smoke(tmp_path, _reducer(_flagged(at=end + 10), _cleared(at=end + 20)))["events"] + assert "island_straggler" in events and "missed_cycles=3" in events and "action=wait" in events + assert "island_straggler_cleared" in events and "reason=a push of it is merged again" in events + cleared = events.split("island_straggler_cleared", 1)[1].split("", 1)[0] + assert "missed_cycles" not in cleared # its reason only + assert 'title="lag"' in events and 'title="back"' in events + assert "island_straggler trainer 1 action=wait missed_cycles=3" in events diff --git a/tests/test_island_straggler.py b/tests/test_island_straggler.py new file mode 100644 index 000000000..d89e13710 --- /dev/null +++ b/tests/test_island_straggler.py @@ -0,0 +1,1185 @@ +"""Island stragglers (own-cluster-fleet-stability 9.1): an island none of whose pushes the +syncer merged in N merge cycles is written as ``island_straggler`` by the fleet controller, +once per stretch, and cleared once a push of it is merged again. The tracker reads the +syncer's tape (a local file or its copy in the run store); the controller asks its policy +whether to wait (default) or replace, and the other islands are not touched.""" + +from __future__ import annotations + +import json +import types + +import pytest +from test_controller import RUNNING, SYNCER, FakeOps, ImmediateThread + +from yeto.launch import island_lifecycle as lc +from yeto.launch import island_straggler as st +from yeto.launch.fleet import FleetController +from yeto.rl.engine.object_store import DirectoryObjectStore + + +def _step(step, merged, *, fragments=2, absent=()): + return {"kind": "outer_step", "step": step, "fragment": (step - 1) % fragments, + "weights": [[k, step - 1, 1.0 / len(merged)] for k in merged], + "raw_weights": [[k, step - 1, 1.0] for k in merged], "absent": list(absent)} + + +def _join(k): + return {"kind": "pool_join", "island_id": k, "generation": 0, "catch_up": False, "base_version": 0} + + +RUN2 = {0: (0, 1), 1: (0, 1)} + + +def test_an_island_merged_in_no_round_for_n_cycles_is_a_straggler_once_then_cleared(): + tracker = st.StragglerTracker(cycles=3) + for k in (0, 1): + tracker.feed(_join(k)) + step = 0 + for _ in range(4): # both islands merged: nothing + step += 1 + tracker.feed(_step(step, [0, 1])) + assert tracker.check(RUN2) == [] + signals = [] + for _ in range(6): # island 1 silent: 3 cycles of 2 fragments + step += 1 + tracker.feed(_step(step, [0], absent=[1])) + signals += tracker.check(RUN2) + (signal,) = signals + assert signal.island == 1 and not signal.cleared and signal.missed_cycles == 3 and signal.merges == 6 + assert signal.fragments == 2 and signal.cycles == 3 and signal.absent and signal.newest_step == step + assert signal.last_merged_step == 4 and "3 merge cycle(s)" in signal.reason + for _ in range(4): # still silent: no second event for the same stretch + step += 1 + tracker.feed(_step(step, [0], absent=[1])) + assert tracker.check(RUN2) == [] + step += 1 + tracker.feed(_step(step, [0, 1])) # a push of it is merged again (a late push carried in) + (cleared,) = tracker.check(RUN2) + assert cleared.island == 1 and cleared.cleared and cleared.last_merged_step == step + + +def test_one_cycle_short_is_not_a_straggler_and_a_merged_push_resets_the_count(): + tracker = st.StragglerTracker(cycles=3) + for k in (0, 1): + tracker.feed(_join(k)) + step = 0 + for _ in range(3): + for _ in range(5): # 5 of the 6 merges without it, then one with it + step += 1 + tracker.feed(_step(step, [0])) + step += 1 + tracker.feed(_step(step, [0, 1])) + assert tracker.check(RUN2) == [] + + +def test_counting_starts_at_the_join_of_the_launch_and_a_relaunch_starts_it_again(): + tracker = st.StragglerTracker(cycles=1) + for step in range(1, 9): # island 1 not joined yet (its launch still starts): nothing counts + tracker.feed(_step(step, [0], fragments=1)) + assert tracker.check(RUN2) == [] + tracker.feed(_join(1)) + tracker.feed(_step(9, [0], fragments=1)) + (signal,) = tracker.check(RUN2) + assert signal.island == 1 and signal.merges == 1 + # relaunched while flagged (a new incarnation token): cleared, and counted from its next join + (cleared,) = tracker.check({0: (0, 1), 1: (1, 2)}) + assert cleared.cleared and cleared.reason == "relaunched" + tracker.feed(_step(10, [0], fragments=1)) + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] + tracker.feed(_join(1)) # a re-JOIN of the same incarnation later does not restart it + tracker.feed(_step(11, [0], fragments=1)) + tracker.feed(_join(1)) + assert [s.island for s in tracker.check({0: (0, 1), 1: (1, 2)})] == [1] + + +def test_only_the_running_islands_are_reported_and_zero_cycles_is_off(): + tracker = st.StragglerTracker(cycles=1) + for k in (0, 1): + tracker.feed(_join(k)) + tracker.feed(_step(1, [0], fragments=1)) + assert tracker.check({0: (0, 1)}) == [] # island 1 draining or recovering: not watched + (flagged,) = tracker.check(RUN2) # running again (same incarnation): reported + (closed,) = tracker.check({0: (0, 1)}) # then it stops running: its stretch is closed + assert not flagged.cleared and closed.cleared and closed.island == 1 and closed.reason == "not running" + assert tracker.check({0: (0, 1)}) == [] + off = st.StragglerTracker(cycles=0) + for k in (0, 1): + off.feed(_join(k)) + for step in range(1, 20): + off.feed(_step(step, [0], fragments=1)) + assert off.check(RUN2) == [] + + +def test_the_flag_is_a_whole_number_of_cycles(): + assert st.straggler_cycles(types.SimpleNamespace()) == 3 + assert st.straggler_cycles(types.SimpleNamespace(rl_island_straggler_cycles=5)) == 5 + assert st.straggler_cycles(types.SimpleNamespace(rl_island_straggler_cycles=0)) == 0 + with pytest.raises(ValueError, match="whole number >= 0"): + st.straggler_cycles(types.SimpleNamespace(rl_island_straggler_cycles=-1)) + + +def test_the_flag_is_checked_with_the_island_pool_options(monkeypatch): + from yeto.cli import build_parser + from yeto.launch import rl_args + + base = ["launch", "--training-mode", "rl", "--model", "m", "--data", "d"] + assert build_parser().parse_args([*base, "--rl-island-straggler-cycles", "4"]).rl_island_straggler_cycles == 4 + assert build_parser().parse_args(base).rl_island_straggler_cycles is None + monkeypatch.setattr(rl_args, "rl_needs_critic", lambda args: False) + args = types.SimpleNamespace(training_mode="rl", rl_sync_island_lease_s=30.0, rl_sync_preset="strict-avg", + experimental_rl_sync=False, syncer_shards=None, rl_island_straggler_cycles=-2) + with pytest.raises(ValueError, match="--rl-island-straggler-cycles must be a whole number"): + rl_args._check_island_pool(args, num_islands=2) + + +def _at(record, t): + return dict(record, time_unix=t) + + +def test_records_from_before_the_watch_started_are_not_counted(tmp_path): + """A syncer incarnation the first listing missed is read from its start: its records + stamped more than CLOCK_SKEW_S before the watch started are an earlier launch's history + (island 1 missing every merge, and its join) and are not counted.""" + objects = DirectoryObjectStore(tmp_path / "store") + clock = [0.0] + source = st.StoreTape(objects, interval_s=30, clock=lambda: clock[0], since=10_000.0) + watch = st.StragglerWatch(source, cycles=1, log=lambda m: None) + assert watch.poll(RUN2) == [] # the tail: nothing there yet + inc = "hosta-20261126T130000Z" # listed late: read from its start + _chunk(objects, inc, 0, _at(_join(0), 9_000.0), _at(_join(1), 9_000.0), + *(_at(_step(n, [0], fragments=1, absent=[1]), 9_000.0 + n) for n in range(1, 9))) + for _ in range(st.STORE_DISCOVER_POLLS): + clock[0] += 31.0 + assert watch.poll(RUN2) == [] # nothing of it counts: island 1 has not joined since + assert inc in source.fresh + _chunk(objects, inc, 1, _at(_join(1), 10_001.0), _at(_step(9, [0], fragments=1), 10_002.0)) + clock[0] += 31.0 + (signal,) = watch.poll(RUN2) + assert signal.merges == 1 and signal.last_merged_step is None + + +def test_a_syncer_clock_300_s_behind_is_still_counted(tmp_path): + """The syncer host's clock may run behind the launcher's: a late-listed incarnation's + records of now are stamped up to CLOCK_SKEW_S before the watch's start and still count.""" + objects = DirectoryObjectStore(tmp_path / "store") + clock = [0.0] + watch = st.StragglerWatch(st.StoreTape(objects, interval_s=30, clock=lambda: clock[0], since=10_000.0), + cycles=1, log=lambda m: None) + watch.poll(RUN2) + _chunk(objects, "hosta-20261126T130000Z", 0, _at(_join(1), 9_700.0), _at(_step(1, [0], fragments=1), 9_701.0)) + signals = [] + for _ in range(st.STORE_DISCOVER_POLLS): + clock[0] += 31.0 + signals += watch.poll(RUN2) + assert [s.island for s in signals] == [1] + assert st.CLOCK_SKEW_S >= 300 + + +def test_the_tail_s_records_count_whatever_their_clock(tmp_path): + """An incarnation read from its tail is read by position: a syncer clock an hour behind + is not taken for history (no clock is compared).""" + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + _chunk(objects, inc, 0, _at(_step(1, [0], fragments=1), 6_000.0)) + clock = [0.0] + watch = st.StragglerWatch(st.StoreTape(objects, interval_s=30, clock=lambda: clock[0], since=10_000.0), + cycles=1, log=lambda m: None) + assert watch.poll(RUN2) == [] + _chunk(objects, inc, 1, _at(_join(1), 6_400.0), _at(_step(2, [0], fragments=1), 6_401.0)) + clock[0] = 31.0 + assert [s.island for s in watch.poll(RUN2)] == [1] + + +def test_a_link_that_reconnects_keeps_the_count_and_the_mark(): + """Each reconnect of the same process is a new connection generation, and the syncer + writes a new pool_join for it: none restarts the count or clears the mark. An island that + reconnects every 2 merges and never delivers is reported once, and stays reported.""" + tracker = st.StragglerTracker(cycles=3) + signals = [] + for step in range(1, 41): + if step % 2 == 1: + tracker.feed(dict(_join(1), generation=step)) + signals += tracker.check(RUN2) + tracker.feed(_step(step, [0], fragments=1, absent=[1])) + signals += tracker.check(RUN2) + assert [(s.island, s.cleared, s.merges) for s in signals] == [(1, False, 3)] + + +def test_a_new_syncer_term_keeps_the_count_and_the_mark(): + tracker = st.StragglerTracker(cycles=2) + tracker.feed(_join(1)) + for step in (1, 2): + tracker.feed(_step(step, [0], fragments=1)) + (signal,) = tracker.check(RUN2) + assert not signal.cleared + tracker.feed(dict(_join(1), syncer_epoch=4, generation=7)) # a syncer that took over + assert tracker.check(RUN2) == [] # still reported: nothing written + tracker.feed(_step(3, [1], fragments=1)) + (cleared,) = tracker.check(RUN2) + assert cleared.cleared and cleared.reason == "a push of it is merged again" + + +def test_an_island_the_syncer_lists_absent_is_counted_without_a_join(): + """A restarted launcher adopts a stuck island: its join came before this watch. The syncer + expects it (absent in its merges), so it is counted from the first such merge.""" + tracker = st.StragglerTracker(cycles=2) + for step in (1, 2): + tracker.feed(_step(step, [0], fragments=1, absent=[] if step == 1 else [1])) + assert tracker.check(RUN2) == [] # one merge listed it absent: 1 of 2 + tracker.feed(_step(3, [0], fragments=1, absent=[1])) + (signal,) = tracker.check(RUN2) + assert signal.island == 1 and signal.merges == 2 and signal.absent + + +GRACE = 600.0 # the controller's recover timeout + + +class _Merges: + """A tracker judged as its controller does (its clock, its recover timeout as the grace), + island 0 merged at every step, island 1 merged only when it pushes.""" + + def __init__(self, cycles=1, fragments=1): + self.tracker, self.fragments = st.StragglerTracker(cycles=cycles), fragments + self.step, self.now = 0, 0.0 + + def merge(self, *, pushes=False, absent=True, dt=30.0): + self.step += 1 + self.now += dt + self.tracker.feed(_step(self.step, [0, 1] if pushes else [0], fragments=self.fragments, + absent=[1] if absent and not pushes else [])) + + def check(self, running=None, **kw): + return self.tracker.check(RUN2 if running is None else running, now=self.now, grace_s=GRACE, **kw) + + +def _relaunched(m): + """Island 1 pushed, then was relaunched (a new token: a spare node, a move, a relaunch).""" + m.tracker.feed(_join(0)) + m.tracker.feed(_join(1)) + m.merge(pushes=True) + assert m.check() == [] + assert m.check({0: (0, 1)}) == [] # recovering + m.tracker.feed(_join(1)) # its new launch joins, then catches up + assert m.check({0: (0, 1), 1: (1, 2)}) == [] + + +def test_a_relaunch_catching_up_past_n_cycles_within_its_recover_timeout_is_not_reported(): + m = _Merges(cycles=1) + _relaunched(m) + for _ in range(19): # 19 merge cycles (570 s) without a push: inside the 600 s grace + m.merge() + assert m.check({0: (0, 1), 1: (1, 2)}) == [] + + +def test_past_its_recover_timeout_a_silent_relaunch_is_counted_from_then_and_reported_after_n_cycles(): + m = _Merges(cycles=3, fragments=2) + _relaunched(m) + run, start = {0: (0, 1), 1: (1, 2)}, m.now # its grace starts when its controller holds it running + while m.now + 30 < start + GRACE: + m.merge() + assert m.check(run) == [] + m.merge() + assert m.check(run) == [] # its grace runs out at this check: counted from here on + for _ in range(3 * 2 - 1): # one merge short of 3 cycles + m.merge() + assert m.check(run) == [] + m.merge() + (signal,) = m.check(run) + assert signal.island == 1 and signal.merges == 6 and signal.missed_cycles == 3 + assert "catch-up grace" in signal.reason + m.merge(pushes=True) + (back,) = m.check(run) + assert back.cleared and back.reason == "a push of it is merged again" + + +def test_after_its_first_merged_push_a_relaunch_is_counted_as_usual(): + m = _Merges(cycles=2) + _relaunched(m) + run = {0: (0, 1), 1: (1, 2)} + for _ in range(5): + m.merge() + assert m.check(run) == [] + m.merge(pushes=True) # caught up: its grace is over + assert m.check(run) == [] + m.merge() + assert m.check(run) == [] + m.merge() + (signal,) = m.check(run) + assert signal.merges == 2 and "catch-up grace" not in signal.reason + + +def test_a_new_island_s_first_join_has_the_grace_an_adopted_one_none(): + m = _Merges(cycles=1) + m.tracker.feed(_join(0)) + assert m.check({0: (0, 1)}) == [] + m.tracker.feed(_join(1)) # added to the fleet: it catches up first + for _ in range(10): + m.merge() + assert m.check() == [] + adopted = _Merges(cycles=1) # a restarted launcher: island 1 joined before its watch + adopted.merge() + (signal,) = adopted.check() + assert signal.island == 1 and signal.absent + + +def test_a_reconnect_neither_starts_nor_extends_the_grace(): + m = _Merges(cycles=1) + _relaunched(m) + run, start = {0: (0, 1), 1: (1, 2)}, m.now + while m.now < start + GRACE: + m.merge() + m.tracker.feed({**_join(1), "generation": 1}) # its link reconnects on and on + assert m.check(run) == [] + m.merge() + m.tracker.feed({**_join(1), "generation": 2}) + (signal,) = m.check(run) + assert signal.island == 1 and "catch-up grace" in signal.reason + pushed = _Merges(cycles=1) # one that pushed: a reconnect gives it no grace + pushed.tracker.feed(_join(1)) + pushed.merge(pushes=True) + pushed.check() + pushed.tracker.feed({**_join(1), "generation": 1}) + pushed.merge() + (signal,) = pushed.check() + assert signal.island == 1 + + +def test_the_same_incarnation_back_from_recovering_has_no_grace(): + m = _Merges(cycles=1) + m.tracker.feed(_join(1)) + m.merge(pushes=True) + m.check() + assert m.check({0: (0, 1)}) == [] # recovering, then back as the same incarnation + assert m.check() == [] + m.merge() + (signal,) = m.check() + assert signal.island == 1 + + +def _graced_after(m, run): + """Island 1's new launch never pushes: not counted for its grace, then reported N cycles on.""" + start = m.now + while m.now + 30 < start + GRACE: + m.merge() + assert m.check(run) == [], m.now - start + m.merge() + assert m.check(run) == [] # its grace runs out here + signals = [] + for _ in range(m.tracker.cycles * m.fragments): + m.merge() + signals += m.check(run) + assert [s.island for s in signals] == [1] and "catch-up grace" in signals[0].reason + + +@pytest.mark.parametrize("case", ["last push merged after it was recovering", "pushes merged while it drained", + "removed, then added again"]) +def test_a_push_merged_while_away_is_its_earlier_launch_s_and_the_new_one_has_its_grace(case): + m = _Merges(cycles=1) + m.tracker.feed(_join(0)) + m.tracker.feed(_join(1)) + m.merge(pushes=True) + assert m.check() == [] + if case == "pushes merged while it drained": # draining: its controller holds it away + m.merge(pushes=True) + assert m.check({0: (0, 1)}) == [] # away: recovering, draining, or removed + m.merge(pushes=True) # its last push, merged once it was away + if case == "removed, then added again": + for _ in range(20): # long gone; the others merge on + m.merge(absent=False) + assert m.check({0: (0, 1)}) == [] + m.tracker.feed(_join(1)) # the new launch (relaunched, started again, added again) joins + run = {0: (0, 1), 1: (1, 2)} + assert m.check(run) == [] + _graced_after(m, run) + + +def test_the_same_launch_back_with_a_reconnect_read_while_away_has_no_grace(): + m = _Merges(cycles=1) + m.tracker.feed(_join(0)) + m.tracker.feed(_join(1)) + m.merge(pushes=True) + m.check() + assert m.check({0: (0, 1)}) == [] # recovering + m.tracker.feed({**_join(1), "generation": 1}) # its link reconnects meanwhile + assert m.check() == [] # back as the same launch + m.merge() + (signal,) = m.check() + assert signal.island == 1 and "catch-up grace" not in signal.reason + + +def test_an_adopted_straggler_that_reconnects_keeps_its_report_and_has_no_grace(): + """Adopted (only listed absent), reported, then its link reconnects (or the syncer takes + over): a join of an island already in the pool is no new island, so no grace and no + false clear.""" + m = _Merges(cycles=1) + m.merge() # adopted: listed absent + (signal,) = m.check() + assert signal.island == 1 and not signal.cleared + for generation in (1, 2): + m.tracker.feed({**_join(1), "generation": generation, "syncer_epoch": generation}) + m.merge() + assert m.check() == [] # no cleared, no new report + assert m.tracker.islands[1].flagged and m.tracker.islands[1].grace_until is None + + +def test_records_of_the_earlier_incarnation_read_late_do_not_count(): + """Relaunched (it left running, then runs as a new token): merges of its earlier + incarnation read late, even ones that list it absent, start nothing; it is counted + from its next join.""" + tracker = st.StragglerTracker(cycles=1) + tracker.feed(_join(1)) + tracker.check(RUN2) + assert tracker.check({0: (0, 1)}) == [] # recovering + tracker.feed(_step(1, [0], fragments=1, absent=[1])) # read late + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] # running as its next incarnation + tracker.feed(_step(2, [0], fragments=1)) + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] # not joined yet: starting + tracker.feed(_join(1)) + tracker.feed(_step(3, [0], fragments=1)) + assert [s.merges for s in tracker.check({0: (0, 1), 1: (1, 2)})] == [1] + + +def test_a_join_recorded_before_the_controller_holds_the_new_incarnation_running_counts(): + """Recovering (the island left running), its new incarnation joins, and only then does + the controller hold it running (a new token): the join is the new incarnation's, so the + island is counted from its return, not left uncounted until a push of it merges.""" + tracker = st.StragglerTracker(cycles=1) + tracker.feed(_join(1)) + tracker.check(RUN2) + assert tracker.check({0: (0, 1)}) == [] # island 1 recovering + tracker.feed(dict(_join(1), catch_up=True)) + assert tracker.check({0: (0, 1)}) == [] # not held running: never reported + assert tracker.check({0: (0, 1), 1: (1, 2)}) == [] # running again + tracker.feed(_step(1, [0], fragments=1)) + (signal,) = tracker.check({0: (0, 1), 1: (1, 2)}) + assert not signal.cleared and signal.island == 1 and signal.merges == 1 + + +def test_an_island_back_running_as_the_same_incarnation_keeps_its_place_in_the_pool(): + tracker = st.StragglerTracker(cycles=1) + tracker.feed(_join(1)) + tracker.check(RUN2) + assert tracker.check({0: (0, 1)}) == [] + tracker.check(RUN2) # the same token back + tracker.feed(_step(1, [0], fragments=1)) + assert [s.island for s in tracker.check(RUN2)] == [1] + again = st.StragglerTracker(cycles=2) # counted from its return: what it missed before is not + again.feed(_join(1)) + again.feed(_step(1, [0], fragments=1)) + again.check(RUN2) + again.check({0: (0, 1)}) + again.check(RUN2) + again.feed(_step(2, [0], fragments=1)) + assert again.check(RUN2) == [] + fresh = st.StragglerTracker(cycles=1) # never joined before it left: still not counted + fresh.check(RUN2) + fresh.check({0: (0, 1)}) + fresh.check(RUN2) + fresh.feed(_step(1, [0], fragments=1)) + assert fresh.check(RUN2) == [] + + +# -- the syncer's tape --------------------------------------------------------------------------- + +def test_the_local_tape_is_read_line_by_line_from_its_offset(tmp_path): + tape = tmp_path / "tape.jsonl" + tape.write_text(json.dumps(_join(9)) + "\n") + source = st.FileTape(tape, offset=tape.stat().st_size) # an earlier syncer job's records + assert source.read() == [] + with tape.open("a") as fh: + fh.write(json.dumps(_join(0)) + "\n" + '{"kind": "outer_st') # the syncer mid-write + assert source.read() == [_join(0)] + with tape.open("a") as fh: + fh.write('ep", "step": 1}\nnot json\n') + assert source.read() == [{"kind": "outer_step", "step": 1}] + assert st.FileTape(tmp_path / "missing.jsonl").read() == [] + + +def _chunk(objects, inc, seq, *records): + objects.write(f"tapes/syncer/{inc}/{seq:08d}.jsonl", "".join(json.dumps(r) + "\n" for r in records).encode()) + + +def test_the_store_tape_starts_at_the_tail_of_the_newest_syncer_and_reads_each_chunk_once(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + old, current = "hostb-20261126T120000Z", "hosta-20261126T130000Z" # by name the newer sorts first + _chunk(objects, old, 0, _join(1), _step(1, [0])) + _chunk(objects, current, 0, _join(1), _step(2, [0])) # the history before this watch + _chunk(objects, current, 1, _step(3, [0])) + objects.write("tapes/syncer-shard1/x/00000000.jsonl", b'{"kind": "outer_step"}\n') # not this tape + objects.write("tapes/l0-host-20261126T120000Z/00000000.jsonl", b'{"event": "rl_local_round"}\n') + clock = [0.0] + source = st.StoreTape(objects, interval_s=30, clock=lambda: clock[0]) + assert source.read() == [] and source.polled # the tail: no history + _chunk(objects, current, 2, _step(4, [0])) + assert source.read() == [] and not source.polled # within the poll interval: no request + clock[0] = 31.0 + assert source.read() == [_step(4, [0])] + clock[0] = 62.0 + assert source.read() == [] + restarted = "hosta-20261126T140000Z" # the syncer restarted: its new tape is read from its start + _chunk(objects, current, 3, _step(5, [0])) + _chunk(objects, restarted, 0, _join(0), _step(6, [0])) + got = [] + for _ in range(st.STORE_DISCOVER_POLLS): # found by the next full listing + clock[0] += 31.0 + got += source.read() + assert got == [_step(5, [0]), _join(0), _step(6, [0])] # the old one drained, then the new one + + +def test_a_watch_started_on_a_history_does_not_count_it(tmp_path): + """The relaunch case through the store: an earlier launch's history (island 1 missing + every merge) in the newest syncer incarnation; a new watch reports nothing until island 1 + joins again, then counts from 0.""" + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + _chunk(objects, inc, 0, _at(_join(0), 10.0), _at(_join(1), 10.0), + *(_at(_step(n, [0], fragments=1), 10.0 + n) for n in range(1, 9))) + clock = [0.0] + watch = st.StragglerWatch(st.StoreTape(objects, interval_s=30, clock=lambda: clock[0], since=100.0), + cycles=2, log=lambda m: None) + assert watch.poll(RUN2) == [] + _chunk(objects, inc, 1, *(_at(_step(n, [0], fragments=1), 101.0 + n) for n in range(9, 12))) + clock[0] = 31.0 + assert watch.poll(RUN2) == [] # island 1 has not joined since the watch started + _chunk(objects, inc, 2, _at(_join(1), 120.0), _at(_step(12, [0], fragments=1), 121.0)) + clock[0] = 62.0 + assert watch.poll(RUN2) == [] # 1 merge since its join + _chunk(objects, inc, 3, _at(_step(13, [0], fragments=1), 122.0)) + clock[0] = 93.0 + (signal,) = watch.poll(RUN2) + assert signal.island == 1 and signal.merges == 2 + + +def test_the_store_tape_reads_at_most_its_chunks_per_poll_and_keeps_what_it_read(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + _chunk(objects, inc, 0, _join(0)) + clock = [0.0] + source = st.StoreTape(objects, interval_s=30, clock=lambda: clock[0], gets_per_poll=4) + assert source.read() == [] + for seq in range(1, 11): + _chunk(objects, inc, seq, _step(seq, [0])) + got = [] + for _ in range(3): + clock[0] += 31.0 + batch = source.read() + assert len(batch) <= 4 + got += batch + assert [r["step"] for r in got] == list(range(1, 11)) + + class Flaky: # the 3rd chunk read of a poll fails once + def __init__(self, inner): + self.inner, self.reads, self.failed = inner, 0, False + + def list(self, prefix, *, start_after=""): + return self.inner.list(prefix, start_after=start_after) + + def read(self, key): + self.reads += 1 + if self.reads == 3 and not self.failed: # the tail reads no chunk + self.failed = True + raise OSError("read timed out") + return self.inner.read(key) + + flaky = st.StoreTape(Flaky(objects), interval_s=30, clock=lambda: clock[0]) + assert flaky.read() == [] + for seq in range(11, 16): + _chunk(objects, inc, seq, _step(seq, [0])) + clock[0] += 31.0 + first = flaky.read() + assert [r["step"] for r in first] == [11, 12] and "read timed out" in flaky.error # kept, not lost + clock[0] += 31.0 + second = flaky.read() + assert [r["step"] for r in second] == [13, 14, 15] and flaky.error is None # none twice, none skipped + + +def test_a_failed_first_read_tries_the_tail_again_and_never_reads_the_history(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + for seq in range(5): + _chunk(objects, inc, seq, _step(seq + 1, [0])) # the history + + class Down: + def __init__(self, inner, fail): + self.inner, self.fail = inner, set(fail) + + def list(self, prefix, *, start_after=""): + if ("root" if prefix == "tapes/syncer/" else "inc") in self.fail: + raise OSError("list failed") + return self.inner.list(prefix, start_after=start_after) + + def read(self, key): + return self.inner.read(key) + + clock = [0.0] + for fail in ({"root"}, {"inc"}): # the incarnations' listing, then the newest one's chunks + clock[0] = 0.0 + down = Down(objects, fail) + source = st.StoreTape(down, interval_s=30, clock=lambda: clock[0]) + assert source.read() == [] and "list failed" in source.error and not source.tailed + down.fail = set() + clock[0] = 31.0 + assert source.read() == [] and source.tailed # the tail now: still no history + _chunk(objects, inc, 5 + len(fail) + (fail == {"inc"}), _step(99, [0])) + clock[0] = 62.0 + assert [r["step"] for r in source.read()] == [99] + + +def _two_syncers(tmp_path, old_tail, new_tail): + """Two syncer incarnations at the first read: ``old`` (stopped) and ``new`` (running).""" + objects = DirectoryObjectStore(tmp_path / "store") + old, new = "z-20991231T000000Z", "a-20000101T000000Z" # by name the stopped one sorts last + _chunk(objects, old, 0, *old_tail) + _chunk(objects, new, 0, *new_tail) + clock = [0.0] + source = st.StoreTape(objects, interval_s=30, clock=lambda: clock[0]) + assert source.read() == [] and source.known == {old, new} + + def grows(inc, seq, *records): + _chunk(objects, inc, seq, *records) + clock[0] += 31.0 + return source.read() + + return source, old, new, grows + + +def test_a_restarted_syncer_whose_last_chunk_has_only_its_own_records_is_read(tmp_path): + """No step or term in its last chunk (round opens, connections): nothing is picked, the + syncer that writes on is read.""" + own = [{"kind": "round_open", "fragment": 0}, {"kind": "member_connected", "learner_id": 0}, + {"kind": "round_attempt_timeout", "fragment": 0}] + _source, _old, new, grows = _two_syncers(tmp_path, [dict(_step(50, [0]), syncer_epoch=1)], own) + assert [r["step"] for r in grows(new, 1, dict(_step(51, [0]), syncer_epoch=1))] == [51] + assert [r["step"] for r in grows(new, 2, dict(_step(52, [0]), syncer_epoch=1))] == [52] + + +def test_a_syncer_resumed_from_an_earlier_step_is_read(tmp_path): + """A syncer restarted from its checkpoint is behind the stopped one's step.""" + _source, _old, new, grows = _two_syncers(tmp_path, [_step(50, [0])], [_step(30, [0])]) + assert [r["step"] for r in grows(new, 1, _step(31, [0]))] == [31] + + +def test_two_syncers_level_at_the_first_read_are_both_followed(tmp_path): + """Level progress, any names: whichever grows is read, each chunk once.""" + _source, old, new, grows = _two_syncers(tmp_path, [_step(40, [0])], [_step(40, [0])]) + assert [r["step"] for r in grows(old, 1, _step(41, [0]))] == [41] + assert [r["step"] for r in grows(new, 1, _step(42, [0]))] == [42] + assert grows(new, 2, _step(43, [0])) + grows(old, 2, _step(44, [0])) == [_step(43, [0]), _step(44, [0])] + + +def test_a_full_listing_never_reads_a_known_incarnation_again(tmp_path): + """A full listing (every STORE_DISCOVER_POLLS reads) adds only incarnations it did not know: + a known one keeps its cursor, so no chunk is read twice.""" + source, _old, new, grows = _two_syncers(tmp_path, [_step(1, [0])], [_step(2, [0])]) + got = [] + for seq in range(1, 3 * st.STORE_DISCOVER_POLLS): + got += grows(new, seq, _step(100 + seq, [0])) + assert [r["step"] for r in got] == [100 + seq for seq in range(1, 3 * st.STORE_DISCOVER_POLLS)] + assert source.fresh == set() + + +class _Ticking: + """A store whose every listing takes 1 s of the poll's clock (chunk reads take none).""" + + def __init__(self, inner): + self.inner, self.t = inner, 0.0 + + def list(self, prefix, *, start_after=""): + self.t += 1.0 + return self.inner.list(prefix, start_after=start_after) + + def read(self, key): + return self.inner.read(key) + + +def test_twenty_incarnations_growing_at_once_each_get_a_chunk_before_any_gets_a_second(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + names = [f"h{i:02d}-20261126T130000Z" for i in range(20)] + for inc in names: + _chunk(objects, inc, 0, _step(0, [0])) + clock = [0.0] + source = st.StoreTape(objects, interval_s=30, clock=lambda: clock[0]) + assert source.read() == [] + for i, inc in enumerate(names): + _chunk(objects, inc, 1, {"kind": "x", "inc": i, "seq": 1}) + _chunk(objects, inc, 2, {"kind": "x", "inc": i, "seq": 2}) + polls = [] + for _ in range(3): + clock[0] += 31.0 + polls.append([(r["inc"], r["seq"]) for r in source.read()]) + assert len(polls[0]) == st.STORE_GETS_PER_POLL and len({i for i, _ in polls[0]}) == 16 # one each + assert {i for i, _ in polls[1][:4]} == set(range(20)) - {i for i, _ in polls[0]} # the unread ones first + got = [x for poll in polls for x in poll] + assert sorted(got) == [(i, q) for i in range(20) for q in (1, 2)] + for i in range(20): # each incarnation's chunks in order + assert [q for j, q in got if j == i] == [1, 2] + + +def test_a_live_syncer_is_listed_however_many_stopped_ones_sort_before_it(tmp_path): + """The listing budget covers 3 incarnations a poll: the stopped ones take turns (the one + listed longest ago first) and one that grew is listed first.""" + inner = DirectoryObjectStore(tmp_path / "store") + dead = [f"a{i}-20261126T120000Z" for i in range(10)] + live = "z-20261126T130000Z" + for inc in [*dead, live]: + _chunk(inner, inc, 0, _step(0, [0])) + objects = _Ticking(inner) + source = st.StoreTape(objects, interval_s=0, clock=lambda: objects.t, budget_s=3.5) + while not source.tailed: + source.read() + got = [] + for seq in range(1, 9): + _chunk(inner, live, seq, _step(seq, [0])) + got.append([r["step"] for r in source.read()]) + assert sorted(x for poll in got for x in poll) == list(range(1, 9)) # all of it, once + assert all(poll and poll[-1] == n for n, poll in enumerate(got, 1) if n >= 6) # then each in its poll + + +def test_the_first_read_keeps_every_tail_across_polls_within_its_budget(tmp_path): + inner = DirectoryObjectStore(tmp_path / "store") + names = [f"h{i:02d}-20261126T130000Z" for i in range(7)] + for inc in names: + _chunk(inner, inc, 0, _step(1, [0])) # the history + objects = _Ticking(inner) + source = st.StoreTape(objects, interval_s=0, clock=lambda: objects.t, budget_s=2.5) + reads = 0 + while not source.tailed: + reads += 1 + assert source.read() == [] # never the history + assert objects.t <= reads * 4 # no listing past its budget + assert reads >= 3 and source.known == set(names) + for inc in names: + _chunk(inner, inc, 1, _step(2, [0])) + got = [] + for _ in range(10): + got += source.read() + assert got == [_step(2, [0])] * 7 + + +class _Paged(_Ticking): + """A paged store (as S3): one listing page holds 2 keys and takes 1 s.""" + + def list_page(self, prefix, *, start_after="", limit=1000): + self.t += 1.0 + return self.inner.list_page(prefix, start_after=start_after, limit=2) + + +def test_the_listing_of_every_syncer_goes_on_across_reads_within_the_budget(tmp_path): + inner = DirectoryObjectStore(tmp_path / "store") + names = [f"h{i:02d}-20261126T130000Z" for i in range(9)] + for inc in names: + _chunk(inner, inc, 0, _step(1, [0])) + _chunk(inner, inc, 1, _step(1, [0])) + objects = _Paged(inner) + source = st.StoreTape(objects, interval_s=0, clock=lambda: objects.t, budget_s=2.5) + reads, before = 0, 0.0 + while not source.tailed: + reads += 1 + before = objects.t + assert source.read() == [] + assert objects.t - before <= 3 # never past its budget (one request may start just inside it) + assert reads >= 4 and source.known == set(names) + + +def test_a_relaunch_between_two_checks_is_cleared_and_has_its_grace(): + """Relaunched by its controller between two polls (never seen away): its report is + cleared as relaunched and its new launch catches up with its grace.""" + m = _Merges(cycles=1) + m.tracker.feed(_join(0)) + m.tracker.feed(_join(1)) + m.merge(pushes=True) + assert m.check() == [] + m.merge() + (flagged,) = m.check() + assert flagged.island == 1 and not flagged.cleared + run = {0: (0, 1), 1: (1, 2)} # a new token at once + (cleared,) = m.check(run) + assert cleared.cleared and cleared.reason == "relaunched" + _graced_after(m, run) + + +def test_a_store_poll_starts_no_request_past_its_budget(tmp_path): + objects = DirectoryObjectStore(tmp_path / "store") + inc = "hosta-20261126T130000Z" + _chunk(objects, inc, 0, _join(0)) + ticks = [0.0] + + def clock(): # every call of the poll's clock: 1 s + ticks[0] += 1.0 + return ticks[0] + + source = st.StoreTape(objects, interval_s=0, clock=clock, budget_s=4.0) + assert source.read() == [] + for seq in range(1, 20): + _chunk(objects, inc, seq, _step(seq, [0])) + before = source.requests + batch = source.read() + assert 0 < len(batch) < 16 and source.requests - before <= 4 + + +def test_a_watch_whose_tape_does_not_read_logs_once_and_goes_on(): + lines = [] + + class Broken: + label = "s3://b/runs/r/tapes/syncer/" + + def read(self): + raise OSError("store down") + + watch = st.StragglerWatch(Broken(), cycles=1, log=lines.append) + assert watch.poll(RUN2) == [] and watch.poll(RUN2) == [] + assert len(lines) == 1 and "store down" in lines[0] + + +def test_the_launcher_watches_an_island_pool_only(tmp_path): + lines = [] + pool = types.SimpleNamespace(training_mode="rl", rl_sync_island_lease_s=30.0) + assert st.watch_for(types.SimpleNamespace(training_mode="rl"), objects=object(), log=lines.append) is None + off = st.watch_for(types.SimpleNamespace(**vars(pool), rl_island_straggler_cycles=0), objects=object(), + log=lines.append) + assert isinstance(off, st.UnavailableWatch) + assert off.notices() == [(st.UNAVAILABLE_EVENT, "turned off (--rl-island-straggler-cycles 0)")] + assert off.notices() == [] and off.poll(RUN2) == [] + none = st.watch_for(pool, log=lines.append, no_source="the syncer runs on its own VM") + assert isinstance(none, st.UnavailableWatch) + assert none.notices() == [(st.UNAVAILABLE_EVENT, "the syncer runs on its own VM")] + assert "watch off: the syncer runs on its own VM" in lines[-1] + watch = st.watch_for(pool, local_tape=tmp_path / "tape.jsonl", objects=object(), log=lines.append) + assert isinstance(watch.source, st.FileTape) and watch.tracker.cycles == 3 + assert watch.quiet_s == 2 * 900 # two rounds at the syncer's default quorum timeout, no upload + watch = st.watch_for(pool, objects=DirectoryObjectStore(tmp_path / "s"), log=lines.append) + assert isinstance(watch.source, st.StoreTape) and watch.source.since > 0 + assert watch.quiet_s == 2 * 900 + 2 * 30 # and two upload intervals of the store copy + soft = types.SimpleNamespace(**vars(pool), rl_sync_soft_deadline_s=60) + # a round short of the soft deadline's pushes runs to the quorum timeout: the longer one counts + assert st.watch_for(soft, objects=DirectoryObjectStore(tmp_path / "s"), log=lines.append).quiet_s == 2 * 900 + 60 + both = types.SimpleNamespace(**vars(soft), rl_elastic=True, rl_elastic_quorum_timeout_s=1800) + assert st.watch_for(both, objects=DirectoryObjectStore(tmp_path / "s"), log=lines.append).quiet_s == 2 * 1800 + 60 + elastic = types.SimpleNamespace(**vars(pool), rl_elastic=True, rl_elastic_quorum_timeout_s=200) + assert st.watch_for(elastic, objects=DirectoryObjectStore(tmp_path / "s"), log=lines.append).quiet_s == 460 + + +# -- the fleet controller ------------------------------------------------------------------------ + +class ScriptedTape: + label = "test tape" + + def __init__(self): + self.pending: list[dict] = [] + + def read(self): + out, self.pending = self.pending, [] + return out + + +class Recorder: + def __init__(self): + self.events = [] + + def event(self, kind, name, **fields): + self.events.append((kind, name, fields)) + + def kinds(self, kind): + return [e for e in self.events if e[0] == kind] + + def maybe_tick(self): + pass + + def cost_tick(self): + pass + + +def _controller(tmp_path, *, policy=None, cycles=1, recover_timeout=600): + ops = FakeOps() + ops.status_seq.update({SYNCER: [RUNNING], "r-l0": [RUNNING], "r-l1": [RUNNING]}) + store = lc.IslandStateStore(DirectoryObjectStore(tmp_path / "store")) + refs = {f"r-l{k}": lc.IslandRef(k, "ssh") for k in (0, 1)} + tape, log = ScriptedTape(), Recorder() + ctl = FleetController(learners={n: (f"task-{n}", 1) for n in refs}, syncer=(SYNCER, "task-syncer", 1), + sky_ops=ops, poll_interval=30, recover_timeout=recover_timeout, thread_cls=ImmediateThread, + recorder=lc.FleetRecorder(store, refs), elastic=True, fleet_log=log, + straggler=st.StragglerWatch(tape, cycles=cycles, log=lambda m: None), + straggler_policy=policy) + return ctl, ops, store, tape, log + + +def test_the_controller_writes_the_straggler_once_waits_and_touches_no_other_island(tmp_path): + ctl, ops, store, tape, log = _controller(tmp_path) + tape.pending += [_join(0), _join(1), _step(1, [0, 1], fragments=1), _step(2, [0], fragments=1, absent=[1])] + ctl._poll_stragglers() + (event,) = [e for e in log.events if e[0] == st.EVENT] + assert event[1] == "r-l1" and event[2]["action"] == st.WAIT and event[2]["missed_cycles"] == 1 + record = store.read(1) + assert record["straggler"]["action"] == "wait" and record["straggler"]["last_merged_step"] == 1 + assert "straggler" not in (store.read(0) or {}) + ctl._poll_stragglers() # nothing new: no second event + assert len([e for e in log.events if e[0] == st.EVENT]) == 1 + tape.pending.append(_step(3, [0, 1], fragments=1)) + ctl._poll_stragglers() + assert [e[:2] for e in log.events if e[0] == st.CLEARED_EVENT] == [(st.CLEARED_EVENT, "r-l1")] + assert store.read(1)["straggler"] is None + assert ops.down_calls == [] and ops.relaunch_calls == [] # waiting stops and relaunches nothing + assert all(rec["state"] == "running" for rec in ctl.learners.values()) + + +def test_a_draining_island_is_not_reported(tmp_path): + ctl, _ops, _store, tape, log = _controller(tmp_path) + ctl.learners["r-l1"]["draining"] = True + tape.pending += [_join(0), _join(1), _step(1, [0], fragments=1), _step(2, [0], fragments=1)] + ctl._poll_stragglers() + assert not [e for e in log.events if e[0] == st.EVENT] + + +def test_the_policy_decides_and_a_replace_is_handed_to_it(tmp_path): + asked, replaced = [], [] + + class Policy: + def __call__(self, name, signal): + asked.append((name, signal.island)) + return st.REPLACE + + def replace(self, name, signal): + replaced.append(name) + + ctl, _ops, store, tape, _log = _controller(tmp_path, policy=Policy()) + tape.pending += [_join(0), _join(1), _step(1, [0, 1], fragments=1), _step(2, [0], fragments=1)] + ctl._poll_stragglers() + assert asked == [("r-l1", 1)] and replaced == ["r-l1"] + assert store.read(1)["straggler"]["action"] == "replace" + + +def test_a_policy_that_fails_or_answers_nonsense_waits(tmp_path): + def broken(name, signal): + raise RuntimeError("no spare") + + ctl, _ops, store, tape, _log = _controller(tmp_path, policy=broken) + tape.pending += [_join(0), _join(1), _step(1, [0, 1], fragments=1), _step(2, [0], fragments=1)] + ctl._poll_stragglers() + assert store.read(1)["straggler"]["action"] == "wait" + ctl, _ops, store, tape, _log = _controller(tmp_path / "b", policy=lambda name, signal: "reboot") + tape.pending += [_join(0), _join(1), _step(1, [0, 1], fragments=1), _step(2, [0], fragments=1)] + ctl._poll_stragglers() + assert store.read(1)["straggler"]["action"] == "wait" + + +def test_without_a_watch_the_controller_reads_nothing(tmp_path): + ctl, _ops, _store, _tape, log = _controller(tmp_path) + ctl.straggler = None + ctl._poll_stragglers() + assert log.events == [] + + +def test_a_slow_start_is_never_said_unavailable(): + """Nothing about this launch's islands read yet (its trainers still load): no notice.""" + lines, tape, now = [], ScriptedTape(), [0.0] + watch = st.StragglerWatch(tape, cycles=1, log=lines.append, quiet_s=300, clock=lambda: now[0]) + tape.pending.append(_join(5)) # another launch's island: not this one's first record + for _ in range(100): + now[0] += 30 + watch.poll(RUN2) + assert lines == [] and watch.notices() == [] + + +def test_a_tape_silent_after_its_first_record_is_said_once_then_taken_back(): + lines, tape, now = [], ScriptedTape(), [0.0] + watch = st.StragglerWatch(tape, cycles=1, log=lines.append, quiet_s=300, clock=lambda: now[0]) + tape.pending.append(_join(0)) + watch.poll(RUN2) + for _ in range(20): + now[0] += 30 + watch.poll(RUN2) + assert len(lines) == 1 and "no syncer record read from test tape in 300 s" in lines[0] + ((kind, why),) = watch.notices() + assert kind == st.UNAVAILABLE_EVENT and "no syncer record" in why and watch.notices() == [] + tape.pending.append(_step(1, [0, 1])) + watch.poll(RUN2) + assert watch.notices() == [(st.AVAILABLE_EVENT, "syncer records read again from test tape")] + for _ in range(9): + now[0] += 30 + watch.poll(RUN2) + assert watch.notices() == [] # 270 s: short of a new silent stretch + + +def test_a_fleet_of_900_s_rounds_read_every_30_s_is_never_said_unavailable(): + """The production defaults: the syncer's quorum timeout (900 s, no soft deadline) and the + store copy read every 30 s. A merge every 900 s is no silence.""" + args = types.SimpleNamespace(training_mode="rl", rl_sync_island_lease_s=30.0) + lines, tape, now = [], ScriptedTape(), [0.0] + watch = st.StragglerWatch(tape, cycles=3, log=lines.append, clock=lambda: now[0], + quiet_s=st.quiet_window_s(args, upload_s=30.0)) + tape.pending.append(_join(0)) + step = 0 + for _ in range(4 * 3600 // 30): # 4 hours of reads + now[0] += 30 + if now[0] % 900 == 0: + step += 1 + tape.pending.append(_step(step, [0, 1], fragments=1)) + watch.poll(RUN2) + assert lines == [] and watch.notices() == [] + + +def test_a_soft_deadline_short_of_its_pushes_waits_for_the_quorum_and_is_not_said_unavailable(): + """soft 60 s, quorum timeout 1800 s, a round every 10 min (too few pushes for the soft + deadline): the window follows the quorum timeout, so no unavailable notice.""" + args = types.SimpleNamespace(training_mode="rl", rl_sync_island_lease_s=30.0, rl_sync_soft_deadline_s=60, + rl_elastic=True, rl_elastic_quorum_timeout_s=1800) + lines, tape, now = [], ScriptedTape(), [0.0] + watch = st.StragglerWatch(tape, cycles=3, log=lines.append, clock=lambda: now[0], + quiet_s=st.quiet_window_s(args, upload_s=30.0)) + tape.pending.append(_join(0)) + step = 0 + for _ in range(4 * 3600 // 30): + now[0] += 30 + if now[0] % 600 == 0: + step += 1 + tape.pending.append(_step(step, [0, 1], fragments=1)) + watch.poll(RUN2) + assert lines == [] and watch.notices() == [] + + +def test_the_launcher_reads_the_store_copy_for_an_island_launch_only(tmp_path, monkeypatch): + from yeto import launcher + + monkeypatch.delenv("YETO_RL_TAPE_UPLOAD_S", raising=False) + states = types.SimpleNamespace(objects=DirectoryObjectStore(tmp_path / "s")) + base = {"training_mode": "rl", "rl_sync_island_lease_s": 30.0, "rl_checkpoint_store": "s3://b/runs/r"} + island = types.SimpleNamespace(**base, rl_fleet_role="island") + assert isinstance(launcher._island_straggler_watch(island, states, None).source, st.StoreTape) + group = types.SimpleNamespace(**base, rl_fleet_role=None) # one launch: its syncer's tape is not uploaded + off = launcher._island_straggler_watch(group, states, None) + assert isinstance(off, st.UnavailableWatch) and "a VM of its own" in off.reason + local = types.SimpleNamespace(event_tape=str(tmp_path / "tape.jsonl"), _event_offset=5) + watch = launcher._island_straggler_watch(group, states, local) + assert isinstance(watch.source, st.FileTape) and watch.source.offset == 5 + assert launcher._island_straggler_watch(island, None, None) is None # no island records: nothing written + local_store = types.SimpleNamespace(**dict(base, rl_checkpoint_store=str(tmp_path / "d")), rl_fleet_role="island") + assert "not an object store" in launcher._island_straggler_watch(local_store, states, None).reason + monkeypatch.setenv("YETO_RL_TAPE_UPLOAD_S", "0") + assert "upload is off" in launcher._island_straggler_watch(island, states, None).reason + with pytest.raises(SystemExit, match="whole number"): + launcher._island_straggler_watch(types.SimpleNamespace(**base, rl_island_straggler_cycles=-1), states, local) + + +def test_a_flagged_island_that_stops_running_is_cleared_naming_why(tmp_path): + from yeto.launch import fleet as lf + + for setup, why in ((lambda rec: rec.update(draining=True), "stopped or removed (island STOP)"), + (lambda rec: rec.update(state=lf.RECOVERING), "recovering"), + (lambda rec: rec.update(state=lf.DONE), "not running (done)")): + ctl, _ops, store, tape, log = _controller(tmp_path / why.split()[0]) + tape.pending += [_join(0), _join(1), _step(1, [0, 1], fragments=1), _step(2, [0], fragments=1)] + ctl._poll_stragglers() + assert store.read(1)["straggler"]["action"] == "wait" + setup(ctl.learners["r-l1"]) + ctl._poll_stragglers() + (cleared,) = log.kinds(st.CLEARED_EVENT) + assert cleared[1] == "r-l1" and cleared[2]["reason"] == why + assert store.read(1)["straggler"] is None + + +def test_the_watch_s_notices_are_written_once_as_unavailable(tmp_path): + ctl, _ops, _store, _tape, log = _controller(tmp_path) + ctl.straggler = st.UnavailableWatch("the run store is not an object store") + ctl._poll_stragglers() + ctl._poll_stragglers() + why = {"reason": "the run store is not an object store"} + assert [e[1:] for e in log.kinds(st.UNAVAILABLE_EVENT)] == [("r-l0", why), ("r-l1", why)] # once per island + + +def test_a_watch_read_again_writes_available(tmp_path): + ctl, _ops, _store, _tape, log = _controller(tmp_path) + ctl.straggler._notices.append((st.AVAILABLE_EVENT, "syncer records read again")) + ctl._poll_stragglers() + assert [e[1] for e in log.kinds(st.AVAILABLE_EVENT)] == ["r-l0", "r-l1"] + + +def _unreadable_record(store, island, times): + """Island ``island``'s record read fails ``times`` times (a 503 of the store), then reads.""" + real, left = store.objects.read, [times] + + def read(key): + if key == lc.state_key(island) and left[0] > 0: + left[0] -= 1 + raise OSError("503 Slow Down") + return real(key) + + store.objects.read = read + return left + + +def test_a_left_mark_whose_record_does_not_read_is_cleared_at_a_later_poll(tmp_path): + ctl, _ops, store, _tape, log = _controller(tmp_path) + store.write(1, "running", straggler={"action": "wait", "missed_cycles": 3, "merges": 3, "fragments": 1, + "newest_step": 9, "last_merged_step": 6, "at": 1.0}) + _unreadable_record(store, 1, 1) + ctl._poll_stragglers() # its record did not read: no verdict, tried again + assert not log.kinds(st.CLEARED_EVENT) + ctl._poll_stragglers() + (cleared,) = log.kinds(st.CLEARED_EVENT) + assert cleared[2]["reason"] == "controller restarted" and store.read(1)["straggler"] is None + ctl._poll_stragglers() + assert len(log.kinds(st.CLEARED_EVENT)) == 1 + + +def test_a_mark_this_watch_wrote_while_the_record_did_not_read_is_kept(tmp_path): + ctl, _ops, store, tape, log = _controller(tmp_path) + left = _unreadable_record(store, 1, 10**6) + tape.pending += [_join(0), _join(1), _step(1, [0, 1], fragments=1), _step(2, [0], fragments=1)] + ctl._poll_stragglers() # reported by this watch while its record does not read + assert [e[1] for e in log.kinds(st.EVENT)] == ["r-l1"] + left[0] = 0 + ctl._poll_stragglers() + assert not log.kinds(st.CLEARED_EVENT) and store.read(1)["straggler"]["action"] == st.WAIT + + +def test_without_a_recover_timeout_a_new_island_has_the_default_grace(tmp_path): + """Relaunch off (--no-island-relaunch, --modal-retries 0): no recover timeout, so a new + island's catch-up has DEFAULT_GRACE_S.""" + ctl, ops, _store, tape, log = _controller(tmp_path, recover_timeout=0) + tape.pending += [_join(0), _step(1, [0], fragments=1)] + ctl._poll_stragglers() + tape.pending.append(_join(1)) # added: it catches up + ctl._poll_stragglers() + step, start = 1, ops.t + while ops.t + 30 < start + st.DEFAULT_GRACE_S: + ops.t += 30 + step += 1 + tape.pending.append(_step(step, [0], fragments=1, absent=[1])) + ctl._poll_stragglers() + assert not log.kinds(st.EVENT) + for _ in range(2): # its grace runs out, then N = 1 cycle on + ops.t += 30 + step += 1 + tape.pending.append(_step(step, [0], fragments=1, absent=[1])) + ctl._poll_stragglers() + (event,) = log.kinds(st.EVENT) + assert event[1] == "r-l1" and "catch-up grace" in event[2]["reason"] + + +def test_the_mark_is_stamped_with_wall_time_as_the_record(tmp_path): + import time + + ctl, ops, store, tape, _log = _controller(tmp_path) + ops.t = 5.0 # the controller's own clock is not wall time + tape.pending += [_join(0), _join(1), _step(1, [0, 1], fragments=1), _step(2, [0], fragments=1)] + before = time.time() + ctl._poll_stragglers() + record = store.read(1) + assert before - 1 <= record["straggler"]["at"] <= time.time() + 1 + assert abs(record["straggler"]["at"] - record["updated"]) < 1 + + +def test_a_mark_an_earlier_launcher_left_is_cleared_once_and_judged_again(tmp_path): + ctl, _ops, store, tape, log = _controller(tmp_path) + store.write(1, "running", straggler={"action": "wait", "missed_cycles": 3, "merges": 3, "fragments": 1, + "newest_step": 9, "last_merged_step": 6, "at": 1.0}) + ctl._poll_stragglers() + (cleared,) = log.kinds(st.CLEARED_EVENT) + assert cleared[1] == "r-l1" and cleared[2]["reason"] == "controller restarted" + assert cleared[2]["missed_cycles"] == 3 and store.read(1)["straggler"] is None + assert (store.read(0) or {}).get("straggler") is None and not log.kinds(st.EVENT) + tape.pending += [_step(10, [0], fragments=1, absent=[1])] # adopted: it joined before this watch + ctl._poll_stragglers() + assert [e[1] for e in log.kinds(st.EVENT)] == ["r-l1"] # judged again by this watch, at once + assert len(log.kinds(st.CLEARED_EVENT)) == 1 diff --git a/tests/test_island_straggler_spares.py b/tests/test_island_straggler_spares.py new file mode 100644 index 000000000..1db700ccf --- /dev/null +++ b/tests/test_island_straggler_spares.py @@ -0,0 +1,195 @@ +"""A straggler island that loses a node and waits for a spare (yeto.launch.island_straggler +over yeto.launch.island_spares): its mark is cleared when it leaves running, it is never +reported while it recovers and waits for a spare, and the island back on its spare is judged +from its new launch. Over the fake SSH cluster and the fakes of test_ssh_island_spares.""" + +from __future__ import annotations + +from test_island_straggler import Recorder, ScriptedTape, _join, _step +from test_rl_ssh_resident import Clock, _cards, make_ops, wait_for # noqa: F401 - _cards: autouse +from test_ssh_island_spares import ( + NAMES, + Cluster, + _controller, + _health, # noqa: F401 - autouse: the fake health checker + islands_spec, + make_spares, + spare, +) + +from yeto.launch import island_lifecycle as lc +from yeto.launch import island_straggler as st +from yeto.launch.fleet import RECOVERING, RUNNING +from yeto.rl.engine.object_store import DirectoryObjectStore + +OTHER = 9 # an island of another launch the syncer merges each round + + +def _fleet(tmp_path): + 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") + store = lc.IslandStateStore(DirectoryObjectStore(tmp_path / "records")) + tape, log = ScriptedTape(), Recorder() + ctl = _controller(ops, recover_timeout=600.0, fleet_log=log, + recorder=lc.FleetRecorder(store, {"isl": lc.IslandRef(0, "ssh")}), + straggler=st.StragglerWatch(tape, cycles=1, log=lambda m: None)) + ctl.ops.sky_ops.t = 0.0 + ctl.ops.now = lambda: clock.t + return cluster, ops, spares, ctl, store, tape, log, clock + + +def test_a_straggler_that_loses_a_node_is_cleared_and_not_reported_while_it_waits_for_a_spare(tmp_path): + cluster, ops, spares, ctl, store, tape, log, clock = _fleet(tmp_path) + rec = ctl.learners["isl"] + step = 0 + + def merges(*merged, absent=()): + nonlocal step + for _ in range(2): + step += 1 + tape.pending.append(_step(step, list(merged), fragments=1, absent=absent)) + + def poll(): + clock.t += 30 + ctl._poll_recorded(rec) + ctl._poll_stragglers() + + poll() + assert rec["state"] == RUNNING + tape.pending += [_join(0), _join(OTHER)] + merges(0, OTHER) + poll() + assert not log.kinds(st.EVENT) + merges(OTHER, absent=[0]) # stuck while connected: merged without it + poll() + assert [e[1] for e in log.kinds(st.EVENT)] == ["isl"] and store.read(0)["straggler"]["action"] == st.WAIT + + spares.records.claim("b300-3", "isl-other") # no free spare: the island waits + cluster.lose(NAMES[1]) + assert wait_for(lambda: ops.islands["isl"].job.procs[1].poll() is not None) + for _ in range(3): # its source finds the node lost after 2 unanswered checks + merges(OTHER, absent=[0]) + poll() + if rec["state"] != RUNNING: + break + # the poll that finds the node lost also clears the mark (it left running), and the + # merges without it meanwhile never reported it a second time + assert rec["state"] == RECOVERING + assert [k for k, _, _ in log.events][1:] == ["island_lost", "island_node_lost", "island_waiting_spare", + st.CLEARED_EVENT] + (cleared,) = log.kinds(st.CLEARED_EVENT) + assert cleared[2]["reason"] == "recovering" and store.read(0)["straggler"] is None + for _ in range(24): # 12 min of waiting, past the 600 s recover timeout; the others merge on + merges(OTHER, absent=[0]) + poll() + assert rec["state"] == RECOVERING + assert len(log.kinds(st.EVENT)) == 1 and len(log.kinds(st.CLEARED_EVENT)) == 1 # never reported meanwhile + assert store.read(0)["straggler"] is None + + spares.records.unclaim("b300-3", "isl-other") # the spare is free: replaced + for _ in range(40): + poll() + if rec["state"] == RUNNING: + break + assert rec["state"] == RUNNING and rec["job_id"] == 1 + assert [f["spare"] for k, _, f in log.events if k == "island_node_replaced"] == ["b300-3"] + # its new launch catches up on the spare while the syncer lists it absent: a new launch + # is not counted before its first merged push, for up to its recover timeout (600 s) + for _ in range(15): # 7.5 min, 15 merge cycles past N = 1 + merges(OTHER, absent=[0]) + poll() + assert len(log.kinds(st.EVENT)) == 1 and store.read(0)["straggler"] is None + tape.pending.append(_join(0)) # caught up, then it pushes: counted as usual from here + merges(0, OTHER) + poll() + assert len(log.kinds(st.EVENT)) == 1 and store.read(0)["state"] == lc.RUNNING + merges(OTHER, absent=[0]) # stuck again on its spare: judged by this launch's merges + poll() + assert len(log.kinds(st.EVENT)) == 2 and store.read(0)["straggler"]["last_merged_step"] == step - 2 + assert "catch-up grace" not in log.kinds(st.EVENT)[1][2]["reason"] + merges(0, OTHER) + poll() + assert [e[2]["reason"] for e in log.kinds(st.CLEARED_EVENT)] == ["recovering", "a push of it is merged again"] + + +def test_a_spare_s_catch_up_past_the_recover_timeout_is_reported_n_cycles_later(tmp_path): + cluster, ops, _spares, ctl, _store, tape, log, clock = _fleet(tmp_path) + rec = ctl.learners["isl"] + step = 0 + + def merges(*merged, absent=()): + nonlocal step + step += 1 + tape.pending.append(_step(step, list(merged), fragments=1, absent=absent)) + + def poll(): + clock.t += 30 + ctl._poll_recorded(rec) + ctl._poll_stragglers() + + poll() + tape.pending += [_join(0), _join(OTHER)] + merges(0, OTHER) + poll() + cluster.lose(NAMES[1]) # a free spare: replaced at once + assert wait_for(lambda: ops.islands["isl"].job.procs[1].poll() is not None) + for _ in range(10): # found lost, then replaced (no merge meanwhile: it ran up to its loss) + poll() + if rec["state"] == RUNNING and rec["job_id"] == 1: + break + assert rec["state"] == RUNNING and rec["job_id"] == 1 + back = clock.t # its controller holds the new launch running: its grace starts + tape.pending.append(_join(0)) + while clock.t + 30 < back + 600.0: # never pushes: not counted for its recover timeout + merges(OTHER, absent=[0]) + poll() + assert not log.kinds(st.EVENT) + merges(OTHER, absent=[0]) + poll() # the grace runs out: counted from here + assert not log.kinds(st.EVENT) + merges(OTHER, absent=[0]) + poll() # N = 1 cycle later: reported + (event,) = log.kinds(st.EVENT) + assert event[2]["missed_cycles"] == 1 and "catch-up grace" in event[2]["reason"] + + +def test_the_dashboard_with_a_straggler_that_loses_a_node_and_is_replaced(tmp_path): + """The fleet events of the case above on the dashboard: the badge goes with the clear, + the spare events leave the card's straggler and lifecycle state as the controller has them.""" + from test_dashboard_fleet_islands import fleet_reducer + from test_dashboard_island_straggler import _cards as dash_cards + from test_dashboard_island_straggler import _smoke + + r = fleet_reducer() + t, name = r.max_ts, "fleet-qa-l1-modal" + + def fleet(event, dt, **fields): + r.feed({"event": event, "time_unix": t + dt, "island": name, "island_id": 1, **fields}) + return dash_cards(r)["1"] + + card = fleet(st.EVENT, 10, action=st.WAIT, missed_cycles=2, merges=2, fragments=1, newest_step=40, + last_merged_step=38, absent=True) + assert card["straggler"]["missed_cycles"] == 2 + fleet("island_lost", 20, reason="job FAILED") + fleet("island_node_lost", 20, node="b300-1", rank=1, reason="power") + fleet("island_waiting_spare", 20, lost="b300-1", reason="no free spare") + card = fleet(st.CLEARED_EVENT, 20, missed_cycles=2, reason="relaunched") + assert card["straggler"] is None and card["status"] not in ("ok", "running") + out = _smoke(tmp_path / "waiting", r) + assert "straggler" not in out["texts"] and "straggler" not in out["nodes"] + fleet("island_node_replaced", 400, lost="b300-1", spare="b300-3", resume_step=7) + fleet("island_launch", 401, incarnation=1) + card = fleet("island_ready", 402) + assert card["straggler"] is None + # its new launch's catch-up outlasted its recover timeout: reported again, by the new launch + card = fleet(st.EVENT, 500, action=st.WAIT, missed_cycles=2, merges=2, fragments=1, newest_step=52, + last_merged_step=None, absent=True) + assert card["straggler"]["last_merged_step"] is None + out = _smoke(tmp_path / "again", r) + assert out["nodes"].count('straggler') == 1 + card = fleet(st.CLEARED_EVENT, 520, missed_cycles=0, reason="a push of it is merged again") + assert card["straggler"] is None and r.island("1")["fleet_state"] == "ready" diff --git a/tests/test_own_clusters_islands_doc.py b/tests/test_own_clusters_islands_doc.py new file mode 100644 index 000000000..0290640d7 --- /dev/null +++ b/tests/test_own_clusters_islands_doc.py @@ -0,0 +1,78 @@ +"""docs/OWN_CLUSTERS.md, "Islands that lag, join or leave": every command of the section +parses, the ``yeto fleet island`` ones run in the doc's order on a seeded per-island fleet +(local store), each dry run writes nothing, and the flags and events the section names are +the code's.""" + +from __future__ import annotations + +import re +import shlex +import types +from pathlib import Path + +from test_fleet_island_changes import fleet_store # noqa: F401 - fixture + +from yeto.launch import island_straggler as st +from yeto.rl import fleet, fleet_islands + +DOC = Path(__file__).resolve().parents[1] / "docs" / "OWN_CLUSTERS.md" +SECTION = "## Islands that lag, join or leave" + + +def section() -> str: + text = DOC.read_text() + start = text.index(SECTION) + end = text.find("\n## ", start + len(SECTION)) + return text[start:] if end < 0 else text[start:end] + + +def commands() -> list[list[str]]: + out = [] + for block in re.findall(r"```bash\n(.*?)```", section(), flags=re.DOTALL): + out += [shlex.split(line) for line in block.replace("\\\n", " ").splitlines() if line.strip()] + inline = re.findall(r"`(yeto island (?:stop|start) [^`]+)`", section()) + return out + [shlex.split(c) for c in inline] + + +def test_the_section_names_the_code_s_flags_and_events(): + text = section() + assert "--rl-island-straggler-cycles" in text and f"`{st.DEFAULT_CYCLES}` is the default" in text + for name in (st.EVENT, st.CLEARED_EVENT, st.UNAVAILABLE_EVENT, st.AVAILABLE_EVENT, st.WAIT, + st.SYNCER_TAPES.rstrip("/"), "controller restarted"): + assert name in text + assert f"at least {st.QUIET_MIN_S / 60:g} minutes" in text and f"every {st.STORE_POLL_S:g} s" in text + from yeto.launch.syncer import SYNCER_DEFAULT_QUORUM_TIMEOUT_S + + defaults = st.quiet_window_s(types.SimpleNamespace(), upload_s=st.STORE_POLL_S) + flat = " ".join(text.split()) + assert f"quorum timeout of {SYNCER_DEFAULT_QUORUM_TIMEOUT_S} s). The longest round is the larger of the two: " \ + f"with the defaults, the window is {defaults / 60:g} minutes" in flat + assert f"at most {st.STORE_GETS_PER_POLL} chunks" in text and f"every {st.STORE_DISCOVER_POLLS} reads" in text + assert f"up to {st.CLOCK_SKEW_S / 60:g} minutes before" in text + assert "(`--recover-timeout`" in text and "catch-up grace ran out" in text # a new launch's grace + assert f"{st.DEFAULT_GRACE_S / 60:g}\n minutes when relaunch is off" in text + for field in st.Straggler.__dataclass_fields__: + if field not in ("island", "cleared", "cycles", "reason"): + assert f"`{field}`" in text, field + + +def test_the_section_commands_run_in_order(fleet_store, capsys): # noqa: F811 + from yeto.cli import build_parser + + cfg, _objects, store, run_cli, _samplers = fleet_store + argvs = commands() + assert {a[1] for a in argvs} == {"fleet", "island"} + for argv in argvs: + build_parser().parse_args(argv[1:]) + plan = fleet.plan_of(cfg) # the island the section removes + entry = dict(cfg["islands"][1]["samplers"][0], name="sglang-north") + member, pools = fleet_islands.compile_island(cfg, plan, k=2, name="north", gpu="modal:1x2xh100", usd_per_h=8.0, + samplers=[entry]) + store.update(lambda d: fleet_islands.add(d, member, pools), note="add north") + for argv in (a for a in argvs if a[:3] == ["yeto", "fleet", "island"]): + rest = argv[3:] + config = rest.index("--config") + del rest[config:config + 2] + before = store.read()["generation"] + assert run_cli(*rest) == 0, (argv, capsys.readouterr().err) + assert store.read()["generation"] == before + (0 if "--dry-run" in argv else 1) diff --git a/tests/test_ssh_island_fleet_e2e.py b/tests/test_ssh_island_fleet_e2e.py new file mode 100644 index 000000000..27543979c --- /dev/null +++ b/tests/test_ssh_island_fleet_e2e.py @@ -0,0 +1,640 @@ +"""SSH trainer islands that join, leave and lag a training fleet, end to end +(own-cluster-fleet-stability 9.1 and 9.2): the real Rust syncer, the trainer worker +reconciling the desired state on a local store, and for each island launch the launcher's +own fleet controller over the resident ``ssh:`` island ops (``yeto.launch.ssh_resident``) on +a fake SSH cluster. Rank 0 of each island is its trainer: its start on the fake nodes +connects a syncer client under the island's learner id, its kill drops the connection. No +cloud, no Ray, no GPU. + +Two islands (``ssh:2x8xb300@bm``, two nodes each) train. Then, one case each: + +* **add**: ``yeto fleet island add`` (its functions) writes a third island into the desired + state; the worker starts its launch on two more nodes, the island catches up to the newest + outer weights and its pushes are merged from then on. +* **remove**: ``remove`` takes island 1 out; the worker writes its island STOP, its + controller drains it, releases its nodes (the kill on each node), and the rounds merge over + island 0 alone. +* **stuck**: island 1's trainer stops pushing while it stays connected (heartbeats). The + syncer merges island 0 at the quorum deadline and excuses island 1; island 1's controller + writes ``island_straggler`` (action ``wait``) once three merge cycles went by without a push + of it, nothing is stopped or relaunched, and once it pushes again its controller writes + ``island_straggler_cleared``. + +Each case checks that the other islands' processes never restarted (one start per node, no +kill before the end, one launch), that the merged steps run 1..N without a gap or a repeat, +that no push is merged twice, and that the resource ledger holds each SSH incarnation once. + +A fourth test runs the stuck case over the per-island wiring: each launch's watch is the +launcher's own for its argv and reads the syncer's tape from the run store, uploaded in +chunks, past an earlier syncer's history; island 1 is relaunched while it is reported. +""" + +from __future__ import annotations + +import json +import threading +import time +from collections import Counter + +import pytest +from test_fleet_island_launches import example_doc +from test_fleet_trainer_worker import FakeLaunches +from test_rl_full_parameter_async import ( + _f32, + _initial, + _start_async_syncer, + _wait, + needs_cargo, + syncer_binary, # noqa: F401 - fixture +) +from test_rl_full_parameter_dynamic_members import ( + LAUNCHED, + MAX_LEARNERS, + POOL, + P, + _client, + _delta, + _outer_steps, +) +from test_rl_ssh_resident import FakeCluster, b300 + +from yeto.cost.ledger import ResourceLedger +from yeto.hw import card_tools +from yeto.launch import island_lifecycle as lifecycle +from yeto.launch import island_straggler as st +from yeto.launch.fleet import FleetController +from yeto.launch.learner_ids import allocate_learner_id +from yeto.launch.pool import desired as dz +from yeto.launch.ssh_resident import SshIslandOps +from yeto.launch.ssh_trainer_island import SshTrainerSpec +from yeto.launch.ssh_trainer_ledger import KIND as SSH_TRAINER +from yeto.modal_runner import RoutingOps +from yeto.rl import fleet, fleet_islands, island_launches, trainer_worker, up +from yeto.rl.engine.object_store import DirectoryObjectStore + +GPU = "ssh:2x8xb300@bm" +NODES = {k: (b300(2 * k), b300(2 * k + 1)) for k in range(MAX_LEARNERS)} # island k on nodes 2k, 2k+1 +CYCLES = 3 +# the stuck case: a short soft deadline, so a round that waits for the silent island merges +# island 0's push after 2 s (the quorum deadline of an island pool, #865) +STUCK_POOL = tuple({"30": "2"}.get(a, a) for a in POOL) + + +@pytest.fixture(autouse=True) +def _ssh_nodes(monkeypatch, tmp_path): + monkeypatch.setattr(card_tools, "check_cards", lambda family, text, **kw: []) + monkeypatch.setenv("YETO_RESOURCE_LEDGER", str(tmp_path / "ledger.jsonl")) + monkeypatch.setenv("YETO_ISLAND_HMAC_KEY", "ssh-island-fleet-test-key") + + +class TrainerCluster(FakeCluster): + """The fake nodes of every island; rank 0's start and kill are its trainer's.""" + + def __init__(self) -> None: + super().__init__([n.name for nodes in NODES.values() for n in nodes]) + self.rank0 = {nodes[0].name: k for k, nodes in NODES.items()} + self.trainer_starts: list[int] = [] + self.trainer_kills: list[int] = [] + self.trainer_events: list[tuple[str, int]] = [] # both, in order (a relaunch: kill, then start) + self.guard = threading.Lock() + + def start(self, node, script): + stream = super().start(node, script) + if "setsid bash -c" in script and node.name in self.rank0: + with self.guard: + self.trainer_starts.append(self.rank0[node.name]) + self.trainer_events.append(("start", self.rank0[node.name])) + return stream + + def run(self, node, script, *, timeout=300.0): + out = super().run(node, script, timeout=timeout) + if "kill -TERM" in script and node.name in self.rank0: + with self.guard: + self.trainer_kills.append(self.rank0[node.name]) + self.trainer_events.append(("kill", self.rank0[node.name])) + return out + + def finish(self, k: int) -> None: + """Island k's trainer ended its run: every rank of its newest incarnation exits 0 (rank 0 last).""" + for node in reversed(NODES[k]): + runs = self.runs[node.name] + if runs and runs[max(runs)].get("state") == "running": + self.exit(node.name, max(runs), 0) + + +class FastClock: + """The island controller's sky side: fake time, 30 s per poll in 10 ms.""" + + def __init__(self) -> None: + self.t = 0.0 + + def now(self): + return self.t + + def sleep(self, seconds): + time.sleep(0.01) + self.t += seconds + + +class FleetLog: + def __init__(self) -> None: + self.events: list[tuple[str, str, dict]] = [] + + def event(self, kind, name, **fields): + self.events.append((kind, name, fields)) + + def maybe_tick(self): + pass + + def cost_tick(self): + pass + + def kinds(self, kind): + return [e for e in list(self.events) if e[0] == kind] + + +class _SyncThread: + def __init__(self, target, daemon=None): + self.target = target + + def start(self): + self.target() + + def join(self, timeout=None): + pass + + +class SshIslandLaunches(FakeLaunches): + """Each island launch is what ``yeto launch --gpu ssh:...`` runs for one island of a + fleet: the resident ssh: island ops on its inventory nodes and the fleet controller + supervising it (its island STOP, its record, the straggler watch), on a thread.""" + + def __init__(self, tmp_path, cluster: TrainerCluster, objects, tape, watch=None) -> None: + super().__init__() + self.tmp_path, self.cluster, self.objects, self.tape = tmp_path, cluster, objects, tape + # the straggler watch of a launch (its argv, its island records); the syncer's tape file by default + self.watch = watch or (lambda argv, states: st.StragglerWatch(st.FileTape(tape), cycles=CYCLES, + log=lambda m: None)) + self.controllers: dict[int, FleetController] = {} + self.logs: dict[int, FleetLog] = {} + self.errors: list[BaseException] = [] + + def start(self, prefix: str, argv: list[str]) -> int: + pid = super().start(prefix, argv) + k = int(argv[argv.index("--rl-fleet-learner-id") + 1]) + assert argv[argv.index("--gpu") + 1] == GPU + name = f"{prefix}-trainer" + ops = SshIslandOps(run_id=prefix, journal_dir=self.tmp_path / "runs" / prefix / "ssh-islands", + events_dir=self.tmp_path / "events" / prefix, ops=self.cluster, log=lambda m: None) + spec = SshTrainerSpec(nodes=NODES[k], run_id=prefix, workdir="/opt/yeto", run_script="echo island", env={}) + ops.add(name, spec) + job = ops.start(name) + log = self.logs[k] = FleetLog() + states = lifecycle.IslandStateStore(self.objects, log=lambda m: None) + recorder = lifecycle.FleetRecorder(states, {name: lifecycle.IslandRef(k, "ssh")}) + ctl = self.controllers[k] = FleetController( + learners={name: (spec, job)}, syncer=None, sky_ops=RoutingOps(FastClock(), None, ssh_ops=ops), + poll_interval=30.0, recover_timeout=600.0, thread_cls=_SyncThread, recorder=recorder, elastic=True, + deterministic_stop=True, fleet_log=log, + straggler=self.watch(argv, states)) + + def supervise(): + code = 0 + try: + ctl.run() + except BaseException as error: # noqa: BLE001 - reported by the test + self.errors.append(error) + code = 1 + self.end(prefix, code) + + threading.Thread(target=supervise, daemon=True).start() + return pid + + +def _config(tmp_path): + doc = example_doc(tmp_path, max_islands=MAX_LEARNERS) + for island in doc["islands"]: + island["trainer"].update(gpu=GPU, usd_per_h=0.0) # own machines + path = tmp_path / "run.json" + path.write_text(json.dumps(doc)) + return up.load_config(str(path)) + + +@needs_cargo +@pytest.mark.parametrize("case", ["add", "remove", "stuck"]) +def test_ssh_islands_join_leave_and_lag_without_touching_the_other_islands(syncer_binary, tmp_path, # noqa: F811 + case): + cfg = _config(tmp_path) + plan = fleet.plan_of(cfg) + objects = DirectoryObjectStore(tmp_path / "store") + store = dz.DesiredStore(objects) + members = island_launches.trainer_members(cfg, plan) + store.apply({"members": [*members, *({"kind": "sampler_pool", "name": p.name, "island": i.index, + "pool": {"provider": "modal"}} for i in plan.islands for p in i.pools)]}, + expect=0) + total_steps, change_at = 12, 3 + process, port, profile_hash = _start_async_syncer( + syncer_binary, tmp_path, *(STUCK_POOL if case == "stuck" else POOL), total_steps=total_steps, + log_file=tmp_path / "syncer.log") + tape = tmp_path / "tape.jsonl" + island_launches.write_syncer_record(objects, addr=f"127.0.0.1:{port}", syncer_epoch=0, learners=LAUNCHED, + max_learners=MAX_LEARNERS, run="r") + states = lifecycle.IslandStateStore(objects, log=lambda m: None) + cluster = TrainerCluster() + launches = SshIslandLaunches(tmp_path, cluster, objects, tape) + worker = trainer_worker.TrainerWorker(store, objects, launches, states, log=lambda m: None) + + clients: dict[int, object] = {} + started = Counter() + gone: list[int] = [] + catching: dict[int, dict] = {} + versions = {k: [0] * P for k in range(MAX_LEARNERS)} + seen: dict[int, set] = {k: set() for k in range(MAX_LEARNERS)} + held: dict[int, list] = {} + state = {"changed": False, "stuck": False, "flagged": False, "cleared": False, "joined_at": None} + beat = [0.0] + + def follow_the_nodes(): + with cluster.guard: + starts, kills = list(cluster.trainer_starts), list(cluster.trainer_kills) + for k in starts[sum(started.values()):]: + started[k] += 1 + client = _client(k, port, profile_hash) + client.start() + clients[k] = client + if k >= LAUNCHED: + catching[k] = {} + for k in kills: + if k in clients and k not in gone: # its machines torn down: the connection just drops + clients.pop(k).close() + gone.append(k) + + def drain(k): + client = clients[k] + client.check_health() + if k in catching: # a joiner applies its catch-up before it answers a PULL + caught = catching[k] + for update in client.drain_updates(): + caught.setdefault(update.fragment_id, update.version) + held.setdefault(k, []).extend(client.drain_pulls()) + if len(caught) < P: + return + versions[k] = [caught[fid] for fid in range(P)] + state["joined_at"] = list(versions[k]) # the outer versions its catch-up brought + del catching[k] + for update in client.drain_updates(): + versions[k][update.fragment_id] = max(versions[k][update.fragment_id], update.version) + if case == "stuck" and k == 1 and state["stuck"]: + return # connected (its heartbeats go on), delivering nothing + for permit in held.pop(k, []) + client.drain_pulls(): + key = (permit.global_step, permit.round_attempt) + if key in seen[k]: + continue + seen[k].add(key) + client.push_fragment(permit.fragment_id, permit.global_step, permit.round_attempt, + versions[k][permit.fragment_id], permit.global_step, 1, 7, + _f32(_delta(k, permit.global_step))) + + def change(): + if case == "add": + k = allocate_learner_id(objects, launched=LAUNCHED, max_learners=MAX_LEARNERS, island="north") + entry = dict(cfg["islands"][1]["samplers"][0], name="sglang-north") + member, pools = fleet_islands.compile_island(cfg, plan, k=k, name="north", gpu=GPU, usd_per_h=0.0, + samplers=[entry]) + store.update(lambda d: fleet_islands.add(d, member, pools), note="add north") + elif case == "remove": + store.update(lambda d: fleet_islands.remove(d, "sglang"), note="remove island 1") + else: + state["stuck"] = True + state["changed"] = True + + def poll(): + assert not launches.errors, launches.errors + if time.monotonic() - beat[0] > 1: # every connected island renews its lease + beat[0] = time.monotonic() + for client in list(clients.values()): + client.heartbeat(0) + worker.step() + follow_the_nodes() + for k in list(catching) or list(clients): + drain(k) + if catching: + return False # a joiner catches up before the fleet moves on + if not state["changed"] and len(clients) == LAUNCHED and min(versions[0]) >= change_at: + change() + if case == "stuck" and state["stuck"] and launches.logs[1].kinds(st.EVENT): + state["stuck"], state["flagged"] = False, True # reported: it pushes again + if case == "stuck" and state["flagged"] and launches.logs[1].kinds(st.CLEARED_EVENT): + state["cleared"] = True + done = all(c.finalizing.is_set() for c in clients.values()) + if case == "add": + return done and 2 in clients and state["joined_at"] is not None + if case == "remove": + return done and 1 in gone + return done and state["cleared"] + + finals = {} + try: + worker.step() # islands 0 and 1 start on their nodes + follow_the_nodes() + assert sorted(clients) == [0, 1] + for fid in range(P): + clients[0].send_init(fid, _f32(_initial(fid))) + _wait(poll, f"the fleet never finalized ({case})", timeout=240) + for k, client in clients.items(): + manifest, _fragments = client.wait_for_final_fragments(timeout=30) + finals[k] = manifest + client.acknowledge_finalization(manifest) + assert process.wait(timeout=15) == 0 + for k in list(clients): + cluster.finish(k) # the trainers end their run: every launch ends by its trainer + _wait(lambda: all(launches.ended(m["prefix"]) is not None for m in worker_members(store, case)), + "an island launch did not end", timeout=60) + finally: + for client in clients.values(): + client.close() + if process.poll() is None: + process.terminate() + process.wait(timeout=10) + assert not launches.errors, launches.errors + + # -- the other islands were never touched: one start per node, one launch, no kill before the end. + # Limit: these count the start / kill scripts the control plane sent to the fake nodes (and the + # worker's launches), not OS processes; they prove yeto restarted nothing, not that nothing on + # a real node could restart a rank by itself. + others = {"add": [0, 1], "remove": [0], "stuck": [0, 1]}[case] + for k in others: + assert started[k] == 1 and launches.started(f"r-i{k}") == 1 + assert [sum(1 for c in cluster.calls if c[:2] == ("start", n.name)) for n in NODES[k]] == [1, 1] + kills_before_end = [k for k in cluster.trainer_kills if k in gone] + assert kills_before_end == ([1] if case == "remove" else []) + if case == "add": + assert started[2] == 1 and launches.started("r-i2") == 1 + if case == "remove": + assert all(sum(1 for c in cluster.calls if c[:2] == ("kill", n.name)) >= 1 for n in NODES[1]) + worker.step() + assert worker.load(1)["state"] == trainer_worker.REMOVED + + # -- the merges: steps 1..N without a gap or a repeat, no push merged twice. + # Limit: a push is keyed by (island, the step it was pushed for); a delta carried into a later + # round keeps its own step, so this catches a double merge, not a wrong carry-over discount. + steps = _outer_steps(tape.read_text()) + assert [r["step"] for r in steps] == list(range(1, total_steps * P + 1)) + merged = [(int(e[0]), pushed) for r in steps for e, pushed in zip(r["raw_weights"], r["pushed_for"])] + assert len(merged) == len(set(merged)), Counter(merged).most_common(3) + for record in steps: + assert abs(sum(float(e[2]) for e in record["weights"]) - 1.0) < 1e-9 + contributors = {int(e[0]) for r in steps for e in r["raw_weights"]} + assert contributors == ({0, 1, 2} if case == "add" else {0, 1}) + if case == "add": # the joiner caught up to the merged weights of the add's time, then merged + first = min(r["step"] for r in steps if 2 in [int(e[0]) for e in r["raw_weights"]]) + assert min(state["joined_at"]) >= change_at and first > max(state["joined_at"]) + if case == "remove": + leave = next(r for r in _records(tape) if r.get("kind") == "pool_leave" and int(r["island_id"]) == 1) + # Limit: by wall time, skipping one cycle of rounds per fragment pair (2 x P): the rounds open + # at the leave may still merge a push island 1 sent before it; this does not pin the round + # its last push merged in, only that island 0 merges alone from then on. + after = [r for r in steps if r.get("time_unix", 0) > leave.get("time_unix", 0)][2 * P:] + assert after and all([int(e[0]) for e in r["raw_weights"]] == [0] for r in after) + + # -- the straggler: written once by island 1's controller, waiting; nobody else reported + if case == "stuck": + (event,) = launches.logs[1].kinds(st.EVENT) + assert event[2]["action"] == st.WAIT and event[2]["missed_cycles"] == CYCLES and event[2]["fragments"] == P + assert event[2]["absent"] is True + assert len(launches.logs[1].kinds(st.CLEARED_EVENT)) == 1 + assert states.read(1)["straggler"] is None # cleared in its record too + absent = [r for r in steps if r["absent"] == [1]] + # merged at the quorum deadline without it. Limit: "any", because which of the rounds without + # island 1 waited for the deadline depends on when its PULL was answered before it went silent + assert any(r["timed_out"] for r in absent) + assert launches.controllers[1].learners["r-i1-trainer"]["relaunches"] == 0 + for k, log in launches.logs.items(): + if case != "stuck" or k != 1: + assert not log.kinds(st.EVENT), (k, log.kinds(st.EVENT)) + + # -- the ledger: each ssh incarnation created once, released at most once + rows = [r for r in ResourceLedger(tmp_path / "ledger.jsonl").records() if r["kind"] == SSH_TRAINER] + created = Counter(r["id"] for r in rows if r["op"] == "create") + released = Counter(r["id"] for r in rows if r["op"] == "release") + islands = {"add": 3, "remove": 2, "stuck": 2}[case] + assert sorted(created) == sorted(f"r-i{k}/r-i{k}-trainer-i0" for k in range(islands)) + assert set(created.values()) == {1} and all(n == 1 for n in released.values()) + + +def _launch_args(argv): + """The args ``yeto launch`` parses from an island launch's argv.""" + from yeto.cli import build_parser + + return build_parser().parse_args(["launch", *argv]) + + +@needs_cargo +def test_a_stuck_island_relaunched_mid_run_is_watched_over_the_run_store(syncer_binary, tmp_path, # noqa: F811 + monkeypatch): + """The stuck case over the per-island wiring: each island launch's watch is the launcher's + own (``launcher._island_straggler_watch`` of its parsed argv and its island records), so it + reads the syncer's tape from the run store (a ``DirectoryObjectStore`` here), where the + syncer launch's uploaders copy it chunk by chunk (``tapes/syncer//``). The + store also holds an earlier syncer's history in which island 1 missed 40 merges: it is + never counted. Island 1 stops pushing and is reported once; then one of its ranks fails, + its controller relaunches it (cleared: recovering); the new incarnation joins again + (catch-up) and stays silent: a new launch is not counted before its first merged push for + up to its recover timeout, so it is reported again only after that grace and N merge cycles + more; then it pushes and the mark is cleared. Island 0 is never touched.""" + from yeto import launcher + from yeto.rl.engine.tape_upload import syncer_incarnation, syncer_uploaders + + monkeypatch.delenv("YETO_RL_TAPE_UPLOAD_S", raising=False) + cfg = _config(tmp_path) + plan = fleet.plan_of(cfg) + objects = DirectoryObjectStore(tmp_path / "store") + store = dz.DesiredStore(objects) + store.apply({"members": [*island_launches.trainer_members(cfg, plan), + *({"kind": "sampler_pool", "name": p.name, "island": i.index, + "pool": {"provider": "modal"}} for i in plan.islands for p in i.pools)]}, expect=0) + old = time.time() - 3600 # an earlier syncer of the run: island 1 missing from its last 40 merges + history = [{"kind": "pool_join", "island_id": k, "generation": 0, "syncer_epoch": 0, "time_unix": old} + for k in (0, 1)] + history += [{"kind": "outer_step", "step": n, "fragment": (n - 1) % P, "weights": [[0, n - 1, 1.0]], + "raw_weights": [[0, n - 1, 1.0]], "absent": [1], "time_unix": old + n} for n in range(1, 41)] + objects.write(f"{st.SYNCER_TAPES}oldhost-20200101T000000Z/00000000.jsonl", + "".join(json.dumps(r) + "\n" for r in history).encode()) + total_steps, change_at = 30, 3 + process, port, profile_hash = _start_async_syncer(syncer_binary, tmp_path, *STUCK_POOL, total_steps=total_steps, + log_file=tmp_path / "syncer.log") + tape = tmp_path / "tape.jsonl" + uploaders = syncer_uploaders(objects, tape, incarnation=syncer_incarnation(), interval_s=0.3, from_end=False, + log=lambda m: None) + island_launches.write_syncer_record(objects, addr=f"127.0.0.1:{port}", syncer_epoch=0, learners=LAUNCHED, + max_learners=MAX_LEARNERS, run="r") + states = lifecycle.IslandStateStore(objects, log=lambda m: None) + watches = {} + + def watch(argv, island_states): + w = launcher._island_straggler_watch(_launch_args(argv), island_states, None) + # a store read every 0.5 s, not every 30 s, so the case runs in seconds (the uploaders + # copy a chunk every 0.3 s). The silence that is said is derived from the launch's argv + # (no soft deadline there: two rounds of the 900 s default quorum timeout and two 30 s + # uploads), far longer than this case, so no unavailable notice is written here + w.source.interval_s = 0.5 + assert w.quiet_s == st.quiet_window_s(_launch_args(argv), upload_s=30.0) >= st.QUIET_MIN_S + watches[int(argv[argv.index("--rl-fleet-learner-id") + 1])] = w + return w + + cluster = TrainerCluster() + launches = SshIslandLaunches(tmp_path, cluster, objects, tape, watch=watch) + worker = trainer_worker.TrainerWorker(store, objects, launches, states, log=lambda m: None) + + clients: dict[int, object] = {} + catching: dict[int, dict] = {} + versions = {k: [0] * P for k in range(LAUNCHED)} + seen: dict[int, set] = {k: set() for k in range(LAUNCHED)} + held: dict[int, list] = {} + phase = {"name": "train", "events": 0} + beat = [0.0] + + def follow_the_nodes(): + with cluster.guard: + events = list(cluster.trainer_events) + for what, k in events[phase["events"]:]: + phase["events"] += 1 + if what == "kill" and k in clients: # its incarnation torn down: the connection drops + clients.pop(k).close() + elif what == "start": + if k in clients: + clients.pop(k).close() + clients[k] = _client(k, port, profile_hash) + clients[k].start() + if phase["name"] != "train": # a relaunched trainer catches up before it answers + catching[k] = {} + seen[k].clear() + + def drain(k): + client = clients[k] + client.check_health() + if k in catching: + for update in client.drain_updates(): + catching[k].setdefault(update.fragment_id, update.version) + held.setdefault(k, []).extend(client.drain_pulls()) + if len(catching[k]) < P: + return + caught = catching.pop(k) + versions[k] = [caught[fid] for fid in range(P)] + for update in client.drain_updates(): + versions[k][update.fragment_id] = max(versions[k][update.fragment_id], update.version) + if k == 1 and phase["name"] in ("stuck", "relaunching", "stuck again"): + held.pop(k, None) + client.drain_pulls() + return # connected (its heartbeats go on), delivering nothing + for permit in held.pop(k, []) + client.drain_pulls(): + key = (permit.global_step, permit.round_attempt) + if key in seen[k]: + continue + seen[k].add(key) + client.push_fragment(permit.fragment_id, permit.global_step, permit.round_attempt, + versions[k][permit.fragment_id], permit.global_step, 1, 7, + _f32(_delta(k, permit.global_step))) + + def poll(): + assert not launches.errors, launches.errors + if time.monotonic() - beat[0] > 1: + beat[0] = time.monotonic() + for client in list(clients.values()): + client.heartbeat(0) + worker.step() + follow_the_nodes() + for k in list(clients): + drain(k) + log = launches.logs[1] + if phase["name"] == "train" and len(clients) == LAUNCHED and min(versions[0]) >= change_at: + # the history in the store and the merges so far reported nobody + assert not log.kinds(st.EVENT) and not launches.logs[0].kinds(st.EVENT) + phase["name"] = "stuck" + elif phase["name"] == "stuck" and log.kinds(st.EVENT): + phase["name"] = "relaunching" + node = NODES[1][1].name + cluster.exit(node, max(cluster.runs[node]), 1) # incarnation 0's rank 1 fails + elif phase["name"] == "relaunching" and log.kinds(st.CLEARED_EVENT) and 1 in clients and 1 not in catching: + phase["name"] = "stuck again" + elif phase["name"] == "stuck again" and len(log.kinds(st.EVENT)) == 2: + phase["name"] = "pushing" + return phase["name"] == "pushing" and len(log.kinds(st.CLEARED_EVENT)) == 2 \ + and all(c.finalizing.is_set() for c in clients.values()) + + try: + worker.step() + follow_the_nodes() + assert sorted(clients) == [0, 1] + for fid in range(P): + clients[0].send_init(fid, _f32(_initial(fid))) + _wait(poll, "the fleet never finalized (stuck, relaunched)", timeout=300) + for client in clients.values(): + manifest, _fragments = client.wait_for_final_fragments(timeout=30) + client.acknowledge_finalization(manifest) + assert process.wait(timeout=15) == 0 + for k in list(clients): + cluster.finish(k) + _wait(lambda: all(launches.ended(m["prefix"]) is not None for m in dz.trainers(store.read()).values()), + "an island launch did not end", timeout=60) + finally: + for client in clients.values(): + client.close() + for up_ in uploaders: + up_.stop(5.0) + if process.poll() is None: + process.terminate() + process.wait(timeout=10) + assert not launches.errors, launches.errors + + # -- the watch read the run store's copy, uploaded chunk by chunk + assert all(isinstance(w.source, st.StoreTape) and w.source.requests > 0 for w in watches.values()) + current = [key for key in objects.list(st.SYNCER_TAPES) if "oldhost-" not in key] + assert len(current) >= 2 and len({key.rsplit("/", 2)[1] for key in current}) == 1 + + # -- island 1: reported, relaunched (cleared), reported again N cycles after its new join, cleared + first, second = launches.logs[1].kinds(st.EVENT) + for event in (first, second): + assert event[2]["action"] == st.WAIT and event[2]["missed_cycles"] == CYCLES and event[2]["fragments"] == P + assert first[2]["last_merged_step"] is not None # its own stretch, not the history's 40 merges + assert first[2]["newest_step"] - first[2]["last_merged_step"] >= CYCLES * P + relaunched, back = launches.logs[1].kinds(st.CLEARED_EVENT) + assert relaunched[2]["reason"] == "recovering" and back[2]["reason"] == "a push of it is merged again" + steps = _outer_steps(tape.read_text()) + joins = [r for r in _records(tape) if r.get("kind") == "pool_join" and int(r["island_id"]) == 1 + and r.get("catch_up") and r["base_version"] <= second[2]["newest_step"]] + rejoin = max(r["base_version"] for r in joins) # the relaunched incarnation's join + assert rejoin >= first[2]["newest_step"] # after the first report (the relaunch may beat the next merge) + assert second[2]["newest_step"] - rejoin >= CYCLES * P # counted from that join, not before + # its new launch caught up without a push for longer than its recover timeout: not counted + # until that grace ran out (the first launch had pushed: no grace in its report) + assert "catch-up grace" in str(second[2]["reason"]) and "catch-up grace" not in str(first[2]["reason"]) + assert states.read(1)["straggler"] is None + ctl = launches.controllers[1] + assert ctl.learners["r-i1-trainer"]["relaunches"] == 1 and launches.started("r-i1") == 1 + + # -- island 0 untouched; the merges continuous, no push merged twice; nobody else reported + assert launches.started("r-i0") == 1 + assert [sum(1 for c in cluster.calls if c[:2] == ("start", n.name)) for n in NODES[0]] == [1, 1] + assert not launches.logs[0].kinds(st.EVENT) and not launches.logs[0].kinds(st.UNAVAILABLE_EVENT) + assert [r["step"] for r in steps] == list(range(1, total_steps * P + 1)) + merged = [(int(e[0]), pushed) for r in steps for e, pushed in zip(r["raw_weights"], r["pushed_for"])] + assert len(merged) == len(set(merged)), Counter(merged).most_common(3) + + # -- the ledger: island 1's two incarnations, each created once + rows = [r for r in ResourceLedger(tmp_path / "ledger.jsonl").records() if r["kind"] == SSH_TRAINER] + created = Counter(r["id"] for r in rows if r["op"] == "create") + assert sorted(created) == ["r-i0/r-i0-trainer-i0", "r-i1/r-i1-trainer-i0", "r-i1/r-i1-trainer-i1"] + assert set(created.values()) == {1} + assert all(n == 1 for n in Counter(r["id"] for r in rows if r["op"] == "release").values()) + + +def worker_members(store, case): + members = list(dz.trainers(store.read()).values()) + if case == "remove": + members.append({"prefix": "r-i1"}) + return members + + +def _records(tape): + return [json.loads(line) for line in tape.read_text().splitlines() if line.strip()] diff --git a/yeto/dashboard/fleet_islands.py b/yeto/dashboard/fleet_islands.py index 81568fe25..278d4ba54 100644 --- a/yeto/dashboard/fleet_islands.py +++ b/yeto/dashboard/fleet_islands.py @@ -323,10 +323,22 @@ def _trainer_records(objects: Any, learners: Any = None) -> dict[int, dict]: "started_at": _f(launch.get("started_at")), "closed_at": _f(launch.get("closed_at")), "down_at": _f(launch.get("down_at")), "name": _str(launch.get("name")), "moving_to": _str(launch.get("moving_to")), - "last_exit": {"code": _int(ended.get("exit_code")), "detail": _str(ended.get("detail"))} if ended else None} + "last_exit": {"code": _int(ended.get("exit_code")), "detail": _str(ended.get("detail"))} if ended else None, + "straggler": _straggler(life.get("straggler"))} return out +def _straggler(mark: Any) -> dict | None: + """The controller's straggler mark in an island's record (``yeto.launch.island_straggler``, + written by ``FleetController._island_straggler``; None once cleared).""" + if not isinstance(mark, dict): + return None + return {**{k: _int(mark.get(k)) for k in ("missed_cycles", "merges", "fragments", "cycles", "newest_step", + "last_merged_step")}, + "action": _str(mark.get("action")), "reason": _str(mark.get("reason")), + "absent": mark.get("absent") is True, "at": _f(mark.get("at"))} + + def _phase(life: str | None) -> str: """A launch's lifecycle state in words (``yeto.rl.island_launches``).""" return {"ordering": "ordering machines (failing over across zones while none is free)", diff --git a/yeto/dashboard/reducer.py b/yeto/dashboard/reducer.py index 17f2b7d02..ed0d6762a 100644 --- a/yeto/dashboard/reducer.py +++ b/yeto/dashboard/reducer.py @@ -41,8 +41,13 @@ from . import topology as topology_mod from .sources import COST_EVENTS_FILE, up_state_stops +# a trainer island the syncer has merged no push of for N merge cycles, and its end (or why +# that cannot be watched): fleet.jsonl events that are not lifecycle states +STRAGGLER_EVENTS = frozenset({"island_straggler", "island_straggler_cleared", "island_straggler_unavailable", + "island_straggler_available"}) +STRAGGLER_TS = "straggler" # fleet_shape_ts key: the time of the island's newest straggler mark event FLEET_EVENTS = frozenset({"island_launch", "island_ready", "island_lost", "island_stop", "island_done", - "cost_tick"}) + "cost_tick"}) | STRAGGLER_EVENTS POLICY_SWEEP_LEDGER_EVENT = "policy_sweep_ledger" # the syncer's own records (``kind``, no ``step``): its config, round opens / timeouts and # the island connections it saw; a ``learner_id`` there is not a sign of life of that island @@ -677,6 +682,7 @@ def _trainer_island_now(self, isl: dict) -> dict | None: "gpu": rec.get("gpu") or row.get("gpu"), "usd_per_h": rec.get("usd_per_h") or row.get("usd_per_h"), "incarnation": rec.get("incarnation"), "relaunches": rec.get("relaunches"), "moves": row.get("moves") or [], "name": row.get("name"), + "straggler": rec.get("straggler"), # the controller's straggler mark, None once cleared "prefix": rec.get("prefix") or row.get("prefix")} def _membership_left(self, isl: dict, now: float | None = None) -> dict | None: @@ -1478,6 +1484,17 @@ def _feed_fleet(self, r: dict, iid: str | None, ts: float | None) -> None: isl[key] = r[field] if eff is not None: shape_ts[key] = eff + if event in STRAGGLER_EVENTS: # a mark on the card, not a lifecycle state: never in the replay + # the newest mark event by its source's time decides (eff: one source in write order, + # its clock stepped back included); an older one arriving later never undoes it + if event in ("island_straggler", "island_straggler_cleared") and ( + eff is None or eff >= shape_ts.get(STRAGGLER_TS, eff)): + if eff is not None: + shape_ts[STRAGGLER_TS] = eff + isl["straggler"] = ({**{k: r.get(k) for k in ("action", "missed_cycles", "newest_step", + "last_merged_step")}, "at": ts} + if event == "island_straggler" else None) + return if eff is not None: bisect.insort(life, (eff, self.event_seq, event, ts)) if older: # folded in time order again: the newest record still decides the state @@ -1750,6 +1767,7 @@ def _island_card(self, isl: dict, now: float) -> dict: # a sampler waiting at its backlog cap writes nothing until the trainers read "waiting_backlog": waiting, "waiting_reason": waiting_why or ("backlog full" if waiting else None), "role": role, "left": left, "stale_after_s": _r(warn_s), "island_now": inow, + "straggler": isl.get("straggler"), # a sampler whose pool removed or retired it but that still runs (draining, or its # machine not released): shown running, alerted past alerts.POOL_REMOVED_GRACE_S "pool_removed": ({**pool_removed, "since_s": _r(now - pool_removed["ts"]) diff --git a/yeto/dashboard/static/app.js b/yeto/dashboard/static/app.js index 30337b9ed..82a7aae1a 100644 --- a/yeto/dashboard/static/app.js +++ b/yeto/dashboard/static/app.js @@ -445,14 +445,18 @@ function cost(){ } var EV_KEEP={rl_engine_selected:1,rl_driver_start:1,rl_driver_phase:1,rl_publication:1,rl_round_trained:1,rl_reconfiguration:1,rl_learner_finalized:1, island_ready:1,island_lost:1,island_stop:1,island_done:1,island_leave:1,operator_stop:1,dashboard_source_lost:1,rl_elastic_recommendation:1, - rl_policy_released:1,rl_sampler_start:1,rl_sampler_join:1,rl_sampler_policy_loaded:1,rl_sampler_backlog_full:1,rl_sampler_admitted:1,rl_sampler_stopped:1}; + rl_policy_released:1,rl_sampler_start:1,rl_sampler_join:1,rl_sampler_policy_loaded:1,rl_sampler_backlog_full:1,rl_sampler_admitted:1,rl_sampler_stopped:1, + island_straggler:1,island_straggler_cleared:1,island_straggler_unavailable:1,island_straggler_available:1}; var POOL_BAD=/evicted|node_lost|crash_loop|failed|breaker|timeout|overdue|orphan|refused|manual_release/; function keepEv(t){return EV_KEEP[t]||/^nc_elastic_/.test(t)} var EVENTS=[],EV_CURSOR=0; function evLevel(t,rec){if(t==="operator_stop")return ["mu","stop"]; + if(t==="island_straggler")return ["wn","lag"];if(t==="island_straggler_cleared")return ["ok","back"];if(t==="island_straggler_unavailable"||t==="island_straggler_available")return ["mu","info"]; if(/^nc_elastic_/.test(t))return POOL_BAD.test(t)?["bd","pool"]:["wn","pool"];if(t==="island_leave")return ["wn","left"];if(t==="island_lost"||(t==="rl_reconfiguration"&&rec.result==="RECOVERY_REQUIRED"))return ["bd","failure"]; if(t==="rl_publication"||t==="rl_round_trained")return ["ok","done"];if(t==="rl_reconfiguration"||t==="dashboard_source_lost")return ["wn","change"];return ["mu","info"]} -function evText(e){var r=e.record||{},keys=["phase","rollout_id","policy_version","result","cause","recommendation","marker","reason_name","backlog_groups","buffer_selected","ticket","shard","why","detail"]; +// a straggler report: its count; its end and the watch's notices: their reason only +var EV_STRAGGLER_KEYS={island_straggler:["action","missed_cycles","newest_step","last_merged_step"]}; +function evText(e){var r=e.record||{},keys=/^island_straggler/.test(e.type)?EV_STRAGGLER_KEYS[e.type]||["reason"]:["phase","rollout_id","policy_version","result","cause","recommendation","marker","reason_name","backlog_groups","buffer_selected","ticket","shard","why","detail"]; return keys.filter(function(k){return r[k]!=null}).map(function(k){return k+"="+String(r[k]).slice(0,80)}).join(" ")} /* newest first by event time; the tapes are read one after another, so arrival (seq) order is not time order. One total-order key per event: its time (an event without one takes the time of the last timed event that diff --git a/yeto/dashboard/static/sft.js b/yeto/dashboard/static/sft.js index e3595d7d3..115f2b05c 100644 --- a/yeto/dashboard/static/sft.js +++ b/yeto/dashboard/static/sft.js @@ -574,7 +574,10 @@ function rlm(V){ var head='Island'+(dl?'Local step / outer sweep':"Round / policy")+'Rewardtrain-rollout KLlogprob |diff|grad_normStep / round timeTokens/s'+(noHbm?"":'HBM peak')+''+(dl?"Last PUSH / BCAST applied":"Last release / load")+'Shard · incarnation'; var flNa=rlMulti(V); var rowOf=function(c){var ex=X[c.id]||{},s=S[c.id],rr=RR(c),r=rr[rr.length-1]||{},liv=rlLive(c.status),h=hbm(c),lim=ex.hbm_total_gib,mx=Math.max(64,fin(lim)?lim*1.15:0),pc=fin(h)?Math.min(100,100*h/mx):0; - var row='
'+rlDot(c.status)+''+esc(c.label)+'
'+esc([c.name,c.gpu?c.gpu+" × "+c.cards:null,c.backend_label].filter(Boolean).join(" · ")||"n/a")+' · '+esc(c.status+(c.waiting_reason?": "+c.waiting_reason:"")+(c.left?" ("+(c.left.reason||"")+")":"")+(c.starting&&c.startup_stage?": "+c.startup_stage.label+(fin(c.startup_stage.age_s)?" "+dur(c.startup_stage.age_s):"")+(fin(c.startup_s)?" · start "+dur(c.startup_s):""):"")+((c.launches||[]).length>1?" · launch "+(c.launches.length)+" ("+(c.launches.length-1)+" superseded)":""))+'
'; + // a trainer island the syncer has merged no push of for N merge cycles (its record's mark, else its fleet + // event): "straggler" in warn colour in place of its live status + var sg=liv&&!!(c.island_now&&"straggler" in c.island_now?c.island_now.straggler:c.straggler); + var row='
'+(sg?'':rlDot(c.status))+''+esc(c.label)+'
'+esc([c.name,c.gpu?c.gpu+" × "+c.cards:null,c.backend_label].filter(Boolean).join(" · ")||"n/a")+' · '+(sg?'straggler':esc(c.status))+esc((c.waiting_reason?": "+c.waiting_reason:"")+(c.left?" ("+(c.left.reason||"")+")":"")+(c.starting&&c.startup_stage?": "+c.startup_stage.label+(fin(c.startup_stage.age_s)?" "+dur(c.startup_stage.age_s):"")+(fin(c.startup_s)?" · start "+dur(c.startup_s):""):"")+((c.launches||[]).length>1?" · launch "+(c.launches.length)+" ("+(c.launches.length-1)+" superseded)":""))+'
'; var hb='
'+(fin(h)?h.toFixed(1)+" GiB"+(fin(lim)?" of "+lim+" GiB":""):"not sampled")+'
'+(fin(lim)?'
':"")+'
'+(fin(h)?"":'
'+(/unavailable/.test(ex.gpu_mem_note||"")?"telemetry library missing":"enable --rl-resource-sample-interval")+'
')+''; if(noHbm)hb=""; if(c.role==="sampler"&&s){var sr=s.rounds||[],l=s.last_round||sr[sr.length-1]||{},ld=(A.releases||[]).map(function(x){return (x.loads||{})[c.id]?[x.policy_version,x.loads[c.id]]:null}).filter(Boolean).pop(); diff --git a/yeto/dashboard/static/topology_diloco.js b/yeto/dashboard/static/topology_diloco.js index cb798a875..9a48f5c34 100644 --- a/yeto/dashboard/static/topology_diloco.js +++ b/yeto/dashboard/static/topology_diloco.js @@ -68,6 +68,8 @@ function islandNow(tr){var n=tr.island_now;if(!n)return null; return {stopped:["stopped: "+(n.reason||""),"mute"],done:["finished","mute"],down:["down (run down)","mute"],removed:["removed from the fleet","mute"], abandoned:["abandoned: "+(n.reason||"given up"),"bad"],failed:["failed: "+(n.reason||"")+(n.detail?" · "+n.detail:""),"bad"], moving:[(n.reason||"moving").replace(/^moving to /,"moving → ")+(n.detail&&/^new launch ordering/.test(n.detail)?" · ordering":""),"warn"],starting:[(n.reason||"starting")+(fin(n.incarnation)?" · incarnation "+n.incarnation:""),"warn"]}[n.state]||null} +// the controller's straggler mark: its record's when the island has one, else its last fleet.jsonl event +function straggler(tr){var n=tr.island_now;return (n&&"straggler" in n?n.straggler:tr.straggler)||null} function trainerState(tr,tn,isl){ var age=fin(tr.phase_since)?tn-tr.phase_since:null,a=age!=null?" · "+dur(age):"",ph=tr.phase_raw,co=isl&&isl.colocated; var inow=islandNow(tr);if(inow)return inow; @@ -355,6 +357,7 @@ function paint(){ tc.step.textContent=(fin(tr.step)?"step "+tr.step:fleet()?"not trained yet":"step —")+(sft()&&fin(tr.steps_total)?" / "+tr.steps_total:"");tc.outer.textContent=fin(tr.outer)?(L.W<640?"sweep ":"outer sweep ")+tr.outer:""; // complete sweeps it applied (hover: the card's tip) fitText(tc.ph,st[0],tc.phw);tc.ph.style.fill=st[1]==="good"?C.ink:c;tc.dot.setAttribute("fill",c); tc.badge.textContent=tr.failure?(/hash/.test(tr.failure.metric)?"hash ✕":/lr/.test(tr.failure.metric)?"lr 0":"failed"):tr.lr_zero&&tr.live?"lr 0":dead?"lost":tr.syncer_link&&tr.syncer_link.state==="disconnected"&&!D.done&&!(tr.island_now&&/^(moving|starting)$/.test(tr.island_now.state))?"link ✕":"";tc.badge.style.fill=C.bad; + if(!tc.badge.textContent&&straggler(tr)&&!D.done){tc.badge.textContent="straggler";tc.badge.style.fill=C.warn} // no push merged for N merge cycles [tc.co?o.merged:tc.box].forEach(function(b){if(b){b.style.stroke=dead||tr.failure?C.bad:"";b.style.strokeDasharray=dead?"5 4":""}}); o.tc.g.setAttribute("opacity",dead?0.6:1); var L0=tc.l,lw=tc.lw; diff --git a/yeto/dashboard/topology_diloco.py b/yeto/dashboard/topology_diloco.py index 4009e4be3..fcd6e6744 100644 --- a/yeto/dashboard/topology_diloco.py +++ b/yeto/dashboard/topology_diloco.py @@ -757,6 +757,7 @@ def _trainer(iid: str, x: _Island, card: dict, st: dict, merges: list[dict], ver "arch": arch_of(card.get("gpu")), "status": st.get("status"), "live": bool(st.get("alive")), "reason": (card.get("left") or {}).get("reason"), "finalized": bool(card.get("finalized")), "island_now": card.get("island_now"), # its trainer island record (a fleet launched island by island) + "straggler": card.get("straggler"), # its last island_straggler event, None once cleared "last_event_ts": st.get("last_event_ts"), "step": step, "outer": _int(full.get("sync/outer_version")) if full else None, "versions": vec, "since": since, "pushed": {str(k): v for k, v in pushed.items()}, diff --git a/yeto/launch/fleet.py b/yeto/launch/fleet.py index 35f1be93f..ec0be6fab 100644 --- a/yeto/launch/fleet.py +++ b/yeto/launch/fleet.py @@ -290,6 +290,8 @@ def __init__( incarnations=None, stop_probe=None, deterministic_stop: bool = False, + straggler=None, + straggler_policy=None, ): """`learners` maps cluster name -> (task, job_id); `syncer` is (name, task, job_id) for a cluster syncer, or None with @@ -409,6 +411,13 @@ def __init__( # STOP there ends that island only. None (a single-trainer launch by default): # nothing is written or read. self.recorder = recorder + # yeto.launch.island_straggler.StragglerWatch or None: the syncer's merges, read each + # poll; a running island none of whose pushes was merged in N merge cycles is written + # as island_straggler (fleet.jsonl and its record). ``straggler_policy(name, signal)`` + # says what to do (island_straggler.WAIT, the default, or REPLACE with a ``replace`` + # callable of its own); None: wait (the syncer merges without it meanwhile). + self.straggler = straggler + self.straggler_policy = straggler_policy # name -> {"incarnation", "relaunches", "adopted"} from the island's record of an # earlier launcher of this run (yeto.launch.island_adopt): an adopted island keeps # its incarnation; a relaunched one continues the count. @@ -535,6 +544,7 @@ def _run_fleet(self) -> dict: self._poll_local_syncer() for rec in self.learners.values(): self._poll_recorded(rec) + self._poll_stragglers() self._end_followers() if all(r["state"] in (DONE, ABANDONED) for r in self.learners.values()): break @@ -1099,6 +1109,135 @@ def _check_stall(self) -> None: print(f"[launcher] ERROR: run stalled: {message}", file=sys.stderr) raise RunStalled(message, silent_s=silent, timeout_s=self.stall_timeout) + # -- island stragglers (yeto.launch.island_straggler) ------------------------------------- + def _poll_stragglers(self) -> None: + """The straggler watch's signals for the islands running now (not draining): each one + is written once (``island_straggler`` / ``island_straggler_cleared`` in fleet.jsonl, + ``straggler`` in the island's record) and its policy is asked what to do; a flagged + island that stops running (recovering, draining, ended) is cleared, naming why. The + watch's notices (nothing can be watched here, its tape went silent, it is read again) + are written once each (``island_straggler_unavailable`` / ``_available``). At its first + poll, a mark an earlier launcher left in an island's record is cleared (``controller + restarted``): this watch judges the island again; a record that does not read is read + again at the next poll. Never raises: a watch that fails is a + missing view, not the end of supervision.""" + if self.straggler is None or self.recorder is None: + return + from . import island_straggler as st + + try: + running, names = {}, {} + for rec in self.learners.values(): + ref = self.recorder.ref(rec["name"]) + if ref is None or ref.role == "sampler": + continue + names[ref.island] = rec + if rec["state"] == RUNNING and not rec.get("draining"): + running[ref.island] = (rec.get("incarnation"), rec.get("job_id")) + pending = getattr(self, "_straggler_marks_pending", None) + if pending is None: + pending = self._straggler_marks_pending = set(names) + if pending: # until each record read: one that does not read is tried at the next poll + self._clear_left_marks({k: names[k] for k in pending if k in names}, pending) + # a new launch (a relaunch, a spare node, a new island) catches up before it pushes: + # not counted until its first merged push, at most for its recover timeout (relaunch + # off: no recover timeout, the default grace) + grace = float(self.recover_timeout or 0.0) + grace = grace if grace > 0 else st.DEFAULT_GRACE_S + for signal in self.straggler.poll(running, now=self.ops.now(), grace_s=grace): + rec = names.get(signal.island) + if rec is not None: + self._island_straggler(rec, signal) + # each trainer island of this launch names it (a nameless fleet.jsonl event would be + # priced as an island of its own); kept until the launch knows its islands + if names: + for kind, why in self.straggler.notices(): + print(f"[launcher] island straggler watch: {why}", file=sys.stderr) + for rec in names.values(): + self._fleet(kind, rec["name"], reason=str(why)[:500]) + except Exception as error: # noqa: BLE001 - a watch, never the end of supervision + print(f"[launcher] island straggler watch: {type(error).__name__}: {error}"[:400], file=sys.stderr) + + def _clear_left_marks(self, names, pending: set) -> None: + """Close the stretch an earlier launcher of this run left open in a record (it was + restarted, or this one adopted the island): written once, then judged again. An island + whose record read (or that has none) leaves ``pending``; one whose read failed stays.""" + from . import island_straggler as st + + store = getattr(self.recorder, "store", None) + if store is None or not callable(getattr(store, "read_all", None)): + pending.clear() + return + said = self.__dict__.setdefault("_straggler_marks_said", set()) + for island, rec in names.items(): + try: + record = store.read_all([island], strict=True).get(int(island)) or {} + except Exception as error: # noqa: BLE001 - not read: tried again at the next poll + if island not in said: + said.add(island) + print(f"[launcher] {rec['name']}: island record: {type(error).__name__}: {error}; " + "read again each poll"[:300], file=sys.stderr) + continue + pending.discard(island) + left = record.get("straggler") + if not left: + continue + fields = {k: left.get(k) for k in ("missed_cycles", "merges", "fragments", "newest_step", + "last_merged_step") if isinstance(left, dict) and k in left} + print(f"[launcher] {rec['name']}: no longer a straggler (controller restarted)", file=sys.stderr) + self._fleet(st.CLEARED_EVENT, rec["name"], **fields, reason="controller restarted") + self._record(rec, straggler=None) + + @staticmethod + def _not_running(rec) -> str: + """Why a flagged island's stretch ends without a merged push: its controller state.""" + if rec.get("draining") or rec.get("stop_request") is not None: + return "stopped or removed (island STOP)" + if rec["state"] == RECOVERING: + return "recovering" + return f"not running ({rec['state']})" + + def _island_straggler(self, rec, signal) -> None: + from dataclasses import replace + + from . import island_straggler as st + + name = rec["name"] + if signal.cleared: + if signal.reason == "not running": + signal = replace(signal, reason=self._not_running(rec)) + print(f"[launcher] {name}: no longer a straggler ({signal.reason})", file=sys.stderr) + self._fleet(st.CLEARED_EVENT, name, **st.signal_fields(signal, None)) + self._record(rec, straggler=None) + return + action = st.WAIT + if self.straggler_policy is not None: + try: + action = self.straggler_policy(name, signal) or st.WAIT + except Exception as error: # noqa: BLE001 - the default is to wait + print(f"[launcher] {name}: straggler policy failed ({type(error).__name__}: {error}); " + "waiting", file=sys.stderr) + action = st.WAIT + if action not in st.ACTIONS: + print(f"[launcher] {name}: straggler policy answered {action!r}; waiting", file=sys.stderr) + action = st.WAIT + fields = st.signal_fields(signal, action) + print(f"[launcher] WARNING: {name}: island straggler: {signal.reason}; " + + ("waiting (the syncer merges the other islands at each quorum deadline, and catches it up " + "once it delivers again)" if action == st.WAIT else "its provider replaces it"), file=sys.stderr) + self._fleet(st.EVENT, name, **fields) + import time + + clock = getattr(getattr(self.recorder, "store", None), "clock", None) or time.time + self._record(rec, straggler=dict(fields, at=round(clock(), 3))) # wall time, as the record's updated + ref = self.recorder.ref(name) if self.recorder is not None else None + if ref is not None: # this watch's own mark: never taken for one an earlier launcher left + (getattr(self, "_straggler_marks_pending", None) or set()).discard(ref.island) + if action == st.REPLACE: + replace = getattr(self.straggler_policy, "replace", None) + if callable(replace): + replace(name, signal) + def _all_learners_finalized(self) -> bool: return self.finalized_probe is not None and all( r["state"] == DONE or self._finalized(r) for r in self.learners.values() diff --git a/yeto/launch/island_straggler.py b/yeto/launch/island_straggler.py new file mode 100644 index 000000000..89386dbf2 --- /dev/null +++ b/yeto/launch/island_straggler.py @@ -0,0 +1,639 @@ +"""Island stragglers of an island pool: a running island none of whose pushes was merged in +N merge cycles (``island_straggler``). + +The syncer already keeps such an island from holding the others: a pool round whose quorum +deadline passes merges the pushes that arrived, the silent island is recorded absent and +excused from the next rounds, and once it delivers again it is caught up and merged again. +What nobody said so far is that an island has stopped contributing: it heartbeats, its +launch is up, and the fleet controller sees nothing wrong. This module watches the syncer's +merges and tells the controller, which writes the event and decides what to do (wait, the +default, or a replacement the island's provider offers). + +* **What is counted.** The syncer's tape (its ``outer_step`` records; ``pool_join`` for the + start of an island). A merge cycle is one outer step of every fragment: with P fragments + (the distinct ``fragment`` ids merged so far, 1 for a non-fragment pool) an island is a + straggler once ``N x P`` merges in a row went by without a push of it in their weights. + A push the syncer refused, or one still in flight, is not merged and does not count. +* **Only this launch's history.** Each source starts at the tape's end when the watch starts + (the local file at its offset; the run store's copy at the tail of every syncer incarnation + there): a relaunched or moved island's new launch never counts the merges its earlier + launches missed, whatever the hosts' clocks say. Only an incarnation the store lists later + is read from its start, without its records stamped more than :data:`CLOCK_SKEW_S` before + the watch's start (a listing that missed it at the first read). +* **When counting starts.** At the island's first ``pool_join`` read by this watch, or at the + first merge that lists it ``absent`` (the syncer expects it: an island a restarted launcher + adopted joined before this watch), or at its first merged push. Only its controller resets + the count: when the island leaves running (recovering, draining, stopped) it starts again + once it runs again: at once for the same incarnation; for a new one (a relaunch) from its + join. A join read while the controller holds the island away from running (recovering) + counts; a relaunch the controller holds running again by its next poll, never seen away, + is counted from the first join read after that poll. A ``pool_join`` + of a reconnect (each connection is a new generation) or of a syncer that took over (a new + term) keeps the count and the mark. A merged push of the island resets the count. +* **A new launch catches up first.** A launch its controller relaunched (a spare node, a + move) or a new island whose ``pool_join`` this watch read is not counted until its first + merged push, for at most ``grace_s`` (the controller's recover timeout) on the controller's + clock; past that it is counted from then on. An adopted island (no join read) has no grace, + and a reconnect's join neither starts nor extends one. +* **Who is watched.** The islands the controller holds running (not draining, not + recovering): it passes their learner ids with a token of the incarnation. +* **Signals.** One :class:`Straggler` when an island crosses the threshold, and one + ``cleared`` signal when a push of it is merged again, when it was relaunched, or when it + stopped running (recovering, draining, ended): the controller writes one event per stretch + and closes each one. + +Sources (:func:`tape_source`): the syncer's tape file on this host (a head-mode syncer), or +its copy in the run store (``tapes/syncer//.jsonl``, uploaded every 30 s +by ``yeto.rl.engine.tape_upload``). A store read costs at most one listing of each known +incarnation's prefix after its last chunk read (within half its budget) and at most +:data:`STORE_GETS_PER_POLL` chunk reads, and starts no new request after +:data:`STORE_POLL_BUDGET_S`. Finding the syncer's incarnations costs one listing page per +incarnation, at the first read, every :data:`STORE_DISCOVER_POLLS` reads and while none is +known; the first read also lists each incarnation once, for its tail. A listing not done +within the budget goes on at the next read. A source that does not read is skipped +for that poll; nothing here ever stops or slows the fleet. When nothing can be watched (no tape +to read, the watch turned off), or the tape goes silent for :func:`quiet_window_s` after its +first record about this launch's islands, the controller is given one notice +(``island_straggler_unavailable``), and one more when records are read again +(``island_straggler_available``). +""" + +from __future__ import annotations + +import json +import os +import time +from collections.abc import Callable, Mapping +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any + +EVENT = "island_straggler" +CLEARED_EVENT = "island_straggler_cleared" +UNAVAILABLE_EVENT = "island_straggler_unavailable" +AVAILABLE_EVENT = "island_straggler_available" # the syncer's records are read again after a silent stretch +DEFAULT_CYCLES = 3 +SYNCER_TAPES = "tapes/syncer/" +STORE_POLL_S = 30.0 # the syncer's uploads are 30 s apart (tape_upload.DEFAULT_INTERVAL_S) +STORE_GETS_PER_POLL = 16 # chunk reads per poll; the rest waits for the next poll +STORE_DISCOVER_POLLS = 10 # a full listing of tapes/syncer/ (a restarted syncer) every this many reads +STORE_POLL_BUDGET_S = 5.0 # no new store request after this long in one poll +MAX_READ_BYTES = 8 << 20 # one poll reads at most this much of a local tape +QUIET_MIN_S = 300.0 # the shortest silence of the syncer's tape, after its first record about this launch, that is said +CLOCK_SKEW_S = 600.0 # the launcher's and the syncer host's clocks may differ by this much +# a new launch's catch-up grace when its controller has no recover timeout (relaunch off: +# --no-island-relaunch or --modal-retries 0); else the recover timeout is the grace +DEFAULT_GRACE_S = 1200.0 + +WAIT = "wait" # the syncer merges without it; it is caught up once it delivers again +REPLACE = "replace" # the island's provider replaces it (its own policy decides) +ACTIONS = (WAIT, REPLACE) + + +def straggler_cycles(args: Any) -> int: + """``--rl-island-straggler-cycles`` (N >= 0; 0 turns the watch off), default + :data:`DEFAULT_CYCLES`.""" + value = getattr(args, "rl_island_straggler_cycles", None) + if value is None: + return DEFAULT_CYCLES + if isinstance(value, bool) or int(value) != value or int(value) < 0: + raise ValueError(f"--rl-island-straggler-cycles must be a whole number >= 0 (got {value!r})") + return int(value) + + +@dataclass(frozen=True) +class Straggler: + """One signal about island ``island`` (its learner id).""" + + island: int + cleared: bool # False: it became a straggler; True: its stretch ended (``reason`` says how) + missed_cycles: int # whole merge cycles since its last merged push (or its join) + merges: int # merges since then + fragments: int # P + cycles: int # N, the threshold + newest_step: int | None # the newest merged step the syncer recorded + last_merged_step: int | None # the newest step a push of the island was merged into + absent: bool # the newest merge listed it absent (expected, not answered) + reason: str = "" + + def fields(self) -> dict[str, Any]: + out = asdict(self) + out.pop("island") + out.pop("cleared") + return out + + +@dataclass +class _Island: + joined: bool = False + misses: int = 0 + last_merged_step: int | None = None + absent: bool = False + flagged: bool = False + token: Any = None + away: bool = False # not running now (recovering, draining, ended): its count restarts + was_joined: bool = False # whether it was in the pool when it left running + joined_away: bool = False # a pool_join read while it was away (its next incarnation's, or a reconnect) + pushed: bool = False # a push of this launch was merged + join_read: bool = False # a pool_join of this launch was read (a new island; an adopted one has none) + grace_until: float | None = None # a new launch catching up: not counted until then (controller clock) + graced: bool = False # its grace ran out before its first merged push + + +def _time(record: Mapping[str, Any]) -> float | None: + value = record.get("time_unix") + if isinstance(value, bool): + return None + try: + return float(value) + except (TypeError, ValueError): + return None + + +@dataclass +class StragglerTracker: + """Folds syncer tape records (:meth:`feed`) and answers :meth:`check` (module doc). + Which records are this launch's is its source's business (each one starts at the tape's + end); no clock is read here.""" + + cycles: int = DEFAULT_CYCLES + islands: dict[int, _Island] = field(default_factory=dict) + fragments: set[int] = field(default_factory=set) + newest_step: int | None = None + + def _island(self, k: int) -> _Island: + return self.islands.setdefault(int(k), _Island()) + + @property + def per_cycle(self) -> int: + return max(1, len(self.fragments)) + + def feed(self, record: Mapping[str, Any]) -> None: + kind = record.get("kind") + if kind not in ("pool_join", "outer_step"): + return + if kind == "pool_join": + island = _int(record.get("island_id")) + if island is None: + return + # in the pool; a reconnect (a new connection generation) or a new syncer term keeps + # its count and its mark: only its controller's relaunch or stop restarts them + state = self._island(island) + # a join of an island already in the pool (adopted, or listed absent) is a reconnect + state.join_read = state.join_read or not state.joined + state.joined = True + state.joined_away = state.joined_away or state.away + return + step, fragment = _int(record.get("step")), _int(record.get("fragment")) + if fragment is not None: + self.fragments.add(fragment) + if step is not None: + self.newest_step = step if self.newest_step is None else max(self.newest_step, step) + merged = {_int(entry[0]) for entry in _entries(record.get("weights")) + _entries(record.get("raw_weights"))} + absent = {_int(i) for i in record.get("absent") or () if _int(i) is not None} + for k in (merged | absent) - set(self.islands) - {None}: + self.islands[k] = _Island() + for k, state in self.islands.items(): + if k in merged: + state.misses, state.absent = 0, False + state.last_merged_step = step if step is not None else state.last_merged_step + state.joined = True # a merged push: it is in the pool + state.pushed, state.grace_until, state.graced = True, None, False # its catch-up is over + elif state.joined or k in absent: + # listed absent: the syncer expects it, so it is in the pool even when its join + # came before this watch (an island adopted by a restarted launcher) + state.joined = True + state.absent = k in absent + if state.grace_until is None: # a new launch still catching up is not counted + state.misses += 1 + + def check(self, running: Mapping[int, Any], *, now: float | None = None, + grace_s: float = 0.0) -> list[Straggler]: + """The signals for the islands held running (learner id -> incarnation token), and + the end of the stretch of a flagged island that is not running any more. ``now``: + the controller's clock; ``grace_s``: how long a new launch may catch up before its + first merged push without being counted (its controller's recover timeout; 0: none).""" + out: list[Straggler] = [] + threshold = self.cycles * self.per_cycle + for k, state in self.islands.items(): + if k in running or state.token is None or state.away: + continue + # it left running: its count restarts when it is running again + if state.flagged: + out.append(self._signal(k, state, cleared=True, reason="not running")) + was_joined = state.joined + self._restart(state) + state.away, state.was_joined, state.joined_away = True, was_joined, False + for k, token in running.items(): + state = self._island(int(k)) + relaunched = state.token is not None and state.token != token + if state.away: + # back: the same incarnation keeps its place in the pool; a new one (relaunched) + # is in it once it joined, which may come before its controller holds it running + state.joined = state.joined_away or (state.token == token and state.was_joined) + state.misses, state.absent = 0, False + if relaunched: # a push merged while it was away was its earlier launch's last one + state.pushed, state.graced, state.grace_until = False, False, None + else: # the same launch: a join read meanwhile was a reconnect, not a new island + state.join_read = False + elif state.token is not None and state.token != token: + # relaunched between two checks: its count starts at its next join + if state.flagged: + out.append(self._signal(int(k), state, cleared=True, reason="relaunched")) + self._restart(state) + state.token, state.away, state.joined_away = token, False, False + # a new launch catches up before its first push: a relaunch (a spare node too), or a + # new island whose join this watch read (an adopted island joined before the watch). + # One grace per launch: a reconnect's join neither starts nor extends it + if ((relaunched or state.join_read) and not state.pushed and not state.graced + and state.grace_until is None and now is not None and grace_s > 0): + state.grace_until, state.misses = now + grace_s, 0 + if state.grace_until is not None: + if now is None or now < state.grace_until: + continue # still catching up: not counted + # no push merged within its recover timeout: counted from now on + state.grace_until, state.graced, state.misses = None, True, 0 + if self.cycles <= 0 or not state.joined: + continue + if not state.flagged and state.misses >= threshold: + state.flagged = True + out.append(self._signal(int(k), state, cleared=False, + reason=f"no push merged in {state.misses // self.per_cycle} merge cycle(s) " + f"({state.misses} merges over {self.per_cycle} fragment(s))" + + (" after its catch-up grace (the recover timeout) ran out with no push " + "of its launch merged" if state.graced else ""))) + elif state.flagged and state.misses < threshold: + state.flagged = False + out.append(self._signal(int(k), state, cleared=True, reason="a push of it is merged again")) + for k, state in self.islands.items(): + if k not in running and state.flagged: # never held running here + state.flagged = False + out.append(self._signal(k, state, cleared=True, reason="not running")) + return out + + @staticmethod + def _restart(state: _Island) -> None: + state.joined, state.misses, state.absent, state.flagged = False, 0, False, False + state.pushed, state.join_read, state.grace_until, state.graced = False, False, None, False + + def _signal(self, k: int, state: _Island, *, cleared: bool, reason: str) -> Straggler: + return Straggler(island=k, cleared=cleared, missed_cycles=state.misses // self.per_cycle, + merges=state.misses, fragments=self.per_cycle, cycles=self.cycles, + newest_step=self.newest_step, last_merged_step=state.last_merged_step, + absent=state.absent, reason=reason) + + +def _int(value: Any) -> int | None: + if isinstance(value, bool): + return None + try: + return int(value) + except (TypeError, ValueError): + return None + + +def _entries(value: Any) -> list: + return [e for e in value or () if isinstance(e, (list, tuple)) and e] + + +# -- the syncer's tape --------------------------------------------------------------------- + +class FileTape: + """The syncer's tape file on this host: the complete lines added since the last read.""" + + def __init__(self, path: str | os.PathLike[str], *, offset: int = 0) -> None: + self.path = Path(os.path.expanduser(str(path))) + self.offset = int(offset) # a reused host's tape: what an earlier syncer job wrote is not read + self.label = str(self.path) + self.error: str | None = None + self.polled = True # every call reads + + def read(self) -> list[dict[str, Any]]: + try: + size = self.path.stat().st_size + except FileNotFoundError: + return [] + if size < self.offset: # rewritten from the start: read it again + self.offset = 0 + if size == self.offset: + return [] + with self.path.open("rb") as handle: + handle.seek(self.offset) + data = handle.read(MAX_READ_BYTES) + end = data.rfind(b"\n") + if end < 0: + return [] + self.offset += end + 1 + return _records(data[: end + 1]) + + +class StoreTape: + """The syncer's tape in the run store (``tapes/syncer//.jsonl``). + + No incarnation is picked as "the" syncer: a restarted syncer may resume an earlier step, + keep its term, or write only its own records (round opens, connections) at first. The + first read lists every syncer incarnation and keeps each one's tail (its last chunk): what + the syncers wrote before this watch is not read. It takes as many reads as its budget + needs (a failed listing is tried again), and nothing else is read before every tail is + kept. From then on each read lists the known incarnations after their last chunk read + (``start_after``) within half of :data:`STORE_POLL_BUDGET_S`: those that grew at their last + listing first, then the one listed longest ago. It then reads the new chunks of those that + grew, one of each (the one read longest ago first) before a second of any, at most + :data:`STORE_GETS_PER_POLL` (the rest at the next read). An incarnation found later (by a + full listing every :data:`STORE_DISCOVER_POLLS` reads, which also goes on across reads + within the budget) did not exist at the first read: it is read from its start, without + its records stamped more than :data:`CLOCK_SKEW_S` before ``since`` (a listing that missed + it at the first read). A chunk read moves the cursor past + it, so a request that fails keeps what was read before it and is tried again at the next + read (``error`` says why); no chunk is read twice or skipped.""" + + def __init__(self, objects: Any, *, interval_s: float = STORE_POLL_S, + clock: Callable[[], float] | None = None, gets_per_poll: int = STORE_GETS_PER_POLL, + discover_polls: int = STORE_DISCOVER_POLLS, budget_s: float = STORE_POLL_BUDGET_S, + since: float | None = None) -> None: + self.objects = objects + self.interval_s = float(interval_s) + self.clock = clock or time.monotonic + self.gets_per_poll, self.discover_polls, self.budget_s = int(gets_per_poll), int(discover_polls), budget_s + self.since = time.time() if since is None else float(since) # the watch's start (wall time) + self.cursors: dict[str, str] = {} # incarnation -> its last chunk read ("" before its first) + self.fresh: set[str] = set() # incarnations read from their start (found after the first read) + self.grew: dict[str, int] = {} # incarnation -> the read that last found a new chunk of it + self.listed: dict[str, int] = {} # incarnation -> the read that last listed it + self.served: dict[str, int] = {} # incarnation -> the read that last read a chunk of it + self._root: tuple[str, set[str]] | None = None # a listing of tapes/syncer/ under way + self._todo: list[str] | None = None # the first read's incarnations whose tail is not kept yet + self.label = f"{getattr(objects, 'uri', 'store')}/{SYNCER_TAPES}" + self.error: str | None = None + self.polled = False # whether the last read() asked the store (False within the interval) + self.tailed = False # the first read's tails are established + self.reads = 0 + self.requests = 0 # listings and chunk reads so far + self._next: float | None = None + + @property + def known(self) -> set[str]: + return set(self.cursors) + + def _incarnations(self, deadline: float) -> set[str] | None: + """The syncer incarnations under ``tapes/syncer/``: one listing page per incarnation + (a page that ends inside one jumps past the rest of its chunks). None while the listing + is not done by ``deadline``: the next call goes on from its last page.""" + page = getattr(self.objects, "list_page", None) + if not callable(page): + self.requests += 1 + return {str(k)[len(SYNCER_TAPES):].split("/")[0] for k in self.objects.list(SYNCER_TAPES) + if len(str(k)[len(SYNCER_TAPES):].split("/")) == 2} + cursor, found = self._root or ("", set()) + while True: + if self.clock() >= deadline: + self._root = (cursor, found) + return None + self.requests += 1 + keys, last = page(SYNCER_TAPES, start_after=cursor, limit=1000) + found |= {str(k)[len(SYNCER_TAPES):].split("/")[0] for k in keys + if len(str(k)[len(SYNCER_TAPES):].split("/")) == 2} + if last is None or not keys: + self._root = None + return found + cursor = f"{SYNCER_TAPES}{str(last)[len(SYNCER_TAPES):].split('/')[0]}/~" # past its chunks + + def _chunks(self, inc: str, after: str = "") -> list[str]: + self.requests += 1 + return sorted(str(k) for k in self.objects.list(f"{SYNCER_TAPES}{inc}/", start_after=after) + if str(k).endswith(".jsonl") and str(k) > after) + + def _tail(self, deadline: float) -> None: + """The first read: every incarnation's tail, within the poll's budget (the rest at the + next read; a failed listing is tried again). Nothing is read before every tail is kept.""" + if self._todo is None: + found = self._incarnations(deadline) + if found is None: + return + self._todo = sorted(found) + while self._todo and self.clock() < deadline: + chunks = self._chunks(self._todo[0]) + self.cursors[self._todo.pop(0)] = chunks[-1] if chunks else "" + self.tailed = not self._todo + + def _discover(self, deadline: float) -> None: + for inc in sorted((self._incarnations(deadline) or set()) - set(self.cursors)): # a known one keeps its cursor + self.cursors[inc] = "" # not there at the first read: read from its start + self.fresh.add(inc) + + def _records_of(self, inc: str, data: Any) -> list[dict[str, Any]]: + records = _records(data if isinstance(data, bytes) else str(data).encode()) + if inc not in self.fresh: + return records + floor = self.since - CLOCK_SKEW_S + return [r for r in records if (_time(r) is None or _time(r) >= floor)] + + def read(self) -> list[dict[str, Any]]: + now = self.clock() + self.polled = False + if self._next is not None and now < self._next: + return [] + self._next = now + self.interval_s + self.polled, self.error = True, None + started, out, gets = self.clock(), [], 0 + self.reads += 1 + try: + deadline = started + self.budget_s + if not self.tailed: + self._tail(deadline) + return [] + if not self.cursors or self._root is not None or self.reads % self.discover_polls == 0: + self._discover(deadline) + grown: dict[str, list[str]] = {} + listing_until = started + self.budget_s / 2 # the other half is the chunk reads' + # one that grew at its last listing first, then the one listed longest ago + active = {i for i in self.cursors if i in self.grew and self.grew[i] == self.listed.get(i)} + for inc in sorted(self.cursors, key=lambda i: (i not in active, self.listed.get(i, -1), i)): + if self.clock() >= listing_until: + break + self.listed[inc] = self.reads + keys = self._chunks(inc, self.cursors[inc]) + if keys: + self.grew[inc], grown[inc] = self.reads, keys + # one chunk of each that grew (the one read longest ago first) before a second of any + queue = sorted(grown, key=lambda i: (self.served.get(i, -1), i)) + while queue and gets < self.gets_per_poll and self.clock() < deadline: + inc = queue.pop(0) + key = grown[inc].pop(0) + gets += 1 + self.requests += 1 + data = self.objects.read(key) + self.cursors[inc], self.served[inc] = key, self.reads + if data: + out += self._records_of(inc, data) + if grown[inc]: + queue.append(inc) + except Exception as error: # noqa: BLE001 - what was read is kept; the rest at the next read + self.error = f"{type(error).__name__}: {error}"[:300] + return out + + +def _records(data: bytes) -> list[dict[str, Any]]: + out = [] + for line in data.splitlines(): + try: + record = json.loads(line) + except (ValueError, UnicodeDecodeError): + continue + if isinstance(record, dict): + out.append(record) + return out + + +class StragglerWatch: + """A tracker fed from one source: :meth:`poll` reads what the syncer added and returns + the signals for the islands held running. A read that fails is logged once per stretch + of failures and tried again at the next poll. :meth:`notices` hands the controller + ``(event, reason)`` pairs to write: once the syncer recorded something about this launch's + islands (a join, or a merge that merged or expected one), ``quiet_s`` (:func:`quiet_window_s`) + without any record read is said once (:data:`UNAVAILABLE_EVENT`), and the next record read + takes it back (:data:`AVAILABLE_EVENT`). A fleet whose trainers start slowly is never said + to be unavailable: nothing is counted before that first record.""" + + def __init__(self, source: Any, *, cycles: int = DEFAULT_CYCLES, quiet_s: float = QUIET_MIN_S, + log: Callable[[str], None] | None = None, clock: Callable[[], float] = time.monotonic) -> None: + import sys + + self.source = source + self.tracker = StragglerTracker(cycles=int(cycles)) + self.log = log or (lambda m: print(m, file=sys.stderr, flush=True)) + self.quiet_s, self.clock = float(quiet_s), clock + self._failing = False + self._seen = False # a record about one of this launch's islands was read + self._last: float | None = None # when a record was last read, once seen + self._said = False # the silence was said (UNAVAILABLE_EVENT) and not taken back yet + self._notices: list[tuple[str, str]] = [] + + @staticmethod + def _about(record: Mapping[str, Any], islands: Any) -> bool: + if record.get("kind") == "pool_join": + return _int(record.get("island_id")) in islands + if record.get("kind") == "outer_step": + named = {_int(e[0]) for e in _entries(record.get("weights")) + _entries(record.get("raw_weights"))} + named |= {_int(i) for i in record.get("absent") or ()} + return bool(named & set(islands)) + return False + + def poll(self, running: Mapping[int, Any], *, now: float | None = None, + grace_s: float = 0.0) -> list[Straggler]: + """Read the tape and judge the islands held running (:meth:`StragglerTracker.check`).""" + try: + records = self.source.read() + error = getattr(self.source, "error", None) + except Exception as raised: # noqa: BLE001 - a watch, never the end of supervision + records, error = [], f"{type(raised).__name__}: {raised}" + if error is not None: + if not self._failing: + self.log(f"[launcher] island straggler watch: the syncer tape {self.source.label} does not read " + f"({error}); tried again next poll"[:400]) + self._failing = True + else: + self._failing = False + for record in records: + self.tracker.feed(record) + islands = {int(k) for k in running} | {k for k, s in self.tracker.islands.items() if s.token is not None} + self._seen = self._seen or any(self._about(r, islands) for r in records) + now_q = self.clock() + if records and self._seen: + self._last = now_q + if self._said: + self._said = False + self._notices.append((AVAILABLE_EVENT, f"syncer records read again from {self.source.label}")) + elif (self._seen and running and getattr(self.source, "polled", True) and self._last is not None + and now_q - self._last >= self.quiet_s and not self._said): + self._said = True + why = (f"no syncer record read from {self.source.label} in {self.quiet_s:g} s; no straggler is " + "reported until the syncer's tape is read again") + self.log(f"[launcher] WARNING: island straggler watch: {why}") + self._notices.append((UNAVAILABLE_EVENT, why)) + return self.tracker.check(running, now=now, grace_s=grace_s) + + def notices(self) -> list[tuple[str, str]]: + out, self._notices = self._notices, [] + return out + + +class UnavailableWatch: + """An island pool whose stragglers cannot be watched from here: no signal ever, and one + notice saying why (the controller writes it as ``island_straggler_unavailable``).""" + + def __init__(self, reason: str) -> None: + self.reason = reason + self._notices = [(UNAVAILABLE_EVENT, reason)] + + def poll(self, running: Mapping[int, Any], **_judge: Any) -> list[Straggler]: + return [] + + def notices(self) -> list[tuple[str, str]]: + out, self._notices = self._notices, [] + return out + + +def tape_source(*, local_tape: str | os.PathLike[str] | None = None, local_offset: int = 0, + objects: Any = None, since: float | None = None) -> Any: + """The syncer tape this controller can read: the local file of a syncer on this host, + else the run store's copy; None when neither is there.""" + if local_tape: + return FileTape(local_tape, offset=local_offset) + if objects is not None: + return StoreTape(objects, since=since) + return None + + +def quiet_window_s(args: Any, *, upload_s: float = 0.0) -> float: + """How long the syncer's tape may be silent before that is said: two of its longest rounds + and two upload intervals of its store copy (``upload_s``; 0 for a tape on this host), at + least :data:`QUIET_MIN_S`. A round with fewer pushes than the soft deadline needs runs on + to its quorum timeout (``--rl-elastic-quorum-timeout-s``, else the syncer's default), so the + longest round is the larger of the two.""" + from .syncer import SYNCER_DEFAULT_QUORUM_TIMEOUT_S, _rl_quorum_timeout_s + + soft = getattr(args, "rl_sync_soft_deadline_s", None) + round_s = max(float(soft or 0.0), float(_rl_quorum_timeout_s(args) or SYNCER_DEFAULT_QUORUM_TIMEOUT_S)) + return max(QUIET_MIN_S, 2.0 * round_s + 2.0 * max(0.0, float(upload_s or 0.0))) + + +def watch_for(args: Any, *, local_tape: str | os.PathLike[str] | None = None, local_offset: int = 0, + objects: Any = None, log: Callable[[str], None] | None = None, + no_source: str | None = None) -> StragglerWatch | UnavailableWatch | None: + """The launcher's watch of an island pool (``--rl-island-straggler-cycles``, default 3; + 0 turns it off): None without an island pool. With the watch off, or with no syncer + tape to read from here (``no_source``: why), an :class:`UnavailableWatch` that says so + once. The watch counts only what the syncer records from now on.""" + import sys + + from .syncer import island_pool + + if getattr(args, "training_mode", "sft") != "rl" or not island_pool(args): + return None + say = log or (lambda m: print(m, file=sys.stderr, flush=True)) + cycles = straggler_cycles(args) + if cycles == 0: + say("[launcher] island straggler watch off (--rl-island-straggler-cycles 0)") + return UnavailableWatch("turned off (--rl-island-straggler-cycles 0)") + source = tape_source(local_tape=local_tape, local_offset=local_offset, objects=objects, since=time.time()) + if source is None: + why = no_source or "no syncer tape to read here (a syncer on this host, or the run store's tapes/syncer/)" + say(f"[launcher] island straggler watch off: {why}") + return UnavailableWatch(why) + say(f"[launcher] island straggler watch: an island none of whose pushes is merged in {cycles} merge " + f"cycle(s) is reported ({EVENT}); syncer tape {source.label}") + upload_s = 0.0 + if isinstance(source, StoreTape): + from ..rl.engine.tape_upload import DEFAULT_INTERVAL_S, upload_interval_s + + upload_s = upload_interval_s() or DEFAULT_INTERVAL_S + return StragglerWatch(source, cycles=cycles, quiet_s=quiet_window_s(args, upload_s=upload_s), log=log) + + +def signal_fields(signal: Straggler, action: str | None) -> dict[str, Any]: + """The event's and the island record's fields of ``signal``.""" + out = signal.fields() + if action is not None: + out["action"] = action + return out diff --git a/yeto/launch/rl_args.py b/yeto/launch/rl_args.py index da98c37b2..cae6acab5 100644 --- a/yeto/launch/rl_args.py +++ b/yeto/launch/rl_args.py @@ -843,6 +843,9 @@ def _check_island_pool(args, *, num_islands: int) -> None: if int(getattr(args, "syncer_shards", None) or 1) > 1: raise ValueError("membership options need one syncer (no --syncer-shards > 1)") check_stale_lag(args) + from .island_straggler import straggler_cycles + + straggler_cycles(args) # --rl-island-straggler-cycles: a whole number >= 0 max_learners = getattr(args, "rl_sync_max_learners", None) if max_learners is not None: # full-parameter: the islands bind the roster 0..N-1 into their session diff --git a/yeto/launcher.py b/yeto/launcher.py index e2b13b36e..dff3b8020 100644 --- a/yeto/launcher.py +++ b/yeto/launcher.py @@ -690,6 +690,37 @@ def reader(): resolve_island_syncer_epoch(args, reader(), **({} if timeout_s is None else {"timeout_s": timeout_s})) +def _island_straggler_watch(args, island_states, local_syncer): + """``yeto.launch.island_straggler``'s watch of an island pool's merges: the syncer's tape + of a syncer on this host, else, for an island launch of a fleet launched island by island, + the copy its syncer launch uploads to an object run store (``tapes/syncer/``); None + without an island fleet's records (nothing is written then).""" + if island_states is None: + return None + from .launch.island_straggler import watch_for + from .launch.storage import is_object_store_uri + from .rl.engine.sample_roles import FLEET_ROLE_ISLAND, fleet_role + from .rl.engine.tape_upload import upload_interval_s + + store = str(getattr(args, "rl_checkpoint_store", None) or "") + if fleet_role(args) != FLEET_ROLE_ISLAND: + why = ("the fleet's syncer runs on a VM of its own and a launch of every island does not copy its tape " + "to the run store; run the syncer on this host (--controller head) or launch the fleet island by " + "island (fleet.launch per_island)") + elif upload_interval_s() is None: + why = "the syncer launch's tape upload is off (YETO_RL_TAPE_UPLOAD_S=0)" + elif not is_object_store_uri(store): + why = f"the run store {store or '(none)'} is not an object store: the syncer launch uploads no tape to it" + else: + why = None + try: + return watch_for(args, local_tape=getattr(local_syncer, "event_tape", None), + local_offset=int(getattr(local_syncer, "_event_offset", 0) or 0), + objects=getattr(island_states, "objects", None) if why is None else None, no_source=why) + except ValueError as error: + raise SystemExit(str(error)) from None + + def _island_state_store(args): """The run store's island records (None: no object API for the store, or none).""" from .launch.island_lifecycle import open_state_store @@ -1345,6 +1376,7 @@ def route_container(learner_id: int): "new_machine_retries": _recorded_new_machine_retries(recorder, name)} for name, a in adoption.items()}, deterministic_stop=deterministic_stop(args)[0], + straggler=_island_straggler_watch(args, island_states, local_syncer if head_mode else None), # why an island stopped, from its own tape records (a breaker, a strict check, a # refusal: never relaunched), not from its rank's exit status stop_probe=( diff --git a/yeto/rl/engine/run_flags.py b/yeto/rl/engine/run_flags.py index 8e6efe844..737db37a5 100644 --- a/yeto/rl/engine/run_flags.py +++ b/yeto/rl/engine/run_flags.py @@ -1038,6 +1038,11 @@ def rl_forward_pairs(*dests: str | tuple[str, str]) -> tuple[tuple[str, str], .. help="with --rl-fleet-role syncer on a cluster: how long the syncer cluster may stay " "unreadable or not UP in a row before the syncer launch fails (and the fleet ends). " "It includes the time the sky API itself does not answer (default 300)"), + cli_flag("--rl-island-straggler-cycles", type=int, default=None, metavar="N", + help="island pool: the fleet controller reports a running island none of whose pushes " + "the syncer merged in N merge cycles (one outer step of every fragment) as " + "island_straggler, and again once it is merged again; the syncer keeps merging the " + "other islands at each quorum deadline. 0 turns the report off (default 3)"), cli_flag("--rl-sync-max-learners", type=int, default=None, metavar="N", help="membership: the syncer admits island ids 0..N-1, so islands may join " "after the launch (default: the launched islands; with the full-parameter "