From e6fe124cfec04d181dc7a2395ab93f956c0556b3 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 00:17:43 +0800 Subject: [PATCH 1/4] fleet.jsonl: learner id as island_id, chunked copy into the run store An island launch of a fleet launched island by island runs one island, island 0 of its launch, so every fleet.jsonl record of such a fleet had island_id 0 and did not match the syncer tape's learner ids. The launch now passes its fleet learner id (--rl-fleet-learner-id) to the fleet log; every other launch keeps the -l index of the island name. fleet.jsonl lived only on the host running the launch. A launch that keeps its island records in the run store now also copies the file there in chunks (fleet/log//-p-/.jsonl, one folder per launcher process), reusing the tape uploader. Upload failures are rate-limited WARN lines and never reach the launcher; the final upload at the end is bounded to 15 s. Launches without island records (one trainer island) upload nothing. dashboard serve/export --store read every folder next to the island tapes (each record folded once, also against a local fleet.jsonl), and python -m yeto.dashboard.fleet_store merge writes one time-ordered, de-duplicated fleet.jsonl from the store and local copies. Co-Authored-By: Claude Opus 5.5 --- docs/DASHBOARD.md | 28 +++ tests/test_fleet_log_store.py | 329 +++++++++++++++++++++++++++ tests/test_fleet_log_store_launch.py | 49 ++++ yeto/dashboard/cli.py | 7 +- yeto/dashboard/fleet.py | 41 +++- yeto/dashboard/fleet_store.py | 250 ++++++++++++++++++++ yeto/launch/manifest.py | 28 ++- yeto/launcher.py | 8 +- yeto/rl/engine/tape_upload.py | 12 +- 9 files changed, 736 insertions(+), 16 deletions(-) create mode 100644 tests/test_fleet_log_store.py create mode 100644 tests/test_fleet_log_store_launch.py create mode 100644 yeto/dashboard/fleet_store.py diff --git a/docs/DASHBOARD.md b/docs/DASHBOARD.md index 63c2d1e67..380d9a74c 100644 --- a/docs/DASHBOARD.md +++ b/docs/DASHBOARD.md @@ -205,6 +205,34 @@ The head-side `fleet.jsonl` is written by `FleetController` and the budget can be passed to the launcher with the environment variables `YETO_DASHBOARD_PRICES` / `YETO_DASHBOARD_BUDGET_USD`. +Each record's `island_id` is the island's learner id, the id the syncer tape uses. +In a fleet launched island by island (`fleet.launch: per_island`) every island +launch runs one island, island 0 of its launch (`-l0-`); its records +carry the fleet learner id (`--rl-fleet-learner-id`), so the islands of the fleet +stay apart on the page. Every other launch keeps the `-l` index of the island +name, as before. + +A launch that keeps its island records in the run store (an island fleet, or +`--island-lifecycle on` with `--rl-checkpoint-store`) also copies `fleet.jsonl` +there, in chunks, every 30 s (`YETO_RL_TAPE_UPLOAD_S`, 0 turns it off): +`fleet/log//-p-/.jsonl`, lane `l` for the +island launch of learner `k` and `fleet` for a launch of the whole fleet. Every +launcher process writes its own folder, so the events of a control plane that +moved to another host, or of a host that was lost, stay in the store. The copy is +observation only: a failed upload is a `WARN` line in the launcher log, retried +with the next chunk, and the launcher's end waits at most 15 s for the last one. +A launch of one trainer island uploads nothing, as before. `--store` reads every +folder next to the island tapes (a lane's folders in the order they started), and +a record that is also in a local `fleet.jsonl` given with `--tapes` counts once. +For tools that read the file itself: + +``` +python -m yeto.dashboard.fleet_store merge --store s3:///runs/ \ + [--fleet-log ~/.yeto/runs//fleet.jsonl ...] --out fleet.merged.jsonl +``` + +writes one `fleet.jsonl`, in time order, each record once. + ## Alert rules and thresholds | Rule | Default threshold | Level | diff --git a/tests/test_fleet_log_store.py b/tests/test_fleet_log_store.py new file mode 100644 index 000000000..2768ec4ee --- /dev/null +++ b/tests/test_fleet_log_store.py @@ -0,0 +1,329 @@ +"""fleet.jsonl names a fleet island by its learner id and is copied into the run store. + +* ``island_id``: an island launch of a fleet launched island by island has one island, + island 0 of its launch (``-l0-``); its records carry the fleet learner id + (``--rl-fleet-learner-id``), the id the syncer tape uses. Every other launch keeps the + ``-l`` index of the name (as on main). +* the store copy (``dashboard.fleet_store``): chunks under ``fleet/log///``, + one folder per launcher process; a failing store is a WARN and never reaches the log + writer; the dashboard and ``fleet_store merge`` fold every folder, each record once. +""" + +from __future__ import annotations + +import json +import threading +from types import SimpleNamespace + +import pytest + +from yeto.dashboard import fleet as fleet_mod +from yeto.dashboard import fleet_store +from yeto.dashboard.fleet import FleetLog, close_open_islands, from_env +from yeto.dashboard.reducer import Reducer +from yeto.dashboard.sources import load_all +from yeto.dashboard.store_tapes import StoreTapes +from yeto.launch import manifest +from yeto.rl.engine.object_store import DirectoryObjectStore + +ISLAND = "run-i1-l0-ssh" # the one island of island 1's launch + + +class Clock: + def __init__(self, t=1000.0): + self.t = t + + def __call__(self): + return self.t + + +def _records(path): + return [json.loads(line) for line in path.read_text().splitlines()] + + +# -- island_id --------------------------------------------------------------------------------- + +def test_a_fleet_island_launch_names_its_island_by_learner_id(tmp_path): + log = from_env(tmp_path / "fleet.jsonl", {ISLAND: SimpleNamespace()}, learner_ids={ISLAND: 3}) + log.event("island_ready", ISLAND) + log.cost_tick() + log.event("island_node_lost", ISLAND, node="b300-1", rank=1) + ready, tick, lost = _records(tmp_path / "fleet.jsonl") + assert ready["island_id"] == 3 and lost["island_id"] == 3 + assert tick["islands"][0]["island_id"] == 3 + assert "learner_id" not in ready and "learner_id" not in lost # no new field: island_id carries it + + +def test_without_a_learner_id_the_name_index_stays(tmp_path): + log = from_env(tmp_path / "fleet.jsonl", {"run-l0-aws": SimpleNamespace(), "run-l1-aws": SimpleNamespace()}) + log.event("island_ready", "run-l1-aws") + log.event("rollout_event", "pool-a", pool_event="pool_up") # a pool: no index in its name + ready, pool = _records(tmp_path / "fleet.jsonl") + assert ready["island_id"] == 1 and pool["island_id"] is None + assert fleet_mod.island_id_of("run-l3-aws") == 3 and fleet_mod.island_id_of("pool") is None + + +def test_the_record_shape_is_main_s_for_a_single_island_launch(tmp_path): + """The customer launch (one trainer island, no fleet role): byte-identical records.""" + clock = Clock() + meta = {"cloud": "modal", "region": None, "gpu": "H100", "gpus": 8} + new = FleetLog(tmp_path / "a.jsonl", {"k31-l0-modal": meta}, prices={}, clock=clock) + new.event("island_ready", "k31-l0-modal") + new.cost_tick() + want = [{"event": "island_ready", "time_unix": 1000.0, "island": "k31-l0-modal", "island_id": 0, + "cloud": "modal", "region": None, "gpu": "H100", "gpus": 8, "price_key": None}] + assert _records(tmp_path / "a.jsonl")[:1] == want + assert list(_records(tmp_path / "a.jsonl")[1]["islands"][0]) == ["island", "island_id", "rate_usd_h", "wall_h", + "cost_usd", "running"] + + +def test_a_bool_or_negative_learner_id_is_not_a_learner_id(tmp_path): + log = from_env(tmp_path / "f.jsonl", {ISLAND: SimpleNamespace(), "x-l2-aws": SimpleNamespace()}, + learner_ids={ISLAND: True, "x-l2-aws": -1}) + assert log.island_id(ISLAND) == 0 and log.island_id("x-l2-aws") == 2 + + +def test_teardown_close_keeps_the_learner_id(tmp_path): + log = from_env(tmp_path / "fleet.jsonl", {ISLAND: SimpleNamespace()}, learner_ids={ISLAND: 2}) + log.event("island_ready", ISLAND) + assert close_open_islands(tmp_path / "fleet.jsonl", "teardown") == [ISLAND] + assert _records(tmp_path / "fleet.jsonl")[-1]["island_id"] == 2 + + +def _launch_args(tmp_path, *, role=None, learner=None): + return SimpleNamespace(cluster_prefix="run-i1", rl_fleet_role=role, rl_fleet_learner_id=learner, + rl_fleet_learners=None if learner is None else 4) + + +def test_the_launch_passes_its_fleet_learner_id(tmp_path, monkeypatch): + monkeypatch.setattr("yeto.runs.run_dir", lambda run: tmp_path / run) + log = manifest._dashboard_fleet_log(_launch_args(tmp_path, role="island", learner=1), # noqa: SLF001 + {ISLAND: SimpleNamespace()}, {ISLAND: ("job", None)}) + assert log.island_id(ISLAND) == 1 and log.uploader is None # no store: local only, as before + plain = manifest._dashboard_fleet_log(_launch_args(tmp_path), {"run-i1-l1-aws": SimpleNamespace()}, # noqa: SLF001 + {"run-i1-l1-aws": ("job", None)}) + assert plain.island_id("run-i1-l1-aws") == 1 and plain.uploader is None + + +def test_per_island_fleet_logs_fold_into_their_learner_islands(tmp_path): + """Two island launches (learner 0 and 1), each island 0 of its launch: the dashboard + shows two islands under the syncer tape's learner ids, not one island 0.""" + paths = [] + for k in (0, 1): + path = tmp_path / f"i{k}" / "fleet.jsonl" + log = from_env(path, {f"run-i{k}-l0-ssh": SimpleNamespace()}, learner_ids={f"run-i{k}-l0-ssh": k}) + log.clock = Clock(1000.0 + k) + log.event("island_ready", f"run-i{k}-l0-ssh") + paths.append(str(path)) + reducer = Reducer() + load_all(reducer, paths) + assert {iid: reducer.islands[iid]["name"] for iid in ("0", "1")} == {"0": "run-i0-l0-ssh", "1": "run-i1-l0-ssh"} + assert reducer.islands["1"]["ready_ts"] == 1001.0 + + +# -- the store copy ---------------------------------------------------------------------------- + +def _store_keys(root): + return sorted(str(p.relative_to(root)) for p in root.rglob("*.jsonl")) + + +def test_the_store_copy_has_every_line_under_its_lane(tmp_path): + store = tmp_path / "store" + objects = DirectoryObjectStore(str(store)) + log = from_env(tmp_path / "fleet.jsonl", {ISLAND: SimpleNamespace()}, learner_ids={ISLAND: 1}) + log.uploader = fleet_store.start_uploader(objects, log.path, learner_id=1, interval_s=3600.0) + log.event("island_ready", ISLAND) + log.event("island_node_lost", ISLAND, node="b300-1") + assert log.close() is True and log.uploader is None + keys = _store_keys(store) + assert len(keys) == 1 and keys[0].startswith("fleet/log/l1/") and keys[0].endswith("/00000000.jsonl") + folder = keys[0].split("/")[3] + assert fleet_store.incarnation().split("-p")[0] == folder.split("-p")[0] # -p- + from yeto.dashboard.store_tapes import launch_started + assert launch_started(folder) is not None + assert (store / keys[0]).read_bytes() == (tmp_path / "fleet.jsonl").read_bytes() + + +def test_a_whole_fleet_launch_uses_the_fleet_lane(): + assert fleet_store.lane(None) == "fleet" and fleet_store.lane(True) == "fleet" and fleet_store.lane(0) == "l0" + + +class FailingObjects: + def __init__(self): + self.writes = 0 + + def write(self, key, data): + self.writes += 1 + raise OSError("store down") + + +def test_a_failing_store_is_a_warn_and_never_reaches_the_writer(tmp_path): + objects, lines = FailingObjects(), [] + up = fleet_store.start_uploader(objects, tmp_path / "fleet.jsonl", learner_id=0, interval_s=3600.0, + log=lines.append) + log = from_env(tmp_path / "fleet.jsonl", {ISLAND: SimpleNamespace()}) + log.uploader = up + for _ in range(3): + log.event("island_ready", ISLAND) + up.flush() + assert len(_records(tmp_path / "fleet.jsonl")) == 3 # the local file is whole + assert objects.writes == 3 and len(lines) == 1 and "WARN" in lines[0] and "store down" in lines[0] + assert log.close(timeout_s=0.2) is False # bounded, never raises + + +def test_the_warn_is_rate_limited(): + lines = [] + warn = fleet_store._Warn(lines.append) # noqa: SLF001 + for _ in range(25): + warn("[tape-upload] fleet.jsonl: OSError: down") + assert len(lines) == 3 and "(1 failure(s))" in lines[0] and "(20 failure(s))" in lines[2] + + +def test_an_upload_interval_of_0_uploads_nothing(tmp_path, monkeypatch): + monkeypatch.setenv("YETO_RL_TAPE_UPLOAD_S", "0") + assert fleet_store.start_uploader(DirectoryObjectStore(str(tmp_path)), tmp_path / "f.jsonl") is None + + +def test_an_uploader_that_cannot_start_is_a_warn(tmp_path, monkeypatch): + lines = [] + + def boom(*a, **kw): + raise RuntimeError("no thread") + + monkeypatch.setattr("yeto.rl.engine.tape_upload.TapeUploader.start", boom) + assert fleet_store.start_uploader(object(), tmp_path / "f.jsonl", interval_s=1.0, log=lines.append) is None + assert lines and "WARN" in lines[0] + + +def test_the_launch_starts_the_copy_only_with_a_store(tmp_path, monkeypatch): + monkeypatch.setattr("yeto.runs.run_dir", lambda run: tmp_path / run) + store = tmp_path / "store" + log = manifest._dashboard_fleet_log(_launch_args(tmp_path, role="island", learner=2), # noqa: SLF001 + {ISLAND: SimpleNamespace()}, {ISLAND: ("job", None)}, + objects=DirectoryObjectStore(str(store))) + assert log.uploader is not None and log.uploader.island == "l2" + log.event("island_ready", ISLAND) + assert log.close() is True + assert [k.split("/")[2] for k in _store_keys(store)] == ["l2"] + + +# -- readers ----------------------------------------------------------------------------------- + +def _two_hosts(tmp_path): + """A control plane that moved: host A's launcher (island ready, node lost), then host B's + (ready again, a spare in); host B's local file also holds A's lines (a restored run + directory), its store folder only its own. Host B's folder sorts first by name.""" + store = tmp_path / "store" + objects = DirectoryObjectStore(str(store)) + a = [{"event": "island_ready", "time_unix": 100.0, "island": ISLAND, "island_id": 1}, + {"event": "island_node_lost", "time_unix": 150.0, "island": ISLAND, "island_id": 1, "node": "b300-1"}, + {"event": "island_lost", "time_unix": 160.0, "island": ISLAND, "island_id": 1}] + b = [{"event": "island_ready", "time_unix": 400.0, "island": ISLAND, "island_id": 1}, + {"event": "island_node_replaced", "time_unix": 401.0, "island": ISLAND, "island_id": 1, "spare": "b300-3"}] + text = lambda rows: "".join(json.dumps(r) + "\n" for r in rows).encode() # noqa: E731 + objects.write("fleet/log/l1/hosta-p7-20261127T010000Z/00000000.jsonl", text(a[:2])) + objects.write("fleet/log/l1/hosta-p7-20261127T010000Z/00000001.jsonl", text(a[2:])) + # host B sorts before host A by name; its folder started later + objects.write("fleet/log/l1/a-hostb-p9-20261127T020000Z/00000000.jsonl", text(b)) + local = tmp_path / "fleet.jsonl" + local.write_bytes(text(a + b)) + return objects, a, b, local + + +def test_the_dashboard_folds_every_folder_once_in_start_order(tmp_path): + objects, a, b, local = _two_hosts(tmp_path) + reducer = Reducer() + load_all(reducer, [str(local)]) + store = fleet_store.store_readers(StoreTapes(objects, label="store")) + assert store.pump(reducer) == 0 # every store record is already folded from the local file + isl = reducer.islands["1"] + assert isl["fleet_state"] == "ready" and isl["lost_ts"] == 160.0 and isl["closed_s"] == pytest.approx(60.0) + assert reducer.duplicates == len(a) + len(b) + only_store = Reducer() + assert fleet_store.store_readers(StoreTapes(objects, label="store")).pump(only_store) == len(a) + len(b) + o = only_store.islands["1"] + assert o["fleet_state"] == "ready" and o["ready_ts"] == 100.0 and o["open_ts"] == 400.0 + assert {r["event"] for r in only_store.fleet_records} == {"island_ready", "island_lost"} + assert sum(1 for e in only_store.events if e["type"] == "island_node_lost") == 1 + + +def test_the_store_readers_report_both_readers(tmp_path): + objects, *_ = _two_hosts(tmp_path) + store = fleet_store.store_readers(StoreTapes(objects, label="store")) + store.pump(Reducer()) + status = store.status() + assert status["label"] == "store" and status["sources"] == 2 and status["failing"] == 0 + assert store.objects is objects and len(store.sources) == 2 + + +class BrokenList(DirectoryObjectStore): + def list(self, prefix, **kw): + if prefix.startswith("fleet/log"): + raise OSError("list refused") + return super().list(prefix, **kw) + + +def test_a_fleet_log_read_failure_shows_in_the_store_status(tmp_path): + store = fleet_store.store_readers(StoreTapes(BrokenList(str(tmp_path)), label="store")) + assert store.pump(Reducer()) == 0 + status = store.status() + assert status["failing"] == 1 and "list refused" in status["last_error"] + + +def test_merge_writes_one_time_ordered_log_without_duplicates(tmp_path, capsys): + objects, a, b, local = _two_hosts(tmp_path) + other = tmp_path / "other.jsonl" + other.write_text(json.dumps(a[0]) + "\nnot json\n") + out = tmp_path / "merged.jsonl" + assert fleet_store.main(["merge", "--store", str(tmp_path / "store"), "--fleet-log", str(local), + "--fleet-log", str(other), "--out", str(out)]) == 0 + assert _records(out) == a + b + assert fleet_store.main(["merge", "--fleet-log", str(other)]) == 0 + assert capsys.readouterr().out == json.dumps(a[0]) + "\n" + + +def test_merge_keeps_an_untimed_record_after_its_predecessor(): + rows = [{"event": "x", "time_unix": 5.0}, {"event": "untimed"}, {"event": "y", "time_unix": 1.0}] + assert [r["event"] for r in fleet_store.merge_records([rows])] == ["y", "x", "untimed"] + + +def test_merge_fails_when_the_store_cannot_be_listed(tmp_path, monkeypatch, capsys): + monkeypatch.setattr("yeto.dashboard.store_tapes.open_objects", lambda store: BrokenList(str(tmp_path))) + assert fleet_store.main(["merge", "--store", "s3://example/run"]) == 2 + assert "list refused" in capsys.readouterr().err + + +def test_a_dashboard_without_store_has_no_store_reader(): + from yeto.dashboard import cli + + assert cli._store(SimpleNamespace(store=None)) is None # noqa: SLF001 + + +def test_the_dashboard_store_reads_the_fleet_logs(tmp_path): + from yeto.dashboard import cli + + objects, *_ = _two_hosts(tmp_path) + store = cli._store(SimpleNamespace(store=str(tmp_path / "store"), store_poll=0)) # noqa: SLF001 + reducer = Reducer() + assert store.pump(reducer) == 5 and "1" in reducer.islands + + +def test_the_writer_and_the_copy_run_concurrently(tmp_path): + """Lines written while chunks upload: the store ends up with exactly the local bytes.""" + store = tmp_path / "store" + log = from_env(tmp_path / "fleet.jsonl", {ISLAND: SimpleNamespace()}) + up = fleet_store.start_uploader(DirectoryObjectStore(str(store)), log.path, interval_s=0.001) + log.uploader = up + stop = threading.Event() + + def write(): + for i in range(200): + log.event("island_ready", ISLAND, n=i) + stop.set() + + t = threading.Thread(target=write) + t.start() + t.join() + assert log.close() is True + data = b"".join((store / k).read_bytes() for k in _store_keys(store)) + assert data == log.path.read_bytes() diff --git a/tests/test_fleet_log_store_launch.py b/tests/test_fleet_log_store_launch.py new file mode 100644 index 000000000..653699ffe --- /dev/null +++ b/tests/test_fleet_log_store_launch.py @@ -0,0 +1,49 @@ +"""launcher.run() copies its fleet.jsonl into the run store when it keeps island records +there (``dashboard.fleet_store``); see test_fleet_log_store.py for the unit cases.""" + +from __future__ import annotations + +import yeto.launcher as launcher +from test_rl_algorithm_provenance import _fake_sky, _no_modal_listing # noqa: F401 (autouse fixtures) +from test_rl_launcher_island_failure import _setup +from test_rl_ssh_resident import NAMES, FakeCluster, _cards # noqa: F401 (autouse fixture) +from test_rl_ssh_resident_launch import _args, _drive, _finish_when_started +from yeto import runs + + +def _store_keys(root): + return sorted(str(p.relative_to(root)) for p in root.rglob("*.jsonl")) + + +def test_a_launch_with_island_records_leaves_its_fleet_log_in_the_store(monkeypatch, tmp_path): + """launcher.run() of a resident ssh: island with its island records in a local run store + (``--island-lifecycle on``): at its end the store holds the run's fleet.jsonl, the + teardown's lines included, under the ``fleet`` lane.""" + cluster = FakeCluster(NAMES) + monkeypatch.setattr("yeto.launch.ssh_resident.SshOps", lambda: cluster) + store = tmp_path / "run-store" + record, clock = [], _drive(monkeypatch) + _setup(monkeypatch, tmp_path, failing=set(), clock=clock, record=record) + args = _args(tmp_path, "--island-lifecycle", "on", "--rl-checkpoint-store", str(store)) + _finish_when_started(clock, cluster) + assert launcher.run(args) == 0 + local = (runs.run_dir(args.cluster_prefix) / "fleet.jsonl").read_bytes() + keys = [k for k in _store_keys(store) if k.startswith("fleet/log/")] + assert keys and {k.split("/")[2] for k in keys} == {"fleet"} + assert b"".join((store / k).read_bytes() for k in keys) == local + assert b'"island_ready"' in local + + +def test_a_launch_without_island_records_uploads_nothing(monkeypatch, tmp_path): + """One trainer island, island lifecycle off (the default for one island): main's + behaviour, the store gets no fleet log even with a checkpoint store.""" + cluster = FakeCluster(NAMES) + monkeypatch.setattr("yeto.launch.ssh_resident.SshOps", lambda: cluster) + store = tmp_path / "run-store" + record, clock = [], _drive(monkeypatch) + _setup(monkeypatch, tmp_path, failing=set(), clock=clock, record=record) + args = _args(tmp_path, "--rl-checkpoint-store", str(store)) + _finish_when_started(clock, cluster) + assert launcher.run(args) == 0 + assert (runs.run_dir(args.cluster_prefix) / "fleet.jsonl").is_file() + assert not [k for k in _store_keys(store) if k.startswith("fleet/")] if store.exists() else True diff --git a/yeto/dashboard/cli.py b/yeto/dashboard/cli.py index 80449b6b5..d02172039 100644 --- a/yeto/dashboard/cli.py +++ b/yeto/dashboard/cli.py @@ -127,10 +127,13 @@ def _paths(args) -> list[str]: def _store(args): if not getattr(args, "store", None): return None + from .fleet_store import store_readers from .store_tapes import StoreTapes, open_objects - return StoreTapes(open_objects(args.store), label="store", - interval_s=float(getattr(args, "store_poll", None) or 0.0)) + interval = float(getattr(args, "store_poll", None) or 0.0) + # the island tapes, and the launchers' fleet.jsonl copies (fleet/log/, fleet_store) + return store_readers(StoreTapes(open_objects(args.store), label="store", interval_s=interval), + interval_s=interval) def _resolved(args, paths: list[str], store=None): diff --git a/yeto/dashboard/fleet.py b/yeto/dashboard/fleet.py index 19ef449fc..9e706974c 100644 --- a/yeto/dashboard/fleet.py +++ b/yeto/dashboard/fleet.py @@ -5,6 +5,12 @@ accumulated wall clock and estimated $ (price table x GPUs x wall clock; an unpriced island has ``null`` amounts, never 0). Writing is best-effort: a failure is printed and never reaches the controller. + +``island_id`` is the island's learner id when the launch knows it (an island launch of a +fleet launched island by island: ``--rl-fleet-learner-id``, the id the syncer tape names it +by; :func:`from_env` ``learner_ids``), else the ``-l`` index of its name (``m``: its +position in the launch, the learner id of every other launch). With a run store the file +is also copied there in chunks (:mod:`.fleet_store`), so the events survive the host. """ from __future__ import annotations @@ -27,6 +33,10 @@ def island_id_of(name: str) -> int | None: return int(m.group(1)) if m else None +def _learner_id(value: Any) -> int | None: + return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None + + def meta_from_task(task: Any) -> dict: """cloud/region/gpu/gpus (+ requested host cpus/memory_gib when known) of a sky Task or ModalIslandConfig (defensive: any shape -> partial dict).""" @@ -80,6 +90,22 @@ def __init__(self, path: str | os.PathLike, islands: dict[str, dict], *, prices: self.open_since: dict[str, float] = {} self.closed_s: dict[str, float] = {name: 0.0 for name in islands} self.last_tick: float | None = None + self.uploader: Any = None # fleet_store: the chunked copy into the run store (None: local only) + + def island_id(self, name: str) -> int | None: + """The island's learner id when its meta carries one, else the index in its name.""" + learner = _learner_id(self.meta.get(name, {}).get("learner_id")) + return learner if learner is not None else island_id_of(name) + + def close(self, timeout_s: float | None = None) -> bool: + """Stop the store copy after a bounded final upload (True: nothing left behind, or + no copy). Never raises.""" + uploader, self.uploader = self.uploader, None + if uploader is None: + return True + from .fleet_store import FINAL_UPLOAD_S, stop_uploader + + return stop_uploader(uploader, FINAL_UPLOAD_S if timeout_s is None else timeout_s) def _write(self, rec: dict) -> None: try: @@ -102,7 +128,7 @@ def event(self, kind: str, name: str, **fields: Any) -> dict: elif kind in ("island_lost", "island_stop") and name in self.open_since: self.closed_s[name] += now - self.open_since.pop(name) m = self.meta[name] - rec = {"event": kind, "time_unix": now, "island": name, "island_id": island_id_of(name), + rec = {"event": kind, "time_unix": now, "island": name, "island_id": self.island_id(name), **{k: m.get(k) for k in ("cloud", "region", "gpu", "gpus", "price_key")}, **{k: m[k] for k in ("cpus", "memory_gib") if m.get(k) is not None}, **fields} self._write(rec) @@ -118,7 +144,7 @@ def cost_tick(self) -> dict: for name in self.meta: rate = self.rate(name) wall_h = self.wall_s(name, now) / 3600.0 - rows.append({"island": name, "island_id": island_id_of(name), "rate_usd_h": rate, + rows.append({"island": name, "island_id": self.island_id(name), "rate_usd_h": rate, "wall_h": wall_h, "cost_usd": rate * wall_h if rate is not None else None, "running": name in self.open_since}) priced = [r["cost_usd"] for r in rows if r["cost_usd"] is not None] @@ -135,11 +161,16 @@ def maybe_tick(self) -> dict | None: return None -def from_env(path: str | os.PathLike, tasks: dict[str, Any]) -> FleetLog: +def from_env(path: str | os.PathLike, tasks: dict[str, Any], *, learner_ids: dict[str, int] | None = None) -> FleetLog: """Production constructor: price table/budget from YETO_DASHBOARD_PRICES / - YETO_DASHBOARD_BUDGET_USD (both optional).""" + YETO_DASHBOARD_BUDGET_USD (both optional). ``learner_ids``: island name -> learner id + when the launch's position is not the id (module doc).""" budget = os.environ.get("YETO_DASHBOARD_BUDGET_USD") - return FleetLog(path, {name: meta_from_task(t) for name, t in tasks.items()}, + meta = {name: meta_from_task(t) for name, t in tasks.items()} + for name, learner in (learner_ids or {}).items(): + if name in meta and _learner_id(learner) is not None: + meta[name]["learner_id"] = int(learner) + return FleetLog(path, meta, prices=load_prices(os.environ.get("YETO_DASHBOARD_PRICES") or None), budget_usd=float(budget) if budget else None) diff --git a/yeto/dashboard/fleet_store.py b/yeto/dashboard/fleet_store.py new file mode 100644 index 000000000..220292cd2 --- /dev/null +++ b/yeto/dashboard/fleet_store.py @@ -0,0 +1,250 @@ +"""The launcher's ``fleet.jsonl`` in the run store. + +``fleet.jsonl`` (island lifecycle, cost ticks, spare-node and node-health events) is a +file in the run directory of the host that runs the launch. When the control plane +moves to another host the file is split over two hosts, and a host that is lost takes +its part with it. A launch that keeps its island records in the run store (an island +fleet: ``island_lifecycle``) therefore also copies the file there, the way an island's +event tape goes (:class:`yeto.rl.engine.tape_upload.TapeUploader`): every ``interval_s`` +the complete lines added since the last upload become one new object + + ``fleet/log//-p-/.jsonl`` + +``lane`` is ``l`` for an island launch of a fleet launched island by island (learner +id ``k``) and ``fleet`` for a launch of the whole fleet; each launcher process adds its +own folder, so two hosts (or two launches of one host) never write the same key. The +copy starts at the beginning of the local file: a launcher restarted on the same host +uploads the earlier records again, and the readers fold each record once. + +Observation only: a failed upload is a WARN on stderr and is retried with the next +chunk; it never reaches the launcher. A launch without island records in a store (one +trainer island, or no ``--rl-checkpoint-store``) uploads nothing: as before. + +Readers merge every folder: ``yeto dashboard serve|export --store`` reads them next to +the island tapes (:func:`store_readers`; a record that is also in a local ``fleet.jsonl`` +given with ``--tapes`` is folded once), and ``python -m yeto.dashboard.fleet_store merge +--store URI [--fleet-log PATH]...`` writes one time-ordered ``fleet.jsonl`` without +duplicates for the tools that read the file. +""" + +from __future__ import annotations + +import json +import os +import socket +import sys +import time +from typing import Any, Callable, Iterable + +LOG_PREFIX = "fleet/log" # chunk keys: ///.jsonl +FLEET_LANE = "fleet" # the lane of a launch that runs the whole fleet +WARN_EVERY = 10 # a failing store: the first failure and then every 10th is printed +FINAL_UPLOAD_S = 15.0 # the bounded final upload at the launcher's end + + +def lane(learner_id: Any = None) -> str: + """``l`` for the island launch of learner ``k``, else :data:`FLEET_LANE`.""" + if isinstance(learner_id, int) and not isinstance(learner_id, bool) and learner_id >= 0: + return f"l{learner_id}" + return FLEET_LANE + + +def incarnation(*, host: str | None = None, pid: int | None = None, now: float | None = None) -> str: + """This launcher's folder: host, pid and UTC start (the start ends the name, as the + trainer tape folders do, so readers order a lane's folders by start).""" + host = host if host is not None else socket.gethostname() + pid = os.getpid() if pid is None else int(pid) + stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime(time.time() if now is None else now)) + return f"{host}-p{pid}-{stamp}" + + +class _Warn: + """The uploader's log: a WARN line for the first failure and every :data:`WARN_EVERY`-th.""" + + def __init__(self, out: Callable[[str], None]) -> None: + self.out = out + self.count = 0 + + def __call__(self, message: str) -> None: + self.count += 1 + if self.count == 1 or self.count % WARN_EVERY == 0: + self.out(f"[launcher] WARN: fleet.jsonl store copy ({self.count} failure(s)): " + f"{message.removeprefix('[tape-upload] ')}"[:300]) + + +def _stderr(message: str) -> None: + print(message, file=sys.stderr, flush=True) + + +def start_uploader(objects: Any, path: str | os.PathLike, *, learner_id: Any = None, environ: Any = None, + log: Callable[[str], None] = _stderr, interval_s: float | None = None) -> Any: + """The started copy of ``path`` into ``objects`` (module doc), or None: the upload + interval is 0 (``YETO_RL_TAPE_UPLOAD_S``), or it could not start (a WARN). Never raises.""" + try: + from yeto.rl.engine.tape_upload import TapeUploader, upload_interval_s # noqa: PLC0415 + + interval = upload_interval_s(None, environ) if interval_s is None else interval_s + if interval is None or interval <= 0: + return None + uploader = TapeUploader(objects, path, island=lane(learner_id), incarnation=incarnation(), interval_s=interval, + log=_Warn(log), prefix=LOG_PREFIX) + return uploader.start() + except Exception as exc: # noqa: BLE001 - telemetry never stops a launch + log(f"[launcher] WARN: fleet.jsonl store copy not started ({type(exc).__name__}: {exc})"[:300]) + return None + + +def stop_uploader(uploader: Any, timeout_s: float = FINAL_UPLOAD_S) -> bool: + """The final upload, bounded; True when the store has every complete line. Never raises.""" + if uploader is None: + return True + try: + return bool(uploader.stop(timeout_s)) + except Exception as exc: # noqa: BLE001 + _stderr(f"[launcher] WARN: fleet.jsonl store copy: final upload failed ({type(exc).__name__})") + return False + + +# -- readers ------------------------------------------------------------------------------------ + +def log_reader(objects: Any, *, label: str = "store-fleet", interval_s: float = 0.0) -> Any: + """A :class:`~yeto.dashboard.store_tapes.StoreTapes` over the store's fleet logs: each + launcher folder is one source, its chunks read once and in order, the folders of a lane + in the order they started.""" + from .store_tapes import StoreTapes # noqa: PLC0415 + + return StoreTapes(objects, label=label, interval_s=interval_s, prefix=LOG_PREFIX + "/") + + +class StoreReaders: + """Several store readers as one (``serve`` / ``export`` take one ``store``): the island + tapes first, then the fleet logs. ``objects`` and ``label`` are the first reader's.""" + + def __init__(self, *readers: Any) -> None: + self.readers = [r for r in readers if r is not None] + self.objects = self.readers[0].objects + self.label = getattr(self.readers[0], "label", "store") + + def pump(self, reducer: Any) -> int: + return sum(int(r.pump(reducer) or 0) for r in self.readers) + + @property + def sources(self) -> set[str]: + return set().union(*(set(getattr(r, "sources", ())) for r in self.readers)) + + @property + def errors(self) -> int: + return sum(int(getattr(r, "errors", 0) or 0) for r in self.readers) + + def status(self) -> dict: + """The first reader's status; failures, errors, requests and sources of all.""" + rows = [r.status() for r in self.readers] + out = dict(rows[0]) + for key in ("sources", "requests", "errors", "failing"): + out[key] = sum(int(row.get(key) or 0) for row in rows) + failed = [row for row in rows if row.get("last_error_at") is not None] + if failed: + last = max(failed, key=lambda row: row["last_error_at"]) + out["last_error"], out["last_error_at"] = last.get("last_error"), last["last_error_at"] + oks = [row.get("last_ok_at") for row in rows] + out["last_ok_at"] = None if any(v is None for v in oks) else min(oks) + out["polled"] = all(bool(row.get("polled")) for row in rows) + return out + + +def store_readers(tapes: Any, *, interval_s: float = 0.0) -> StoreReaders: + """The dashboard's store: the island tapes ``tapes`` and the fleet logs of its store.""" + return StoreReaders(tapes, log_reader(tapes.objects, interval_s=interval_s)) + + +def _jsonl(text: str) -> list[dict]: + out = [] + for line in text.splitlines(): + try: + rec = json.loads(line) + except ValueError: + continue + if isinstance(rec, dict): + out.append(rec) + return out + + +def _time(rec: dict) -> float | None: + v = rec.get("time_unix") + return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None + + +def merge_records(groups: Iterable[Iterable[dict]]) -> list[dict]: + """Every record of ``groups`` once (equal JSON is one record), in time order; a record + without ``time_unix`` keeps the time of the record before it in its group.""" + seen: set[str] = set() + rows: list[tuple[float, int, dict]] = [] + for group in groups: + last = float("-inf") + for rec in group: + key = json.dumps(rec, sort_keys=True, separators=(",", ":"), default=str) + t = _time(rec) + last = last if t is None else t + if key in seen: + continue + seen.add(key) + rows.append((last, len(rows), rec)) + rows.sort(key=lambda row: (row[0], row[1])) + return [rec for _, _, rec in rows] + + +def read_store(objects: Any) -> list[list[dict]]: + """The records of every fleet log folder in the store, one list per folder.""" + reader = log_reader(objects) + by_source: dict[str, list[dict]] = {} + + class _BySource: # a reducer stand-in: every record, by source + def feed(self, record: Any, *, source: str = "-", offset: int | None = None, **_: Any) -> bool: + if isinstance(record, dict): + by_source.setdefault(source, []).append(record) + return True + return False + + reader.pump(_BySource()) + if reader.failing: + raise OSError(f"fleet logs not read from the store: {reader.last_error}") + return list(by_source.values()) + + +def main(argv: Any = None) -> int: + """``merge --store URI [--fleet-log PATH]... [--out PATH]``: one ``fleet.jsonl``.""" + import argparse # noqa: PLC0415 + from pathlib import Path # noqa: PLC0415 + + parser = argparse.ArgumentParser(prog="python -m yeto.dashboard.fleet_store") + sub = parser.add_subparsers(dest="cmd", required=True) + mg = sub.add_parser("merge", help="the run's fleet.jsonl from the store (and local copies), merged") + mg.add_argument("--store", default=None, help="the run store (s3://, oss:// or a directory)") + mg.add_argument("--fleet-log", action="append", default=[], help="a local fleet.jsonl (repeatable)") + mg.add_argument("--out", default="-", help="output file (default: stdout)") + args = parser.parse_args(argv) + if not args.store and not args.fleet_log: + parser.error("merge needs --store and/or --fleet-log") + groups: list[list[dict]] = [] + if args.store: + from .store_tapes import open_objects # noqa: PLC0415 + + try: + groups += read_store(open_objects(args.store)) + except OSError as exc: + print(f"[fleet-log] {exc}", file=sys.stderr) + return 2 + for path in args.fleet_log: + groups.append(_jsonl(Path(path).expanduser().read_text(encoding="utf-8", errors="replace"))) + merged = merge_records(groups) + text = "".join(json.dumps(rec, ensure_ascii=False, default=str) + "\n" for rec in merged) + if args.out == "-": + sys.stdout.write(text) + else: + Path(args.out).expanduser().write_text(text, encoding="utf-8") + print(f"[fleet-log] {len(merged)} record(s) from {len(groups)} log(s)", file=sys.stderr) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/yeto/launch/manifest.py b/yeto/launch/manifest.py index 429e2d699..6b0ce4303 100644 --- a/yeto/launch/manifest.py +++ b/yeto/launch/manifest.py @@ -92,18 +92,38 @@ def _write_run_manifest(args) -> dict | None: return manifest -def _dashboard_fleet_log(args, tasks, results): +def _fleet_learner(args): + """``(learner id, learners)`` of a fleet island launch, else None (never raises).""" + try: + from ..rl.engine import sample_roles + + return sample_roles.fleet_learner(args) + except Exception: # noqa: BLE001 - the fleet log falls back to the launch's island index + return None + + +def _dashboard_fleet_log(args, tasks, results, objects=None): """fleet-dashboard 2.3: the run's ``fleet.jsonl`` writer, or None if it - cannot be built (never blocks a launch).""" + cannot be built (never blocks a launch). An island launch of a fleet launched + island by island names its island by its fleet learner id. ``objects``: the run + store's object API when the launch keeps its island records there; the file is + then also copied into the store in chunks (``dashboard.fleet_store``).""" + member = _fleet_learner(args) try: from .. import runs from ..dashboard.fleet import from_env - return from_env(runs.run_dir(args.cluster_prefix) / "fleet.jsonl", - {name: tasks[name] for name in results}) + learner_ids = None if member is None else {name: member[0] for name in results} + log = from_env(runs.run_dir(args.cluster_prefix) / "fleet.jsonl", + {name: tasks[name] for name in results}, learner_ids=learner_ids) except Exception as e: # noqa: BLE001 print(f"[launcher] fleet.jsonl disabled: {e}", file=sys.stderr) return None + if objects is not None: + from ..dashboard.fleet_store import start_uploader + + log.uploader = start_uploader(objects, log.path, learner_id=None if member is None else member[0]) + return log def _no_sync_events_dir(args) -> Path: diff --git a/yeto/launcher.py b/yeto/launcher.py index 7b76ee929..a663d5285 100644 --- a/yeto/launcher.py +++ b/yeto/launcher.py @@ -1314,7 +1314,8 @@ def route_container(learner_id: int): no_recover=verda["no_recover"] if verda else (), instance_guard=verda["guard"] if verda else None, on_rename=_rename_hook(clusters, on_clusters, [] if head_mode else [syncer_cluster]), - fleet_log=_dashboard_fleet_log(args, tasks, results), + fleet_log=_dashboard_fleet_log(args, tasks, results, + objects=None if island_states is None else island_states.objects), syncer_finished_probe=local_syncer.finished if head_mode else None, left_pool_probe=( (lambda name: name in event_collectors and event_collectors[name].left_pool) @@ -1690,6 +1691,11 @@ def drain_tapes(limit: float = NO_SYNC_EVENT_DRAIN_S) -> None: f"Terminate them from the cloud console, then: yeto down {prefix}", file=sys.stderr, ) + close_fleet_log = getattr(getattr(controller, "fleet_log", None), "close", None) + if callable(close_fleet_log): + # the store copy of fleet.jsonl: its last lines (the island_stop just written + # included), bounded; a store that fails is a WARN, never the exit code + close_fleet_log() if ssh_islands is not None: ssh_islands.close() # streams and locks; a kept island is reattached by the next launch if island_states is not None: diff --git a/yeto/rl/engine/tape_upload.py b/yeto/rl/engine/tape_upload.py index d77485fe8..fcbfb5c13 100644 --- a/yeto/rl/engine/tape_upload.py +++ b/yeto/rl/engine/tape_upload.py @@ -55,8 +55,10 @@ def safe_part(name: Any) -> str: return _SAFE.sub("_", str(name)).strip("._") or "_" -def chunk_key(island: str, incarnation: str, seq: int) -> str: - return f"{TAPES_PREFIX}/{safe_part(island)}/{safe_part(incarnation)}/{seq:08d}.jsonl" +def chunk_key(island: str, incarnation: str, seq: int, prefix: str = TAPES_PREFIX) -> str: + """``///.jsonl`` (``prefix``: ``tapes`` for the event + tapes, ``fleet/log`` for the launcher's ``fleet.jsonl``, ``dashboard.fleet_store``).""" + return f"{prefix}/{safe_part(island)}/{safe_part(incarnation)}/{seq:08d}.jsonl" def final_flush_s(environ: Any = None) -> float: @@ -112,8 +114,10 @@ def upload_interval_s(spec_value: Any = None, environ: Any = None) -> float | No class TapeUploader: def __init__(self, objects: Any, tape: str | os.PathLike[str], *, island: str, incarnation: str, - interval_s: float = DEFAULT_INTERVAL_S, log: Callable[[str], None] = print) -> None: + interval_s: float = DEFAULT_INTERVAL_S, log: Callable[[str], None] = print, + prefix: str = TAPES_PREFIX) -> None: self.objects = objects + self.prefix = prefix self.tape = Path(tape) self.island = str(island) self.incarnation = str(incarnation) @@ -148,7 +152,7 @@ def flush(self) -> int: return 0 # a torn last line waits for its newline data = data[: end + 1] try: - self.objects.write(chunk_key(self.island, self.incarnation, self.seq), data) + self.objects.write(chunk_key(self.island, self.incarnation, self.seq, self.prefix), data) except Exception as error: # noqa: BLE001 - observation must never stop the island self.failures += 1 self.log(f"[tape-upload] {self.tape.name}: {type(error).__name__}: {error}"[:300]) From 0fcf91510fb3723f1c308203d149fec8ea18c9e4 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 00:19:01 +0800 Subject: [PATCH 2/4] tests: the customer K3.1 runs keep no island records (no fleet log upload); default tape keys unchanged Co-Authored-By: Claude Opus 5.5 --- tests/test_fleet_log_store_launch.py | 46 ++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/tests/test_fleet_log_store_launch.py b/tests/test_fleet_log_store_launch.py index 653699ffe..3c113194d 100644 --- a/tests/test_fleet_log_store_launch.py +++ b/tests/test_fleet_log_store_launch.py @@ -3,6 +3,9 @@ from __future__ import annotations +import pytest + +import test_k31_customer_plan_golden as golden import yeto.launcher as launcher from test_rl_algorithm_provenance import _fake_sky, _no_modal_listing # noqa: F401 (autouse fixtures) from test_rl_launcher_island_failure import _setup @@ -47,3 +50,46 @@ def test_a_launch_without_island_records_uploads_nothing(monkeypatch, tmp_path): assert launcher.run(args) == 0 assert (runs.run_dir(args.cluster_prefix) / "fleet.jsonl").is_file() assert not [k for k in _store_keys(store) if k.startswith("fleet/")] if store.exists() else True + + +# -- the customer path --------------------------------------------------------------------------- + +@pytest.mark.parametrize("case", sorted(golden.CASES)) +def test_the_customer_runs_keep_no_island_records_so_no_fleet_log_upload(case, tmp_path, monkeypatch): + """Every customer K3.1 run (one buffer trainer, async GRPO, no fleet): the launch keeps + no island records in the store (``island_lifecycle_enabled`` False, as on main), so the + launcher builds its fleet log with ``objects=None`` and nothing is uploaded.""" + import yeto.cli as cli + from yeto.gpu_spec import parse_gpu_spec + + monkeypatch.setenv("HOME", str(tmp_path / "home")) + args = cli.parse_args(golden._argv(golden.CASES[case], tmp_path)) # noqa: SLF001 + assert not getattr(args, "dry_run", False) and getattr(args, "island_lifecycle", None) in (None, "auto") + assert launcher.island_lifecycle_enabled(args, parse_gpu_spec(args.gpu)) is False + + +class Recording: + def __init__(self): + self.keys = [] + + def write(self, key, data): + self.keys.append(key) + + +def test_the_tape_uploader_default_keys_are_main_s(tmp_path): + """Without ``prefix`` the uploader writes main's keys (``tapes///``), + and the trainer / syncer uploaders pass none.""" + import inspect + + from yeto.rl.engine import tape_upload + + assert tape_upload.chunk_key("trainer", "l0-h-20261127T000000Z", 3) == "tapes/trainer/l0-h-20261127T000000Z/00000003.jsonl" + assert tape_upload.chunk_key("a/b", "", 0) == "tapes/a_b/_/00000000.jsonl" + tape = tmp_path / "tape.jsonl" + tape.write_text('{"a": 1}\n{"b": 2}\n') + objects = Recording() + up = tape_upload.TapeUploader(objects, tape, island="syncer", incarnation="h-1", interval_s=30.0) + assert up.prefix == "tapes" and up.interval_s == 30.0 and up.flush() > 0 + assert objects.keys == ["tapes/syncer/h-1/00000000.jsonl"] + for fn in (tape_upload.trainer_uploader, tape_upload.syncer_uploaders): + assert "prefix" not in inspect.getsource(fn) From 636a077d0f8c535cdc198773554e80a133059eec Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 01:10:39 +0800 Subject: [PATCH 3/4] fleet.jsonl store copy: review fixes - Folder names carry a random nonce before the UTC start: two launchers of one host with the same pid in the same second write two folders (the dashboard keeps one cursor per folder). - The dashboard folds an island's fleet lifecycle records by their own time: an older host's records that arrive after the newer host's (store copy read after the local file) add their closed intervals and no longer reset the island's state; each shape field follows the newest record that names it. - yeto down copies the island_stop lines it appends into the store (same lane, WARN on failure). - The fleet log is built before the fleet controller, so its store copy is stopped even when the controller cannot be built. fleet.store.json records the store and the start offset of the copy: a run directory reused by a run with another store starts at the file's end. - An explicit upload interval must be positive; the store status of the two readers reports the oldest clean poll. Co-Authored-By: Claude Opus 5.5 --- docs/DASHBOARD.md | 27 ++-- tests/test_fleet_log_store.py | 232 +++++++++++++++++++++++---- tests/test_fleet_log_store_launch.py | 30 ++++ yeto/cli.py | 10 +- yeto/dashboard/fleet_store.py | 118 ++++++++++++-- yeto/dashboard/reducer.py | 37 ++++- yeto/launch/manifest.py | 12 +- yeto/launcher.py | 13 +- 8 files changed, 414 insertions(+), 65 deletions(-) diff --git a/docs/DASHBOARD.md b/docs/DASHBOARD.md index 380d9a74c..40b13b930 100644 --- a/docs/DASHBOARD.md +++ b/docs/DASHBOARD.md @@ -215,15 +215,24 @@ name, as before. A launch that keeps its island records in the run store (an island fleet, or `--island-lifecycle on` with `--rl-checkpoint-store`) also copies `fleet.jsonl` there, in chunks, every 30 s (`YETO_RL_TAPE_UPLOAD_S`, 0 turns it off): -`fleet/log//-p-/.jsonl`, lane `l` for the -island launch of learner `k` and `fleet` for a launch of the whole fleet. Every -launcher process writes its own folder, so the events of a control plane that -moved to another host, or of a host that was lost, stay in the store. The copy is -observation only: a failed upload is a `WARN` line in the launcher log, retried -with the next chunk, and the launcher's end waits at most 15 s for the last one. -A launch of one trainer island uploads nothing, as before. `--store` reads every -folder next to the island tapes (a lane's folders in the order they started), and -a record that is also in a local `fleet.jsonl` given with `--tapes` counts once. +`fleet/log//-p--/.jsonl`, lane `l` for +the island launch of learner `k` and `fleet` for a launch of the whole fleet. Every +launcher process writes its own folder (the random nonce keeps two launchers of one +host apart), so the events of a control plane that moved to another host, or of a +host that was lost, stay in the store. Only this run's part of the local file is +copied: `fleet.store.json` next to it records the store and the offset the copy +starts at, and a run directory reused by a run with another store starts at the +file's end. `yeto down` copies the `island_stop` lines it appends for islands a +killed launcher left open. The copy is observation only: a failed upload is a +`WARN` line, retried with the next chunk, and the launcher's end (and `yeto down`) +waits at most 15 s for the last one. A launch of one trainer island uploads +nothing, as before. `--store` reads every folder next to the island tapes, and a +record that is also in a local `fleet.jsonl` given with `--tapes` counts once. The +page folds an island's lifecycle records by their own time, whatever the order it +reads them in: a host's older records that arrive after the newer host's (its run +directory has only its own lines) add their closed ready -> lost intervals and do +not change the island's current state. A host clock that is off by more than the +gap between two hosts' records still orders those records by that clock. For tools that read the file itself: ``` diff --git a/tests/test_fleet_log_store.py b/tests/test_fleet_log_store.py index 2768ec4ee..5710a4caa 100644 --- a/tests/test_fleet_log_store.py +++ b/tests/test_fleet_log_store.py @@ -138,7 +138,7 @@ def test_the_store_copy_has_every_line_under_its_lane(tmp_path): keys = _store_keys(store) assert len(keys) == 1 and keys[0].startswith("fleet/log/l1/") and keys[0].endswith("/00000000.jsonl") folder = keys[0].split("/")[3] - assert fleet_store.incarnation().split("-p")[0] == folder.split("-p")[0] # -p- + assert fleet_store.incarnation().split("-p")[0] == folder.split("-p")[0] # -p-- from yeto.dashboard.store_tapes import launch_started assert launch_started(folder) is not None assert (store / keys[0]).read_bytes() == (tmp_path / "fleet.jsonl").read_bytes() @@ -198,8 +198,9 @@ def boom(*a, **kw): def test_the_launch_starts_the_copy_only_with_a_store(tmp_path, monkeypatch): monkeypatch.setattr("yeto.runs.run_dir", lambda run: tmp_path / run) store = tmp_path / "store" - log = manifest._dashboard_fleet_log(_launch_args(tmp_path, role="island", learner=2), # noqa: SLF001 - {ISLAND: SimpleNamespace()}, {ISLAND: ("job", None)}, + args = _launch_args(tmp_path, role="island", learner=2) + args.rl_checkpoint_store = str(store) + log = manifest._dashboard_fleet_log(args, {ISLAND: SimpleNamespace()}, {ISLAND: ("job", None)}, # noqa: SLF001 objects=DirectoryObjectStore(str(store))) assert log.uploader is not None and log.uploader.island == "l2" log.event("island_ready", ISLAND) @@ -209,42 +210,82 @@ def test_the_launch_starts_the_copy_only_with_a_store(tmp_path, monkeypatch): # -- readers ----------------------------------------------------------------------------------- -def _two_hosts(tmp_path): - """A control plane that moved: host A's launcher (island ready, node lost), then host B's - (ready again, a spare in); host B's local file also holds A's lines (a restored run - directory), its store folder only its own. Host B's folder sorts first by name.""" +def _text(rows) -> bytes: + return "".join(json.dumps(r) + "\n" for r in rows).encode() + + +A_ROWS = [{"event": "island_ready", "time_unix": 100.0, "island": ISLAND, "island_id": 1}, + {"event": "island_node_lost", "time_unix": 150.0, "island": ISLAND, "island_id": 1, "node": "b300-1"}, + {"event": "island_lost", "time_unix": 160.0, "island": ISLAND, "island_id": 1}] +B_ROWS = [{"event": "island_ready", "time_unix": 400.0, "island": ISLAND, "island_id": 1}, + {"event": "island_node_replaced", "time_unix": 401.0, "island": ISLAND, "island_id": 1, "spare": "b300-3"}] + + +def _two_hosts(tmp_path, *, a_stamp="20261127T010000Z", b_stamp="20261127T020000Z"): + """A control plane that moved: host A's launcher (island ready, node lost, island lost), + then host B's (ready again, a spare in). Host B's local file has only its own lines; the + store has both folders. Host B's folder sorts first by name.""" store = tmp_path / "store" objects = DirectoryObjectStore(str(store)) - a = [{"event": "island_ready", "time_unix": 100.0, "island": ISLAND, "island_id": 1}, - {"event": "island_node_lost", "time_unix": 150.0, "island": ISLAND, "island_id": 1, "node": "b300-1"}, - {"event": "island_lost", "time_unix": 160.0, "island": ISLAND, "island_id": 1}] - b = [{"event": "island_ready", "time_unix": 400.0, "island": ISLAND, "island_id": 1}, - {"event": "island_node_replaced", "time_unix": 401.0, "island": ISLAND, "island_id": 1, "spare": "b300-3"}] - text = lambda rows: "".join(json.dumps(r) + "\n" for r in rows).encode() # noqa: E731 - objects.write("fleet/log/l1/hosta-p7-20261127T010000Z/00000000.jsonl", text(a[:2])) - objects.write("fleet/log/l1/hosta-p7-20261127T010000Z/00000001.jsonl", text(a[2:])) - # host B sorts before host A by name; its folder started later - objects.write("fleet/log/l1/a-hostb-p9-20261127T020000Z/00000000.jsonl", text(b)) + objects.write(f"fleet/log/l1/hosta-p7-0a0a0a0a-{a_stamp}/00000000.jsonl", _text(A_ROWS[:2])) + objects.write(f"fleet/log/l1/hosta-p7-0a0a0a0a-{a_stamp}/00000001.jsonl", _text(A_ROWS[2:])) + objects.write(f"fleet/log/l1/a-hostb-p9-0b0b0b0b-{b_stamp}/00000000.jsonl", _text(B_ROWS)) local = tmp_path / "fleet.jsonl" - local.write_bytes(text(a + b)) - return objects, a, b, local + local.write_bytes(_text(B_ROWS)) + return objects, A_ROWS, B_ROWS, local + + +def _lifecycle(isl): + return {k: isl[k] for k in ("fleet_state", "ready_ts", "last_ready_ts", "stop_ts", "lost_ts", "open_ts", + "closed_s")} -def test_the_dashboard_folds_every_folder_once_in_start_order(tmp_path): +RUNNING_AGAIN = {"fleet_state": "ready", "ready_ts": 100.0, "last_ready_ts": 400.0, "stop_ts": None, + "lost_ts": 160.0, "open_ts": 400.0, "closed_s": pytest.approx(60.0)} + + +def test_the_moved_host_s_island_is_running_with_the_lost_host_s_history(tmp_path): + """Local file of host B only (its run directory), store with A and B: the island runs + (B's ready is the newest record), A's ready -> lost interval is billed, each record once.""" objects, a, b, local = _two_hosts(tmp_path) reducer = Reducer() load_all(reducer, [str(local)]) store = fleet_store.store_readers(StoreTapes(objects, label="store")) - assert store.pump(reducer) == 0 # every store record is already folded from the local file - isl = reducer.islands["1"] - assert isl["fleet_state"] == "ready" and isl["lost_ts"] == 160.0 and isl["closed_s"] == pytest.approx(60.0) - assert reducer.duplicates == len(a) + len(b) + assert store.pump(reducer) == len(a) # A's lines are new; B's are folded already + assert _lifecycle(reducer.islands["1"]) == RUNNING_AGAIN + assert reducer.duplicates == len(b) + assert sum(1 for e in reducer.events if e["type"] == "island_node_lost") == 1 only_store = Reducer() assert fleet_store.store_readers(StoreTapes(objects, label="store")).pump(only_store) == len(a) + len(b) - o = only_store.islands["1"] - assert o["fleet_state"] == "ready" and o["ready_ts"] == 100.0 and o["open_ts"] == 400.0 + assert _lifecycle(only_store.islands["1"]) == RUNNING_AGAIN assert {r["event"] for r in only_store.fleet_records} == {"island_ready", "island_lost"} - assert sum(1 for e in only_store.events if e["type"] == "island_node_lost") == 1 + + +def test_a_folder_stamp_two_hours_off_does_not_change_the_state(tmp_path): + """Host B's clock 2 h behind for its folder stamp: B's folder is read before A's; the + records' own times still decide (the newest record, B's ready, sets the state).""" + objects, a, b, local = _two_hosts(tmp_path, a_stamp="20261127T030000Z", b_stamp="20261127T010000Z") + reducer = Reducer() + assert fleet_store.store_readers(StoreTapes(objects, label="store")).pump(reducer) == len(a) + len(b) + assert _lifecycle(reducer.islands["1"]) == RUNNING_AGAIN + + +@pytest.mark.parametrize("order", ["in-order", "reversed", "lost-first"]) +def test_the_lifecycle_does_not_depend_on_the_read_order(order): + rows = [{"event": "island_ready", "time_unix": 10.0, "island": ISLAND, "island_id": 1, "gpu": "B300"}, + {"event": "island_lost", "time_unix": 20.0, "island": ISLAND, "island_id": 1}, + {"event": "island_ready", "time_unix": 30.0, "island": ISLAND, "island_id": 1, "gpu": "H100"}, + {"event": "island_stop", "time_unix": 50.0, "island": ISLAND, "island_id": 1, "reason": "teardown"}] + want = Reducer() + for r in rows: + want.feed(dict(r)) + got = Reducer() + feed = {"in-order": rows, "reversed": rows[::-1], "lost-first": [rows[1], rows[3], rows[0], rows[2]]}[order] + for r in feed: + got.feed(dict(r)) + assert _lifecycle(got.islands["1"]) == _lifecycle(want.islands["1"]) + assert _lifecycle(want.islands["1"])["closed_s"] == pytest.approx(30.0) + assert got.islands["1"]["gpu"] == "H100" # the newest record's shape def test_the_store_readers_report_both_readers(tmp_path): @@ -327,3 +368,140 @@ def write(): assert log.close() is True data = b"".join((store / k).read_bytes() for k in _store_keys(store)) assert data == log.path.read_bytes() + + +# -- folders of one host --------------------------------------------------------------------------- + +def test_two_launchers_of_one_host_pid_and_second_get_two_folders(): + from yeto.dashboard.store_tapes import launch_started + + one = fleet_store.incarnation(host="h", pid=1, now=1795700000.0) + two = fleet_store.incarnation(host="h", pid=1, now=1795700000.0) + assert one != two and one.startswith("h-p1-") and two.startswith("h-p1-") + assert launch_started(one) == launch_started(two) == 1795700000.0 # the start still ends the name + assert fleet_store.incarnation(host="h", pid=1, now=1795700000.0, nonce="ab") == "h-p1-ab-20261126T133320Z" + + +def test_a_quick_restart_s_chunks_are_read_after_the_first_launcher_s(tmp_path): + """A launcher restarted on the same host in the same second writes seq 0 again, under its + own folder: a dashboard that already consumed the first folder's chunks reads it (one + cursor per folder).""" + objects = DirectoryObjectStore(str(tmp_path / "store")) + first, second = (fleet_store.incarnation(host="h", pid=1, now=1795700000.0) for _ in range(2)) + rows = [{"event": "island_ready", "time_unix": 10.0 + i, "island": ISLAND, "island_id": 1} for i in range(3)] + objects.write(f"fleet/log/l1/{first}/00000000.jsonl", _text(rows[:1])) + objects.write(f"fleet/log/l1/{first}/00000001.jsonl", _text(rows[1:2])) + reader = fleet_store.log_reader(objects) + reducer = Reducer() + assert reader.pump(reducer) == 2 + objects.write(f"fleet/log/l1/{second}/00000000.jsonl", _text(rows[2:])) + assert reader.pump(reducer) == 1 and len(reader.cursors) == 2 + assert reducer.islands["1"]["last_ready_ts"] == 12.0 + + +# -- a reused run directory ------------------------------------------------------------------------ + +def test_the_copy_starts_where_this_run_s_lines_start(tmp_path): + path = tmp_path / "runs" / "r" / "fleet.jsonl" + assert fleet_store.copy_start(path, "s3://store/a") == 0 # a new run directory + path.write_bytes(_text(A_ROWS)) + size = path.stat().st_size + assert fleet_store.copy_start(path, "s3://store/a", learner_id=1) == 0 # the same run again + assert fleet_store.read_copy_record(path)["learner_id"] == 1 + assert fleet_store.copy_start(path, "s3://store/b") == size # another run's store: from the end + path.write_bytes(_text(A_ROWS + B_ROWS)) + assert fleet_store.copy_start(path, "s3://store/b") == size # that run's start is kept + other = tmp_path / "old" / "fleet.jsonl" + other.parent.mkdir() + other.write_bytes(_text(A_ROWS)) # written before the copy record existed + assert fleet_store.copy_start(other, "s3://store/a") == other.stat().st_size + + +def test_a_reused_run_directory_uploads_only_this_run_s_lines(tmp_path, monkeypatch): + monkeypatch.setattr("yeto.runs.run_dir", lambda run: tmp_path / run) + (tmp_path / "run-i1").mkdir() + old = _text([{"event": "island_ready", "time_unix": 1.0, "island": ISLAND, "island_id": 0}]) + (tmp_path / "run-i1" / "fleet.jsonl").write_bytes(old) # an earlier run of this name + store = tmp_path / "store" + args = _launch_args(tmp_path, role="island", learner=1) + args.rl_checkpoint_store = str(store) + log = manifest._dashboard_fleet_log(args, {ISLAND: SimpleNamespace()}, {ISLAND: ("job", None)}, # noqa: SLF001 + objects=DirectoryObjectStore(str(store))) + log.event("island_ready", ISLAND) + assert log.close() is True + uploaded = b"".join((store / k).read_bytes() for k in _store_keys(store)) + assert uploaded == log.path.read_bytes()[len(old):] and b'"time_unix": 1.0' not in uploaded + + +# -- yeto down ------------------------------------------------------------------------------------- + +def _down_run(tmp_path, monkeypatch, *, record=True, store_objects=None): + from yeto import cli + + monkeypatch.setattr(cli.runs, "run_dir", lambda run: tmp_path / run) + path = tmp_path / "r" / "fleet.jsonl" + path.parent.mkdir() + path.write_bytes(_text(B_ROWS[:1])) # the launcher was killed: the island is still open + store = tmp_path / "store" + if record: + fleet_store.copy_start(path, str(store), learner_id=1) + if store_objects is not None: + monkeypatch.setattr("yeto.launch.island_lifecycle.store_objects", lambda uri: store_objects) + return cli, path, store + + +def test_yeto_down_copies_the_island_stop_lines_into_the_store(tmp_path, monkeypatch): + cli, path, store = _down_run(tmp_path, monkeypatch) + assert cli._close_fleet_islands("r") == [ISLAND] # noqa: SLF001 + keys = _store_keys(store) + assert len(keys) == 1 and keys[0].startswith("fleet/log/l1/") + (rec,) = [json.loads(line) for line in (store / keys[0]).read_text().splitlines()] + assert rec["event"] == "island_stop" and rec["island_id"] == 1 + + +def test_yeto_down_of_a_local_only_run_copies_nothing(tmp_path, monkeypatch, capsys): + cli, path, store = _down_run(tmp_path, monkeypatch, record=False) + assert cli._close_fleet_islands("r") == [ISLAND] # noqa: SLF001 + assert not store.exists() and "WARN" not in capsys.readouterr().err + assert fleet_store.upload_appended(path, 0) is True # no copy record: nothing to copy, not a failure + + +def test_yeto_down_with_a_failing_store_still_closes_the_islands(tmp_path, monkeypatch, capsys): + monkeypatch.setattr(fleet_store, "FINAL_UPLOAD_S", 0.3) # the bounded final upload, short here + cli, path, store = _down_run(tmp_path, monkeypatch, store_objects=FailingObjects()) + assert cli._close_fleet_islands("r") == [ISLAND] # noqa: SLF001 + assert _records(path)[-1]["event"] == "island_stop" + assert "WARN" in capsys.readouterr().err + + +# -- arguments and status -------------------------------------------------------------------------- + +@pytest.mark.parametrize("bad", [0, 0.0, -1.0]) +def test_an_explicit_interval_must_be_positive(tmp_path, bad): + with pytest.raises(ValueError, match="interval_s must be > 0"): + fleet_store.start_uploader(DirectoryObjectStore(str(tmp_path)), tmp_path / "f.jsonl", interval_s=bad) + + +class _Status: + def __init__(self, **status): + self._status = {"label": "x", "sources": 1, "requests": 1, "errors": 0, "failing": 0, "last_error": None, + "last_error_at": None, "last_ok_at": None, "polled": True, **status} + self.objects = object() + + def status(self): + return dict(self._status) + + def pump(self, reducer): + return 0 + + +def test_the_store_status_is_ok_since_the_oldest_clean_poll(): + both = fleet_store.StoreReaders(_Status(last_ok_at=20.0), _Status(last_ok_at=10.0)) + assert both.status()["last_ok_at"] == 10.0 + one_never = fleet_store.StoreReaders(_Status(last_ok_at=20.0), _Status(last_ok_at=None)) + assert one_never.status()["last_ok_at"] is None + failed = fleet_store.StoreReaders(_Status(last_error="old", last_error_at=1.0, errors=1), + _Status(last_error="new", last_error_at=5.0, errors=2, failing=1)) + status = failed.status() + assert (status["last_error"], status["last_error_at"], status["errors"], status["failing"]) == ("new", 5.0, 3, 1) + assert fleet_store.StoreReaders(_Status(), _Status(polled=False)).status()["polled"] is False diff --git a/tests/test_fleet_log_store_launch.py b/tests/test_fleet_log_store_launch.py index 3c113194d..964b98026 100644 --- a/tests/test_fleet_log_store_launch.py +++ b/tests/test_fleet_log_store_launch.py @@ -93,3 +93,33 @@ def test_the_tape_uploader_default_keys_are_main_s(tmp_path): assert objects.keys == ["tapes/syncer/h-1/00000000.jsonl"] for fn in (tape_upload.trainer_uploader, tape_upload.syncer_uploaders): assert "prefix" not in inspect.getsource(fn) + + +def test_the_store_copy_stops_when_the_fleet_controller_cannot_be_built(monkeypatch, tmp_path): + """The fleet log (and its store copy) is built before the controller; a controller that + raises in its constructor still gets the copy stopped by the launcher's teardown.""" + from yeto.dashboard import fleet_store + + stopped = [] + + class Uploader: + island = "fleet" + + def stop(self, timeout_s=None): + stopped.append(timeout_s) + return True + + monkeypatch.setattr(fleet_store, "start_uploader", lambda *a, **k: Uploader()) + cluster = FakeCluster(NAMES) + monkeypatch.setattr("yeto.launch.ssh_resident.SshOps", lambda: cluster) + record, clock = [], _drive(monkeypatch) + _setup(monkeypatch, tmp_path, failing=set(), clock=clock, record=record) + + def broken(*a, **kw): + raise RuntimeError("controller init failed") + + monkeypatch.setattr(launcher, "FleetController", broken) + args = _args(tmp_path, "--island-lifecycle", "on", "--rl-checkpoint-store", str(tmp_path / "run-store")) + with pytest.raises(RuntimeError, match="controller init failed"): + launcher.run(args) + assert stopped == [fleet_store.FINAL_UPLOAD_S] diff --git a/yeto/cli.py b/yeto/cli.py index ec70c1299..65b1500dc 100644 --- a/yeto/cli.py +++ b/yeto/cli.py @@ -2583,8 +2583,14 @@ def _down_one(cluster: str) -> None: def _close_fleet_islands(name: str) -> list[str]: try: from .dashboard.fleet import FLEET_FILE, close_open_islands, teardown_stop_reason - - return close_open_islands(runs.run_dir(name) / FLEET_FILE, teardown_stop_reason()) + from .dashboard.fleet_store import upload_appended + + path = runs.run_dir(name) / FLEET_FILE + before = path.stat().st_size if path.is_file() else 0 + closed = close_open_islands(path, teardown_stop_reason()) + if closed: # a fleet.jsonl copied into the run store gets these lines too (WARN on failure) + upload_appended(path, before) + return closed except Exception as e: # noqa: BLE001 - telemetry never fails a down print(f"[yeto] fleet.jsonl: island_stop not written ({e})", file=sys.stderr) return [] diff --git a/yeto/dashboard/fleet_store.py b/yeto/dashboard/fleet_store.py index 220292cd2..e1fd3c476 100644 --- a/yeto/dashboard/fleet_store.py +++ b/yeto/dashboard/fleet_store.py @@ -8,13 +8,16 @@ event tape goes (:class:`yeto.rl.engine.tape_upload.TapeUploader`): every ``interval_s`` the complete lines added since the last upload become one new object - ``fleet/log//-p-/.jsonl`` + ``fleet/log//-p--/.jsonl`` ``lane`` is ``l`` for an island launch of a fleet launched island by island (learner id ``k``) and ``fleet`` for a launch of the whole fleet; each launcher process adds its -own folder, so two hosts (or two launches of one host) never write the same key. The -copy starts at the beginning of the local file: a launcher restarted on the same host -uploads the earlier records again, and the readers fold each record once. +own folder (a random nonce: two launchers of one host never share one, even with the same +pid in the same second), so no two write the same key. The copy covers this run's part of +the local file (:func:`copy_start`: a run directory reused by another run starts at the +file's end); a launcher restarted for the same run uploads its earlier lines again, and the +readers fold each record once. ``yeto down`` copies the ``island_stop`` lines it appends +(:func:`upload_appended`). Observation only: a failed upload is a WARN on stderr and is retried with the next chunk; it never reaches the launcher. A launch without island records in a store (one @@ -31,9 +34,11 @@ import json import os +import secrets import socket import sys import time +from pathlib import Path from typing import Any, Callable, Iterable LOG_PREFIX = "fleet/log" # chunk keys: ///.jsonl @@ -49,13 +54,64 @@ def lane(learner_id: Any = None) -> str: return FLEET_LANE -def incarnation(*, host: str | None = None, pid: int | None = None, now: float | None = None) -> str: - """This launcher's folder: host, pid and UTC start (the start ends the name, as the - trainer tape folders do, so readers order a lane's folders by start).""" +def incarnation(*, host: str | None = None, pid: int | None = None, now: float | None = None, + nonce: str | None = None) -> str: + """This launcher's folder: host, pid, a random nonce and UTC start. The nonce keeps two + launchers of one host apart even with the same pid in the same second (containers); the + start ends the name, as the trainer tape folders do, so readers order a lane's folders + by start.""" host = host if host is not None else socket.gethostname() pid = os.getpid() if pid is None else int(pid) + nonce = secrets.token_hex(4) if nonce is None else str(nonce) stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime(time.time() if now is None else now)) - return f"{host}-p{pid}-{stamp}" + return f"{host}-p{pid}-{nonce}-{stamp}" + + +# -- which part of the local file belongs to this store --------------------------------------- +# +# A run directory (``~/.yeto/runs//``) outlives its run: a new run of the same name +# appends to the same ``fleet.jsonl``. ``fleet.store.json`` next to it records the store the +# file is copied to and the byte offset the copy starts at. A launch for the same store goes +# on from that offset (a restarted launcher of the run uploads its earlier lines again: the +# readers fold each record once); a launch for another store, or a file without the record +# (written before this copy existed), starts at the file's end, so an earlier run's lines +# never reach this run's store (the rule of ``tape_upload.syncer_uploaders(from_end=True)``). + +COPY_RECORD = "fleet.store.json" +COPY_SCHEMA = "yeto.fleet.log-copy/v1" + + +def copy_record_path(path: str | os.PathLike) -> Path: + return Path(path).with_name(COPY_RECORD) + + +def read_copy_record(path: str | os.PathLike) -> dict | None: + try: + doc = json.loads(copy_record_path(path).read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + return doc if isinstance(doc, dict) and doc.get("schema") == COPY_SCHEMA and doc.get("store") else None + + +def copy_start(path: str | os.PathLike, store: str, *, learner_id: Any = None) -> int: + """The byte offset of ``path`` this launch's copy into ``store`` starts at (see above), + recorded for the next launch and for ``yeto down``. Never raises (a record that cannot be + written: the offset still holds for this launch).""" + p = Path(path) + try: + size = p.stat().st_size + except OSError: + size = 0 + known = read_copy_record(p) + start = min(int(known.get("start") or 0), size) if known and known.get("store") == str(store) else size + doc = {"schema": COPY_SCHEMA, "store": str(store), "start": start, + "learner_id": learner_id if lane(learner_id) != FLEET_LANE else None} + try: + p.parent.mkdir(parents=True, exist_ok=True) + copy_record_path(p).write_text(json.dumps(doc, sort_keys=True) + "\n", encoding="utf-8") + except OSError as exc: + _stderr(f"[launcher] WARN: fleet.jsonl store copy: {COPY_RECORD} not written ({type(exc).__name__})") + return start class _Warn: @@ -77,23 +133,60 @@ def _stderr(message: str) -> None: def start_uploader(objects: Any, path: str | os.PathLike, *, learner_id: Any = None, environ: Any = None, - log: Callable[[str], None] = _stderr, interval_s: float | None = None) -> Any: - """The started copy of ``path`` into ``objects`` (module doc), or None: the upload - interval is 0 (``YETO_RL_TAPE_UPLOAD_S``), or it could not start (a WARN). Never raises.""" + log: Callable[[str], None] = _stderr, interval_s: float | None = None, offset: int = 0) -> Any: + """The started copy of ``path`` from byte ``offset`` into ``objects`` (module doc), or + None: the upload interval is 0 (``YETO_RL_TAPE_UPLOAD_S``), or it could not start (a + WARN). An explicit ``interval_s`` must be positive (ValueError: a caller's bug); otherwise + never raises.""" + if interval_s is not None and not interval_s > 0: + raise ValueError(f"fleet.jsonl store copy: interval_s must be > 0 (got {interval_s!r}); " + "turn the copy off with YETO_RL_TAPE_UPLOAD_S=0") try: from yeto.rl.engine.tape_upload import TapeUploader, upload_interval_s # noqa: PLC0415 interval = upload_interval_s(None, environ) if interval_s is None else interval_s - if interval is None or interval <= 0: + if interval is None: return None uploader = TapeUploader(objects, path, island=lane(learner_id), incarnation=incarnation(), interval_s=interval, log=_Warn(log), prefix=LOG_PREFIX) + uploader.offset = max(0, int(offset)) return uploader.start() except Exception as exc: # noqa: BLE001 - telemetry never stops a launch log(f"[launcher] WARN: fleet.jsonl store copy not started ({type(exc).__name__}: {exc})"[:300]) return None +def upload_appended(path: str | os.PathLike, offset: int, *, objects: Any = None, + timeout_s: float | None = None, log: Callable[[str], None] = _stderr) -> bool: + """``yeto down``: the lines appended to ``path`` from ``offset`` on (the ``island_stop`` + of the islands a killed launcher left open) into the store its copy record names, in the + record's lane, as one more folder; bounded. Nothing without a copy record (a run whose + fleet.jsonl stays local) or without new lines. A failure is a WARN; never raises. + Returns True when the store has every new line (or there is nothing to copy).""" + try: + record = read_copy_record(path) + if record is None: + return True + size = Path(path).stat().st_size + if size <= offset: + return True + if objects is None: + from yeto.launch.island_lifecycle import store_objects # noqa: PLC0415 + + objects = store_objects(record["store"]) + if objects is None: + return True + from yeto.rl.engine.tape_upload import TapeUploader # noqa: PLC0415 + + uploader = TapeUploader(objects, path, island=lane(record.get("learner_id")), incarnation=incarnation(), + interval_s=FINAL_UPLOAD_S, log=_Warn(log), prefix=LOG_PREFIX) + uploader.offset = int(offset) + return bool(uploader.stop(FINAL_UPLOAD_S if timeout_s is None else timeout_s)) + except Exception as exc: # noqa: BLE001 - telemetry never fails a down + log(f"[yeto] WARN: fleet.jsonl store copy: island_stop lines not copied ({type(exc).__name__}: {exc})"[:300]) + return False + + def stop_uploader(uploader: Any, timeout_s: float = FINAL_UPLOAD_S) -> bool: """The final upload, bounded; True when the store has every complete line. Never raises.""" if uploader is None: @@ -214,7 +307,6 @@ def feed(self, record: Any, *, source: str = "-", offset: int | None = None, **_ def main(argv: Any = None) -> int: """``merge --store URI [--fleet-log PATH]... [--out PATH]``: one ``fleet.jsonl``.""" import argparse # noqa: PLC0415 - from pathlib import Path # noqa: PLC0415 parser = argparse.ArgumentParser(prog="python -m yeto.dashboard.fleet_store") sub = parser.add_subparsers(dest="cmd", required=True) diff --git a/yeto/dashboard/reducer.py b/yeto/dashboard/reducer.py index 3d5dfe761..9e5f42d76 100644 --- a/yeto/dashboard/reducer.py +++ b/yeto/dashboard/reducer.py @@ -346,6 +346,10 @@ def __init__(self, *, run: str | None = None, prices: dict | None = None, self.fleet_records: deque = deque(maxlen=FLEET_VIEW_MAX) # the view shows the last ones self.spot: deque = deque(maxlen=SPOT_MAX) self.cost_ticks: deque = deque(maxlen=FLEET_VIEW_MAX) + # island -> its timed fleet.jsonl lifecycle records [(time, seq, event)], in time order: + # an older record that arrives later (another host's store copy) is replayed in place + self.fleet_lifecycle: dict[str, list[tuple[float, int, str]]] = {} + self.fleet_shape_ts: dict[str, dict[str, float]] = {} # island -> shape field -> its record's time self.events: deque = deque(maxlen=MAX_EVENTS) self.event_seq = 0 self.max_ts: float | None = None @@ -1447,11 +1451,34 @@ def _feed_fleet(self, r: dict, iid: str | None, ts: float | None) -> None: if iid is None: return isl = self.island(iid) - for key in ("cloud", "region", "gpu", "gpus", "price_key", "cpus", "memory_gib"): - if r.get(key) is not None: - isl[key] = r[key] - if r.get("island") is not None: - isl["name"] = r["island"] + life = self.fleet_lifecycle.setdefault(iid, []) + older = ts is not None and bool(life) and ts < life[-1][0] + shape_ts = self.fleet_shape_ts.setdefault(iid, {}) + for key, field in (*((k, k) for k in ("cloud", "region", "gpu", "gpus", "price_key", "cpus", + "memory_gib")), ("name", "island")): + # each shape field: the newest record that names it (an older one arriving later does not) + if r.get(field) is not None and (ts is None or ts >= shape_ts.get(key, ts)): + isl[key] = r[field] + if ts is not None: + shape_ts[key] = ts + if ts is not None: + bisect.insort(life, (ts, self.event_seq, event)) + if older: # folded in time order again: the newest record still decides the state + self._replay_fleet_lifecycle(isl, life) + return + self._fold_fleet_lifecycle(isl, event, ts) + + def _replay_fleet_lifecycle(self, isl: dict, life: list[tuple[float, int, str]]) -> None: + """The island's lifecycle fields from its timed records alone, in time order (the + fold of :meth:`_fold_fleet_lifecycle`, from a new island's values).""" + fresh = _new_island(isl["id"]) + for key in ("fleet_state", "ready_ts", "last_ready_ts", "stop_ts", "lost_ts", "open_ts", "closed_s"): + isl[key] = fresh[key] + for t, _seq, event in life: + self._fold_fleet_lifecycle(isl, event, t) + + @staticmethod + def _fold_fleet_lifecycle(isl: dict, event: str, ts: float | None) -> None: isl["fleet_state"] = event[len("island_"):] # wall clock accrues over ready -> lost/stop intervals (relaunches re-open one) if event == "island_ready" and ts is not None: diff --git a/yeto/launch/manifest.py b/yeto/launch/manifest.py index 6b0ce4303..8e7cdd6df 100644 --- a/yeto/launch/manifest.py +++ b/yeto/launch/manifest.py @@ -119,10 +119,14 @@ def _dashboard_fleet_log(args, tasks, results, objects=None): except Exception as e: # noqa: BLE001 print(f"[launcher] fleet.jsonl disabled: {e}", file=sys.stderr) return None - if objects is not None: - from ..dashboard.fleet_store import start_uploader - - log.uploader = start_uploader(objects, log.path, learner_id=None if member is None else member[0]) + store = getattr(args, "rl_checkpoint_store", None) + if objects is not None and store: + from ..dashboard.fleet_store import copy_start, start_uploader + + learner = None if member is None else member[0] + # a reused run directory: only this run's lines go to its store (fleet_store.copy_start) + log.uploader = start_uploader(objects, log.path, learner_id=learner, + offset=copy_start(log.path, str(store), learner_id=learner)) return log diff --git a/yeto/launcher.py b/yeto/launcher.py index a663d5285..e2b13b36e 100644 --- a/yeto/launcher.py +++ b/yeto/launcher.py @@ -880,6 +880,7 @@ def run(args, on_clusters=None, local_syncer=None, on_instance_ids=None) -> int: clusters: list[str] = [] sky_storages: dict[str, str] = {} # bucket sky creates -> its island cluster (sky_storage_ledger) controller = None + fleet_log = None # dashboard.fleet.FleetLog of the run (its store copy is stopped at the end) teardown_unverified = False run_started_unix = time.time() # Modal rows created after this are this run's app # Every billed resource of this run goes into its crash-safe ledger; the cost guard @@ -1286,6 +1287,10 @@ def route_container(learner_id: int): sky_sdk_ops = SkySDKOps() # the failure-path teardown verifies every node instance sky_sdk_ops.nodes_by_cluster = dict(nodes_by_cluster) + # built before the controller: the finally block stops its store copy even when the + # controller cannot be built + fleet_log = _dashboard_fleet_log(args, tasks, results, + objects=None if island_states is None else island_states.objects) controller = FleetController( learners={name: (tasks[name], job_id) for name, (job_id, _h) in results.items()}, syncer=None if syncer_cluster is None else (syncer_cluster, syncer_task, syncer_job), @@ -1314,8 +1319,7 @@ def route_container(learner_id: int): no_recover=verda["no_recover"] if verda else (), instance_guard=verda["guard"] if verda else None, on_rename=_rename_hook(clusters, on_clusters, [] if head_mode else [syncer_cluster]), - fleet_log=_dashboard_fleet_log(args, tasks, results, - objects=None if island_states is None else island_states.objects), + fleet_log=fleet_log, syncer_finished_probe=local_syncer.finished if head_mode else None, left_pool_probe=( (lambda name: name in event_collectors and event_collectors[name].left_pool) @@ -1691,11 +1695,10 @@ def drain_tapes(limit: float = NO_SYNC_EVENT_DRAIN_S) -> None: f"Terminate them from the cloud console, then: yeto down {prefix}", file=sys.stderr, ) - close_fleet_log = getattr(getattr(controller, "fleet_log", None), "close", None) - if callable(close_fleet_log): + if fleet_log is not None: # the store copy of fleet.jsonl: its last lines (the island_stop just written # included), bounded; a store that fails is a WARN, never the exit code - close_fleet_log() + fleet_log.close() if ssh_islands is not None: ssh_islands.close() # streams and locks; a kept island is reattached by the next launch if island_states is not None: From f372a9e29b4a7bebc34eb355c5d6d8b4adc60dd7 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 02:57:39 +0800 Subject: [PATCH 4/4] fleet.jsonl store copy: bind the copy record to its run; fold one source in write order The copy record (fleet.store.json) now names the run it belongs to (the run registry's started_at, new for each run of a name). copy_start resumes only for the same run and store; yeto down copies its island_stop lines only into the store the record of this run names. A launch that does not copy the file (no store, no island records, the copy turned off) voids an existing record (no store, the file's end), so a later yeto down or launch never puts its lines into an earlier run's store. A run directory that never had a record still gets none. The reducer folds the records of one source in write order (a clock stepped back in one file folds as on main) and replays an island's lifecycle only for a record older than the newest one of another source. The replay cost and the same-time tie across sources are documented. Co-Authored-By: Claude Opus 5.5 --- docs/DASHBOARD.md | 17 ++- tests/test_fleet_log_store.py | 221 +++++++++++++++++++++++++++++++--- yeto/cli.py | 4 +- yeto/dashboard/fleet_store.py | 79 ++++++++---- yeto/dashboard/reducer.py | 45 ++++--- yeto/launch/manifest.py | 9 +- 6 files changed, 312 insertions(+), 63 deletions(-) diff --git a/docs/DASHBOARD.md b/docs/DASHBOARD.md index 40b13b930..aed0f7601 100644 --- a/docs/DASHBOARD.md +++ b/docs/DASHBOARD.md @@ -220,10 +220,12 @@ the island launch of learner `k` and `fleet` for a launch of the whole fleet. Ev launcher process writes its own folder (the random nonce keeps two launchers of one host apart), so the events of a control plane that moved to another host, or of a host that was lost, stay in the store. Only this run's part of the local file is -copied: `fleet.store.json` next to it records the store and the offset the copy -starts at, and a run directory reused by a run with another store starts at the -file's end. `yeto down` copies the `island_stop` lines it appends for islands a -killed launcher left open. The copy is observation only: a failed upload is a +copied: `fleet.store.json` next to it records the run (its registry start), the +store and the offset the copy starts at. A restarted launcher of the run goes on +from that offset; a later run of the name starts at the file's end, and a launch +that does not copy the file voids the record (no store from the file's end on). +`yeto down` copies the `island_stop` lines it appends for islands a killed +launcher left open, only into the store the record of this run names. The copy is observation only: a failed upload is a `WARN` line, retried with the next chunk, and the launcher's end (and `yeto down`) waits at most 15 s for the last one. A launch of one trainer island uploads nothing, as before. `--store` reads every folder next to the island tapes, and a @@ -231,8 +233,11 @@ record that is also in a local `fleet.jsonl` given with `--tapes` counts once. T page folds an island's lifecycle records by their own time, whatever the order it reads them in: a host's older records that arrive after the newer host's (its run directory has only its own lines) add their closed ready -> lost intervals and do -not change the island's current state. A host clock that is off by more than the -gap between two hosts' records still orders those records by that clock. +not change the island's current state. Records of one source (one local file, one +launcher folder in the store) fold in the order they were written, so a host clock +stepped back (NTP) folds as before. A host clock that is off by more than the gap +between two hosts' records still orders those records by that clock, and records of +two hosts with the same `time_unix` fold in the order they are read (a known limit). For tools that read the file itself: ``` diff --git a/tests/test_fleet_log_store.py b/tests/test_fleet_log_store.py index 5710a4caa..bb38e83d1 100644 --- a/tests/test_fleet_log_store.py +++ b/tests/test_fleet_log_store.py @@ -20,7 +20,7 @@ from yeto.dashboard import fleet as fleet_mod from yeto.dashboard import fleet_store from yeto.dashboard.fleet import FleetLog, close_open_islands, from_env -from yeto.dashboard.reducer import Reducer +from yeto.dashboard.reducer import _FLEET_LIFE, Reducer, _new_island from yeto.dashboard.sources import load_all from yeto.dashboard.store_tapes import StoreTapes from yeto.launch import manifest @@ -270,24 +270,80 @@ def test_a_folder_stamp_two_hours_off_does_not_change_the_state(tmp_path): assert _lifecycle(reducer.islands["1"]) == RUNNING_AGAIN -@pytest.mark.parametrize("order", ["in-order", "reversed", "lost-first"]) +LIFE = [{"event": "island_ready", "time_unix": 10.0, "island": ISLAND, "island_id": 1, "gpu": "B300"}, + {"event": "island_lost", "time_unix": 20.0, "island": ISLAND, "island_id": 1}, + {"event": "island_ready", "time_unix": 30.0, "island": ISLAND, "island_id": 1, "gpu": "H100"}, + {"event": "island_stop", "time_unix": 50.0, "island": ISLAND, "island_id": 1, "reason": "teardown"}] +HOST = ["host-a", "host-a", "host-b", "host-b"] # the lost host wrote the first two, the new one the rest + + +@pytest.mark.parametrize("order", [[0, 1, 2, 3], [2, 3, 0, 1], [2, 0, 3, 1], [2, 0, 1, 3], [0, 2, 3, 1]]) def test_the_lifecycle_does_not_depend_on_the_read_order(order): - rows = [{"event": "island_ready", "time_unix": 10.0, "island": ISLAND, "island_id": 1, "gpu": "B300"}, - {"event": "island_lost", "time_unix": 20.0, "island": ISLAND, "island_id": 1}, - {"event": "island_ready", "time_unix": 30.0, "island": ISLAND, "island_id": 1, "gpu": "H100"}, - {"event": "island_stop", "time_unix": 50.0, "island": ISLAND, "island_id": 1, "reason": "teardown"}] + """Two sources (hosts) read in any interleaving, each in its own order.""" want = Reducer() - for r in rows: + for r in LIFE: want.feed(dict(r)) got = Reducer() - feed = {"in-order": rows, "reversed": rows[::-1], "lost-first": [rows[1], rows[3], rows[0], rows[2]]}[order] - for r in feed: - got.feed(dict(r)) + for k in order: + got.feed(dict(LIFE[k]), source=HOST[k]) assert _lifecycle(got.islands["1"]) == _lifecycle(want.islands["1"]) assert _lifecycle(want.islands["1"])["closed_s"] == pytest.approx(30.0) assert got.islands["1"]["gpu"] == "H100" # the newest record's shape +def _main_fold(rows): + """origin/main's fold of one source: every record in write order.""" + isl = {k: _new_island("1")[k] for k in _FLEET_LIFE} + for r in rows: + Reducer._fold_fleet_lifecycle(isl, r["event"], r.get("time_unix")) # noqa: SLF001 + return isl + + +@pytest.mark.parametrize("source", [None, "fleet.jsonl"]) +def test_a_clock_stepped_back_in_one_file_folds_in_write_order(source): + """NTP steps the launcher host's clock back between ready and lost: one file, written in + order. The island is lost, as on main (not ready and billed on).""" + rows = [{"event": "island_ready", "time_unix": 100.0, "island": ISLAND, "island_id": 1, "gpu": "B300"}, + {"event": "island_lost", "time_unix": 90.0, "island": ISLAND, "island_id": 1}, + {"event": "island_ready", "time_unix": 95.0, "island": ISLAND, "island_id": 1, "gpu": "H100"}, + {"event": "island_stop", "time_unix": 99.0, "island": ISLAND, "island_id": 1}] + for n in range(1, len(rows) + 1): + reducer = Reducer() + for r in rows[:n]: + reducer.feed(dict(r), **({} if source is None else {"source": source})) + assert _lifecycle(reducer.islands["1"]) == _lifecycle(_main_fold(rows[:n])), n + assert reducer.islands["1"]["fleet_state"] == "stop" and reducer.islands["1"]["gpu"] == "H100" + lost = Reducer() + for r in rows[:2]: + lost.feed(dict(r), source="fleet.jsonl") + assert lost.islands["1"]["fleet_state"] == "lost" and lost.islands["1"]["open_ts"] is None + # another host's older interval read after it: replayed, each record at its own time + for r in ({"event": "island_ready", "time_unix": 50.0, "island": ISLAND, "island_id": 1}, + {"event": "island_lost", "time_unix": 60.0, "island": ISLAND, "island_id": 1}): + lost.feed(dict(r), source="old-host") + assert lost.islands["1"]["fleet_state"] == "lost" and lost.islands["1"]["lost_ts"] == 90.0 + assert lost.islands["1"]["closed_s"] == pytest.approx(10.0) and lost.islands["1"]["ready_ts"] == 50.0 + + +def test_a_late_copy_is_folded_in_at_its_place_and_the_rest_replayed(): + """A record of another source before several folded ones: the state from there on is the + time-ordered fold (the replay starts at the record, not at the island's first one).""" + rows = [{"event": e, "time_unix": t, "island": ISLAND, "island_id": 1} + for e, t in (("island_ready", 10.0), ("island_lost", 20.0), ("island_ready", 30.0), + ("island_lost", 40.0), ("island_ready", 60.0))] + want = Reducer() + for r in rows: + want.feed(dict(r)) + for late in range(len(rows)): + got = Reducer() + for k, r in enumerate(rows): + if k != late: + got.feed(dict(r), source="new-host") + got.feed(dict(rows[late]), source="old-host") + assert _lifecycle(got.islands["1"]) == _lifecycle(want.islands["1"]), late + assert want.islands["1"]["closed_s"] == pytest.approx(20.0) and want.islands["1"]["open_ts"] == 60.0 + + def test_the_store_readers_report_both_readers(tmp_path): objects, *_ = _two_hosts(tmp_path) store = fleet_store.store_readers(StoreTapes(objects, label="store")) @@ -403,18 +459,150 @@ def test_a_quick_restart_s_chunks_are_read_after_the_first_launcher_s(tmp_path): def test_the_copy_starts_where_this_run_s_lines_start(tmp_path): path = tmp_path / "runs" / "r" / "fleet.jsonl" - assert fleet_store.copy_start(path, "s3://store/a") == 0 # a new run directory + assert fleet_store.copy_start(path, "s3://store/a", run=1.0) == 0 # a new run directory path.write_bytes(_text(A_ROWS)) size = path.stat().st_size - assert fleet_store.copy_start(path, "s3://store/a", learner_id=1) == 0 # the same run again + assert fleet_store.copy_start(path, "s3://store/a", learner_id=1, run=1.0) == 0 # the run restarted assert fleet_store.read_copy_record(path)["learner_id"] == 1 - assert fleet_store.copy_start(path, "s3://store/b") == size # another run's store: from the end + assert fleet_store.copy_start(path, "s3://store/a", run=2.0) == size # another run, same store: from the end + assert fleet_store.copy_start(path, "s3://store/b", run=2.0) == size # another store: from the end path.write_bytes(_text(A_ROWS + B_ROWS)) - assert fleet_store.copy_start(path, "s3://store/b") == size # that run's start is kept + assert fleet_store.copy_start(path, "s3://store/b", run=2.0) == size # that run's start is kept + assert fleet_store.copy_start(path, "s3://store/b") == path.stat().st_size # no run identity: the end other = tmp_path / "old" / "fleet.jsonl" other.parent.mkdir() other.write_bytes(_text(A_ROWS)) # written before the copy record existed - assert fleet_store.copy_start(other, "s3://store/a") == other.stat().st_size + assert fleet_store.copy_start(other, "s3://store/a", run=1.0) == other.stat().st_size + + +def _new_run(name="run-i1"): + """A run of ``name`` in the (test's) run registry: its identity, new each time.""" + from yeto import runs + + runs.create_run(name, {}) + started = fleet_store.run_identity(name) + assert started is not None + return started + + +def _launch(tmp_path, store=None, *, environ=None, monkeypatch=None): + """One island launch of learner 1 (``store``: it copies its fleet.jsonl there), one record.""" + args = _launch_args(tmp_path, role="island", learner=1) + args.rl_checkpoint_store = None if store is None else str(store) + log = manifest._dashboard_fleet_log(args, {ISLAND: SimpleNamespace()}, {ISLAND: ("job", None)}, # noqa: SLF001 + objects=None if store is None else DirectoryObjectStore(str(store))) + log.event("island_ready", ISLAND) + return log + + +def _uploaded(store) -> bytes: + return b"".join((store / k).read_bytes() for k in _store_keys(store)) if store.exists() else b"" + + +def _folders(store) -> list[bytes]: + """Each launcher folder's bytes, in a fixed order (folder names carry a random nonce).""" + out: dict[str, bytes] = {} + for k in _store_keys(store) if store.exists() else (): + folder = k.rsplit("/", 1)[0] + out[folder] = out.get(folder, b"") + (store / k).read_bytes() + return sorted(out.values()) + + +def test_yeto_down_after_a_launch_without_a_copy_leaves_the_earlier_store_alone(tmp_path, monkeypatch): + """run 1 copies into S1; run 2 of the name keeps its fleet.jsonl local and its launcher is + killed; yeto down closes run 2's island: its island_stop stays out of S1.""" + from yeto import cli + + monkeypatch.setattr("yeto.runs.run_dir", lambda run: tmp_path / run) + s1 = tmp_path / "s1" + _new_run() + assert _launch(tmp_path, s1).close() is True + before = _uploaded(s1) + _new_run() + log = _launch(tmp_path) # killed: never closed + assert fleet_store.read_copy_record(log.path) is None # the record names no store any more + assert cli._close_fleet_islands("run-i1") == [ISLAND] # noqa: SLF001 + assert _records(log.path)[-1]["event"] == "island_stop" and _uploaded(s1) == before + + +def test_yeto_down_does_not_use_another_run_s_record(tmp_path, monkeypatch): + """A record left by an earlier run of the name (its launch never voided it): yeto down of + this run copies nothing into that run's store.""" + from yeto import cli + + monkeypatch.setattr("yeto.runs.run_dir", lambda run: tmp_path / run) + s1 = tmp_path / "s1" + path = tmp_path / "run-i1" / "fleet.jsonl" + path.parent.mkdir() + fleet_store.copy_start(path, str(s1), learner_id=1, run=_new_run()) + _new_run() + path.write_bytes(_text(B_ROWS[:1])) # this run's open island + monkeypatch.setattr("yeto.launch.island_lifecycle.store_objects", lambda uri: DirectoryObjectStore(uri)) + assert cli._close_fleet_islands("run-i1") == [ISLAND] # noqa: SLF001 + assert not s1.exists() + + +def test_a_launch_without_a_copy_between_two_copies_into_one_store_stays_local(tmp_path, monkeypatch): + """S2, a launch that keeps its lines local, S2 again: the middle run's lines never reach S2.""" + monkeypatch.setattr("yeto.runs.run_dir", lambda run: tmp_path / run) + s2 = tmp_path / "s2" + _new_run() + assert _launch(tmp_path, s2).close() is True + first = _folders(s2) + _new_run() + middle = _launch(tmp_path) + middle.event("island_stop", ISLAND) + assert middle.close() is True + size = middle.path.stat().st_size + _new_run() + third = _launch(tmp_path, s2) + assert third.close() is True + assert _folders(s2) == sorted([*first, third.path.read_bytes()[size:]]) + + +def test_another_run_s_record_for_the_same_store_starts_at_the_end(tmp_path, monkeypatch): + """The record of an earlier run for this store, not voided (that run's launch was older + or died first): a new run starts at the file's end all the same.""" + monkeypatch.setattr("yeto.runs.run_dir", lambda run: tmp_path / run) + s2 = tmp_path / "s2" + path = tmp_path / "run-i1" / "fleet.jsonl" + path.parent.mkdir() + fleet_store.copy_start(path, str(s2), learner_id=1, run=_new_run()) + path.write_bytes(_text(A_ROWS)) # lines of runs that are not the next one + _new_run() + log = _launch(tmp_path, s2) + assert log.close() is True + assert _uploaded(s2) == log.path.read_bytes()[len(_text(A_ROWS)):] + + +def test_a_restarted_launcher_of_the_run_goes_on_from_the_run_s_start(tmp_path, monkeypatch): + monkeypatch.setattr("yeto.runs.run_dir", lambda run: tmp_path / run) + store = tmp_path / "s" + _new_run() + assert _launch(tmp_path, store).close() is True + again = _launch(tmp_path, store) # the same run (no new registry entry) + assert fleet_store.read_copy_record(again.path)["start"] == 0 and again.close() is True + + +def test_a_launch_with_the_copy_turned_off_voids_the_record(tmp_path, monkeypatch): + monkeypatch.setattr("yeto.runs.run_dir", lambda run: tmp_path / run) + store = tmp_path / "s" + _new_run() + assert _launch(tmp_path, store).close() is True + monkeypatch.setenv("YETO_RL_TAPE_UPLOAD_S", "0") + log = _launch(tmp_path, store) + assert log.uploader is None and fleet_store.read_copy_record(log.path) is None + assert json.loads(fleet_store.copy_record_path(log.path).read_text())["start"] == log.path.stat().st_size \ + - len(_text([_records(log.path)[-1]])) + + +def test_a_launch_without_a_record_writes_none(tmp_path, monkeypatch): + """A local-only launch of a run directory that never had a copy (one trainer island, the + customer path): no fleet.store.json appears.""" + monkeypatch.setattr("yeto.runs.run_dir", lambda run: tmp_path / run) + _new_run() + log = _launch(tmp_path) + assert log.close() is True and not fleet_store.copy_record_path(log.path).exists() def test_a_reused_run_directory_uploads_only_this_run_s_lines(tmp_path, monkeypatch): @@ -443,8 +631,9 @@ def _down_run(tmp_path, monkeypatch, *, record=True, store_objects=None): path.parent.mkdir() path.write_bytes(_text(B_ROWS[:1])) # the launcher was killed: the island is still open store = tmp_path / "store" + cli.runs.create_run("r", {}) if record: - fleet_store.copy_start(path, str(store), learner_id=1) + fleet_store.copy_start(path, str(store), learner_id=1, run=fleet_store.run_identity("r")) if store_objects is not None: monkeypatch.setattr("yeto.launch.island_lifecycle.store_objects", lambda uri: store_objects) return cli, path, store diff --git a/yeto/cli.py b/yeto/cli.py index 65b1500dc..3a47463fb 100644 --- a/yeto/cli.py +++ b/yeto/cli.py @@ -2583,13 +2583,13 @@ def _down_one(cluster: str) -> None: def _close_fleet_islands(name: str) -> list[str]: try: from .dashboard.fleet import FLEET_FILE, close_open_islands, teardown_stop_reason - from .dashboard.fleet_store import upload_appended + from .dashboard.fleet_store import run_identity, upload_appended path = runs.run_dir(name) / FLEET_FILE before = path.stat().st_size if path.is_file() else 0 closed = close_open_islands(path, teardown_stop_reason()) if closed: # a fleet.jsonl copied into the run store gets these lines too (WARN on failure) - upload_appended(path, before) + upload_appended(path, before, run=run_identity(name)) return closed except Exception as e: # noqa: BLE001 - telemetry never fails a down print(f"[yeto] fleet.jsonl: island_stop not written ({e})", file=sys.stderr) diff --git a/yeto/dashboard/fleet_store.py b/yeto/dashboard/fleet_store.py index e1fd3c476..ace84e04d 100644 --- a/yeto/dashboard/fleet_store.py +++ b/yeto/dashboard/fleet_store.py @@ -70,12 +70,15 @@ def incarnation(*, host: str | None = None, pid: int | None = None, now: float | # -- which part of the local file belongs to this store --------------------------------------- # # A run directory (``~/.yeto/runs//``) outlives its run: a new run of the same name -# appends to the same ``fleet.jsonl``. ``fleet.store.json`` next to it records the store the -# file is copied to and the byte offset the copy starts at. A launch for the same store goes -# on from that offset (a restarted launcher of the run uploads its earlier lines again: the -# readers fold each record once); a launch for another store, or a file without the record -# (written before this copy existed), starts at the file's end, so an earlier run's lines -# never reach this run's store (the rule of ``tape_upload.syncer_uploaders(from_end=True)``). +# appends to the same ``fleet.jsonl``. ``fleet.store.json`` next to it records the run (the +# run registry's ``started_at``, new for each run of the name: :func:`run_identity`), the store +# the file is copied to and the byte offset the copy starts at. A launch of the same run for +# the same store goes on from that offset (a restarted launcher of the run uploads its earlier +# lines again: the readers fold each record once); any other launch, or a file without the +# record (written before this copy existed), starts at the file's end, so an earlier run's +# lines never reach this run's store (the rule of ``tape_upload.syncer_uploaders(from_end=True)``). +# A launch that does not copy the file voids the record (:func:`copy_off`): no store, the file's +# end. ``yeto down`` copies its lines only for the run the record names. COPY_RECORD = "fleet.store.json" COPY_SCHEMA = "yeto.fleet.log-copy/v1" @@ -93,27 +96,58 @@ def read_copy_record(path: str | os.PathLike) -> dict | None: return doc if isinstance(doc, dict) and doc.get("schema") == COPY_SCHEMA and doc.get("store") else None -def copy_start(path: str | os.PathLike, store: str, *, learner_id: Any = None) -> int: - """The byte offset of ``path`` this launch's copy into ``store`` starts at (see above), - recorded for the next launch and for ``yeto down``. Never raises (a record that cannot be - written: the offset still holds for this launch).""" - p = Path(path) +def run_identity(name: str) -> float | None: + """The run of ``name`` the copy record names: its run registry ``started_at`` (set anew by + every run of the name, kept by its launcher restarts and its ``yeto down``), or None.""" try: - size = p.stat().st_size + from yeto import runs # noqa: PLC0415 + + started = (runs.load_run(name) or {}).get("started_at") + return float(started) if started is not None else None + except Exception: # noqa: BLE001 - telemetry never stops a launch or a down + return None + + +def _size(p: Path) -> int: + try: + return p.stat().st_size except OSError: - size = 0 - known = read_copy_record(p) - start = min(int(known.get("start") or 0), size) if known and known.get("store") == str(store) else size - doc = {"schema": COPY_SCHEMA, "store": str(store), "start": start, - "learner_id": learner_id if lane(learner_id) != FLEET_LANE else None} + return 0 + + +def _write_record(p: Path, doc: dict) -> None: try: p.parent.mkdir(parents=True, exist_ok=True) copy_record_path(p).write_text(json.dumps(doc, sort_keys=True) + "\n", encoding="utf-8") except OSError as exc: _stderr(f"[launcher] WARN: fleet.jsonl store copy: {COPY_RECORD} not written ({type(exc).__name__})") + + +def copy_start(path: str | os.PathLike, store: str, *, learner_id: Any = None, run: float | None = None) -> int: + """The byte offset of ``path`` this launch's copy into ``store`` starts at (see above), + recorded for the next launch and for ``yeto down``. ``run``: :func:`run_identity` (None: + the file's end). Never raises (a record that cannot be written: the offset still holds for + this launch).""" + p = Path(path) + size = _size(p) + known = read_copy_record(p) + same = known is not None and known.get("store") == str(store) and run is not None and known.get("run") == run + start = min(int(known.get("start") or 0), size) if same else size + _write_record(p, {"schema": COPY_SCHEMA, "store": str(store), "start": start, "run": run, + "learner_id": learner_id if lane(learner_id) != FLEET_LANE else None}) return start +def copy_off(path: str | os.PathLike, *, run: float | None = None) -> None: + """A launch that does not copy ``path`` (no store, no island records, the copy turned + off): its record, if any, names no store from the file's end on, so neither ``yeto down`` + nor a later launch of another run copies this launch's lines into an earlier run's + store. A file without a record keeps none (one-island launches write nothing). Never raises.""" + p = Path(path) + if copy_record_path(p).exists(): + _write_record(p, {"schema": COPY_SCHEMA, "store": None, "start": _size(p), "run": run, "learner_id": None}) + + class _Warn: """The uploader's log: a WARN line for the first failure and every :data:`WARN_EVERY`-th.""" @@ -156,16 +190,17 @@ def start_uploader(objects: Any, path: str | os.PathLike, *, learner_id: Any = N return None -def upload_appended(path: str | os.PathLike, offset: int, *, objects: Any = None, +def upload_appended(path: str | os.PathLike, offset: int, *, run: float | None = None, objects: Any = None, timeout_s: float | None = None, log: Callable[[str], None] = _stderr) -> bool: """``yeto down``: the lines appended to ``path`` from ``offset`` on (the ``island_stop`` of the islands a killed launcher left open) into the store its copy record names, in the - record's lane, as one more folder; bounded. Nothing without a copy record (a run whose - fleet.jsonl stays local) or without new lines. A failure is a WARN; never raises. - Returns True when the store has every new line (or there is nothing to copy).""" + record's lane, as one more folder; bounded. Nothing without a copy record of this ``run`` + (:func:`run_identity`; a run whose fleet.jsonl stays local, or a record another run left) + or without new lines. A failure is a WARN; never raises. Returns True when the store has + every new line (or there is nothing to copy).""" try: record = read_copy_record(path) - if record is None: + if record is None or run is None or record.get("run") != run: return True size = Path(path).stat().st_size if size <= offset: diff --git a/yeto/dashboard/reducer.py b/yeto/dashboard/reducer.py index 9e5f42d76..17f2b7d02 100644 --- a/yeto/dashboard/reducer.py +++ b/yeto/dashboard/reducer.py @@ -320,6 +320,9 @@ def _new_island(iid: str) -> dict: } +_FLEET_LIFE = ("fleet_state", "ready_ts", "last_ready_ts", "stop_ts", "lost_ts", "open_ts", "closed_s") + + class Reducer: """Incremental tape -> view reducer. Not thread-safe; callers lock.""" @@ -346,9 +349,10 @@ def __init__(self, *, run: str | None = None, prices: dict | None = None, self.fleet_records: deque = deque(maxlen=FLEET_VIEW_MAX) # the view shows the last ones self.spot: deque = deque(maxlen=SPOT_MAX) self.cost_ticks: deque = deque(maxlen=FLEET_VIEW_MAX) - # island -> its timed fleet.jsonl lifecycle records [(time, seq, event)], in time order: - # an older record that arrives later (another host's store copy) is replayed in place - self.fleet_lifecycle: dict[str, list[tuple[float, int, str]]] = {} + # island -> its timed fleet.jsonl lifecycle records [(eff, seq, event, time)] in fold order: + # an older record of another source that arrives later (a store copy) is replayed in place + self.fleet_lifecycle: dict[str, list[tuple[float, int, str, float]]] = {} + self.fleet_source_ts: dict[tuple[str, str], float] = {} # (island, source) -> its newest record time self.fleet_shape_ts: dict[str, dict[str, float]] = {} # island -> shape field -> its record's time self.events: deque = deque(maxlen=MAX_EVENTS) self.event_seq = 0 @@ -1451,31 +1455,44 @@ def _feed_fleet(self, r: dict, iid: str | None, ts: float | None) -> None: if iid is None: return isl = self.island(iid) + # The island's timed lifecycle records in fold order (eff, seq, event, ts). A source's + # time never goes back (eff): a clock stepped back in one file folds in write order, as on + # main. A record before the newest of another source (a lost host's store copy read late) + # makes the island's lifecycle a replay of all its timed records in that order. Each such + # record costs one fold per record of the island: a whole host's copy read after the + # newer host's is quadratic (10k lifecycle records of one island, half per host: 5-15 s, + # once when a reader starts; a replay from the record's place is no cheaper here, every + # older record lands before all of the newer host's); in-order streams and late single + # records stay linear. Records of two + # sources at one time fold in arrival order (a known limit: docs/DASHBOARD.md). life = self.fleet_lifecycle.setdefault(iid, []) - older = ts is not None and bool(life) and ts < life[-1][0] + eff = None if ts is None else max(ts, self.fleet_source_ts.get((iid, self._source), ts)) + if eff is not None: + self.fleet_source_ts[(iid, self._source)] = eff + older = eff is not None and bool(life) and eff < life[-1][0] shape_ts = self.fleet_shape_ts.setdefault(iid, {}) for key, field in (*((k, k) for k in ("cloud", "region", "gpu", "gpus", "price_key", "cpus", "memory_gib")), ("name", "island")): # each shape field: the newest record that names it (an older one arriving later does not) - if r.get(field) is not None and (ts is None or ts >= shape_ts.get(key, ts)): + if r.get(field) is not None and (eff is None or eff >= shape_ts.get(key, eff)): isl[key] = r[field] - if ts is not None: - shape_ts[key] = ts - if ts is not None: - bisect.insort(life, (ts, self.event_seq, event)) + if eff is not None: + shape_ts[key] = eff + 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 self._replay_fleet_lifecycle(isl, life) return self._fold_fleet_lifecycle(isl, event, ts) - def _replay_fleet_lifecycle(self, isl: dict, life: list[tuple[float, int, str]]) -> None: - """The island's lifecycle fields from its timed records alone, in time order (the + def _replay_fleet_lifecycle(self, isl: dict, life: list[tuple[float, int, str, float]]) -> None: + """The island's lifecycle fields from its timed records alone, in fold order (the fold of :meth:`_fold_fleet_lifecycle`, from a new island's values).""" fresh = _new_island(isl["id"]) - for key in ("fleet_state", "ready_ts", "last_ready_ts", "stop_ts", "lost_ts", "open_ts", "closed_s"): + for key in _FLEET_LIFE: isl[key] = fresh[key] - for t, _seq, event in life: - self._fold_fleet_lifecycle(isl, event, t) + for _eff, _seq, event, ts in life: + self._fold_fleet_lifecycle(isl, event, ts) @staticmethod def _fold_fleet_lifecycle(isl: dict, event: str, ts: float | None) -> None: diff --git a/yeto/launch/manifest.py b/yeto/launch/manifest.py index 8e7cdd6df..aca6a1196 100644 --- a/yeto/launch/manifest.py +++ b/yeto/launch/manifest.py @@ -119,14 +119,17 @@ def _dashboard_fleet_log(args, tasks, results, objects=None): except Exception as e: # noqa: BLE001 print(f"[launcher] fleet.jsonl disabled: {e}", file=sys.stderr) return None + from ..dashboard.fleet_store import copy_off, copy_start, run_identity, start_uploader + store = getattr(args, "rl_checkpoint_store", None) + run = run_identity(args.cluster_prefix) if objects is not None and store: - from ..dashboard.fleet_store import copy_start, start_uploader - learner = None if member is None else member[0] # a reused run directory: only this run's lines go to its store (fleet_store.copy_start) log.uploader = start_uploader(objects, log.path, learner_id=learner, - offset=copy_start(log.path, str(store), learner_id=learner)) + offset=copy_start(log.path, str(store), learner_id=learner, run=run)) + if log.uploader is None: # no copy: a record an earlier launch left names no store from here on + copy_off(log.path, run=run) return log