Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions docs/DASHBOARD.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,48 @@ 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 (`<prefix>-l0-<cloud>`); 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<m>` 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/<lane>/<host>-p<pid>-<nonce>-<UTC start>/<seq>.jsonl`, lane `l<k>` 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 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
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. 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:

```
python -m yeto.dashboard.fleet_store merge --store s3://<bucket>/runs/<run> \
[--fleet-log ~/.yeto/runs/<run>/fleet.jsonl ...] --out fleet.merged.jsonl
```

writes one `fleet.jsonl`, in time order, each record once.

## Alert rules and thresholds

| Rule | Default threshold | Level |
Expand Down
696 changes: 696 additions & 0 deletions tests/test_fleet_log_store.py

Large diffs are not rendered by default.

125 changes: 125 additions & 0 deletions tests/test_fleet_log_store_launch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
"""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 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
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


# -- 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/<island>/<incarnation>/<seq>``),
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)


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]
10 changes: 8 additions & 2 deletions yeto/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 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, 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)
return []
Expand Down
7 changes: 5 additions & 2 deletions yeto/dashboard/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
41 changes: 36 additions & 5 deletions yeto/dashboard/fleet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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<m>`` 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
Expand All @@ -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)."""
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Expand All @@ -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]
Expand All @@ -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)

Expand Down
Loading
Loading