From cb50f075c7c2e6717e25029d4be0a2c0f49afb2f Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 15:36:55 +0800 Subject: [PATCH 1/4] Add the site image catalog and pick an island's image from it A site that adopts an image for a model records it in a site image catalog (~/.yeto/site-images.yaml, or the inventory's top-level site_images:). Each record names the model, role, engine, digest, CPU and card architectures, versions, smoke evidence and its status. An ssh: trainer island whose --rl-image and inventory name no image, and an ssh sampler pool node on container.image auto without an inventory image, now take the newest verified-smoke record that fits every node, before the built-in default; the launcher and the pool dry-run print the image and where it came from. A configuration that names its image never reads the catalog, so explicit images (every customer config) are unchanged. A broken catalog is refused when it is read. own-cluster-fleet-stability 7.1, 7.4. Co-Authored-By: Claude Opus 5.5 --- tests/test_site_images.py | 361 +++++++++++++++++++++++++++ yeto/launch/node_inventory.py | 12 +- yeto/launch/rl_backend.py | 54 +++- yeto/launch/site_images.py | 419 ++++++++++++++++++++++++++++++++ yeto/launch/ssh_sampler_pool.py | 44 +++- 5 files changed, 871 insertions(+), 19 deletions(-) create mode 100644 tests/test_site_images.py create mode 100644 yeto/launch/site_images.py diff --git a/tests/test_site_images.py b/tests/test_site_images.py new file mode 100644 index 000000000..5668d205d --- /dev/null +++ b/tests/test_site_images.py @@ -0,0 +1,361 @@ +"""The site image catalog (own-cluster-fleet-stability 7.1) and the image selection +order of an ssh: trainer island and an ssh sampler pool (7.4): explicit, then the +site catalog, then the built-in default.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import pytest +import yaml + +from yeto.launch import site_images as si +from yeto.launch import ssh_sampler_pool as sp +from yeto.launch.node_inventory import InventoryError, parse_inventory, parse_node + +D1 = "a" * 64 +D2 = "b" * 64 +D3 = "c" * 64 +REF1 = f"registry.example/site/miles-new@sha256:{D1}" +REF2 = f"registry.example/site/miles-new@sha256:{D2}" +REF3 = f"registry.example/site/vllm-new@sha256:{D3}" +K31_SPEC = Path(__file__).resolve().parents[1] / "examples" / "k31" / "sampler-spec.nc-mi355x-vllm.json" + + +def record(**kw): + raw = {"model": "moonshotai/Kimi-K3.1-Pro", "role": "trainer", "engine": "miles", "ref": REF1, + "device_family": "cuda", "cpu_arch": "x86_64", "card_archs": ["sm103"], + "versions": {"python": "3.12.3", "torch": "2.9.0", "cuda": "13.0"}, + "evidence": {"at": "2026-11-26T10:00:00Z", "node": "b300-0", "seconds": 812.4, "result": "pass"}, + "status": "verified-smoke", **kw} + return {k: v for k, v in raw.items() if v is not None} + + +def write_catalog(path: Path, *records) -> Path: + path.write_text(yaml.safe_dump({"version": 1, "images": list(records)})) + return path + + +def b300(name="b300-0", **kw): + raw = {"name": name, "host": name, "device_family": "cuda", "cpu_arch": "x86_64", "card": "B300", + "cards_per_node": 8, "hbm_gib": 288, "host_memory_gib": 2048, **kw} + return parse_node(raw, index=0) + + +@pytest.fixture(autouse=True) +def _home(tmp_path, monkeypatch): + """No developer catalog leaks in: the default path is under a fresh home.""" + monkeypatch.setenv("HOME", str(tmp_path / "home")) + + +# -- schema (7.1) -------------------------------------------------------------------- + + +def test_a_record_round_trips_and_normalizes(): + r = si.parse_record(record(ref="docker:" + REF1, card_archs=["SM103"], cpu_arch="amd64", device_family="nvidia")) + assert (r.ref, r.card_archs, r.cpu_arch, r.device_family, r.model_key) == (REF1, ("sm103",), "x86_64", "cuda", + "kimi_k31") + assert si.parse_record(r.to_doc()) == r + + +@pytest.mark.parametrize("change, message", [ + ({"role": "syncer"}, "role 'syncer' is unknown"), + ({"engine": "deepspeed"}, "trainer engine 'deepspeed' is unknown"), + ({"role": "sampler", "engine": "miles"}, "sampler engine 'miles' is unknown"), + ({"ref": "registry.example/site/miles-new:latest"}, "must be pinned by digest"), + ({"cpu_arch": "riscv64"}, "cpu_arch 'riscv64' is unknown"), + ({"card_archs": []}, "card_archs must be a non-empty list"), + ({"card_archs": "sm103"}, "card_archs must be a non-empty list"), + ({"status": "smoked"}, "status 'smoked' is unknown"), + ({"evidence": {"at": "x", "node": "n"}}, r"needs evidence \['seconds', 'result'\]"), + ({"evidence": {"at": "x", "node": "n", "seconds": 1, "result": "fail"}}, "needs evidence.result pass"), + ({"colour": "red"}, r"unknown key\(s\) \['colour'\]"), + ({"model": None}, r"missing key\(s\) \['model'\]"), + ({"device_family": "quantum"}, "device family 'quantum' is unknown"), +]) +def test_bad_records_are_refused_by_key(change, message): + raw = record(**{k: v for k, v in change.items() if v is not None}) + if change.get("model", 1) is None: + raw.pop("model") + with pytest.raises(si.SiteImagesError, match=message): + si.parse_record(raw, where="images[0]") + + +def test_a_retired_record_needs_no_evidence(): + assert si.parse_record(record(status="retired", evidence=None)).status == "retired" + + +def test_a_missing_catalog_is_empty_and_a_broken_one_names_its_path(tmp_path): + assert si.load(tmp_path / "none.yaml") == [] + bad = tmp_path / "bad.yaml" + bad.write_text("images: [ {model: x\n") + with pytest.raises(si.SiteImagesError, match=f"{bad} is not valid YAML"): + si.load(bad) + bad.write_text(yaml.safe_dump({"version": 1, "images": [record(), record(role="pilot")]})) + with pytest.raises(si.SiteImagesError, match=rf"{bad}: images\[1\]: role 'pilot'"): + si.load(bad) + bad.write_text(yaml.safe_dump({"version": 2, "images": []})) + with pytest.raises(si.SiteImagesError, match="version 2 is not 1"): + si.load(bad) + bad.write_text(yaml.safe_dump(["not", "a", "mapping"])) + with pytest.raises(si.SiteImagesError, match="must be a mapping"): + si.load(bad) + bad.write_text(yaml.safe_dump({"version": 1, "images": [], "extra": 1})) + with pytest.raises(si.SiteImagesError, match=r"unknown top-level key\(s\) \['extra'\]"): + si.load(bad) + + +def test_add_replaces_the_same_image_keeps_the_others_and_never_overwrites_a_broken_catalog(tmp_path): + path = tmp_path / "sub" / "site-images.yaml" + si.add(record(), path) + si.add(record(ref=REF2), path) + si.add(record(evidence={"at": "2026-11-27T00:00:00Z", "node": "b300-1", "seconds": 9, "result": "pass"}), path) + records = si.load(path) + assert [(r.ref, r.evidence["node"]) for r in records] == [(REF2, "b300-0"), (REF1, "b300-1")] + with pytest.raises(si.SiteImagesError): + si.add(record(status="verified-smoke", evidence={}), path) + assert si.load(path) == records # an invalid record writes nothing + path.write_text("images: [") + with pytest.raises(si.SiteImagesError, match="not valid YAML"): + si.add(record(ref=REF3), path) + assert path.read_text() == "images: [" + assert not [p for p in path.parent.iterdir() if p.name.startswith(".")] # no temporary file left + + +# -- matching (7.1) ------------------------------------------------------------------ + + +def test_match_takes_the_newest_verified_record_that_fits_every_node(tmp_path): + older = record(ref=REF1, evidence={"at": "2026-11-20T00:00:00Z", "node": "b300-0", "seconds": 1, + "result": "pass"}) + newer = record(ref=REF2, evidence={"at": "2026-11-26T00:00:00Z", "node": "b300-0", "seconds": 1, + "result": "pass"}) + path = write_catalog(tmp_path / "c.yaml", newer, older, + record(ref=REF3, status="retired", evidence={"at": "2027-01-01T00:00:00Z"}), + record(ref=REF3, model="Qwen/Qwen3-8B"), + record(ref=REF3, card_archs=["sm90"]), + record(ref=REF3, cpu_arch="aarch64"), + record(ref=REF3, role="sampler", engine="vllm")) + assert [r.ref for r in si.match("kimi-k3.1-pro", "trainer", b300(), path=path)] == [REF2, REF1] + assert [r.ref for r in si.match("moonshotai/Kimi-K3.1-Pro", "trainer", [b300(), b300("b300-1")], + path=path)] == [REF2, REF1] + # one node of another card: no record fits the whole island + h200 = b300("h200-0", card="H200", hbm_gib=141) + assert si.match("kimi_k31", "trainer", [b300(), h200], path=path) == [] + assert si.match("kimi_k31", "trainer", b300(), engine="verl", path=path) == [] + assert si.match(None, "trainer", b300(), path=path) == [] + assert [r.ref for r in si.match("kimi_k31", "sampler", b300(), path=path)] == [REF3] + + +def test_records_of_one_date_prefer_the_later_entry(tmp_path): + path = write_catalog(tmp_path / "c.yaml", record(ref=REF1), record(ref=REF2)) + assert [r.ref for r in si.match("kimi_k31", "trainer", b300(), path=path)] == [REF2, REF1] + + +def test_a_record_names_why_it_does_not_fit(): + r = si.parse_record(record(card_archs=["sm90"], cpu_arch="aarch64")) + assert r.problems(b300()) == ["it is a aarch64 image, node b300-0 is x86_64", + "it was smoked on sm90 cards, node b300-0 has sm103"] + + +# -- selection order (7.4) ----------------------------------------------------------- + + +def test_select_order_explicit_then_site_then_default(tmp_path): + path = write_catalog(tmp_path / "c.yaml", record()) + ref, source = si.select("docker:mine@sha256:" + D3, "kimi_k31", "trainer", b300(), path=path, default="d") + assert (ref, source) == ("docker:mine@sha256:" + D3, si.SOURCE_EXPLICIT) + choice = si.select(None, "kimi_k31", "trainer", b300(), path=path, default="d") + assert tuple(choice) == (REF1, si.SOURCE_SITE) + assert choice.line("trainer") == (f"trainer image {REF1} (adopted 2026-11-26T10:00:00Z on b300-0) " + f"(source: site image catalog {path})") + calls = [] + choice = si.select(None, "Qwen/Qwen3-8B", "trainer", b300(), path=path, + default=lambda: calls.append(1) or "builtin") + assert tuple(choice) == ("builtin", si.SOURCE_DEFAULT) and calls == [1] + assert choice.line("trainer") == (f"trainer image builtin (source: built-in default; no verified-smoke " + f"record in {path} for qwen/qwen3-8b trainer on these nodes)") + missing = si.select(None, "kimi_k31", "trainer", b300(), path=tmp_path / "none.yaml", default="d") + assert missing.source == si.SOURCE_DEFAULT and "no catalog at" in missing.why + + +def test_an_explicit_image_never_reads_the_catalog(tmp_path): + bad = tmp_path / "bad.yaml" + bad.write_text("images: [") + assert tuple(si.select("x@sha256:" + D1, "kimi_k31", "trainer", b300(), path=bad)) == \ + ("x@sha256:" + D1, si.SOURCE_EXPLICIT) + with pytest.raises(si.SiteImagesError): + si.select(None, "kimi_k31", "trainer", b300(), path=bad) + + +def test_the_default_path_is_under_home_and_the_inventory_may_move_it(tmp_path): + assert si.default_path() == tmp_path / "home" / ".yeto" / "site-images.yaml" + inv = tmp_path / "cluster" / "inventory.yaml" + inv.parent.mkdir() + inv.write_text(yaml.safe_dump({"site_images": "images.yaml", "nodes": []})) + assert si.inventory_catalog_path(inv) == tmp_path / "cluster" / "images.yaml" + inv.write_text(yaml.safe_dump({"site_images": "~/elsewhere.yaml", "nodes": []})) + assert si.inventory_catalog_path(inv) == tmp_path / "home" / "elsewhere.yaml" + inv.write_text(yaml.safe_dump({"nodes": []})) + assert si.inventory_catalog_path(inv) == si.default_path() + assert si.inventory_catalog_path(None) == si.default_path() + + +def test_the_inventory_accepts_site_images_and_refuses_a_non_path(): + node = {"name": "b300-0", "host": "b300-0", "device_family": "cuda", "cpu_arch": "x86_64", "card": "B300", + "cards_per_node": 8, "hbm_gib": 288, "host_memory_gib": 2048} + assert [n.name for n in parse_inventory({"site_images": "/etc/yeto/images.yaml", "nodes": [node]})] == ["b300-0"] + with pytest.raises(InventoryError, match="site_images: must be a file path"): + parse_inventory({"site_images": ["a"], "nodes": [node]}) + with pytest.raises(InventoryError, match=r"known: \['images', 'node_health', 'nodes', 'site_images'\]"): + parse_inventory({"lease": "x", "nodes": [node]}) + + +# -- the ssh: trainer island (7.4) --------------------------------------------------- + + +def _inventory(tmp_path, *, catalog=None, image=None, nodes=1): + entries = [] + for i in range(nodes): + entry = {"name": f"b300-{i}", "host": f"b300-{i}", "device_family": "cuda", "cpu_arch": "x86_64", + "card": "B300", "cards_per_node": 8, "hbm_gib": 288, "host_memory_gib": 2048, + "runtime": "docker", "docker_args": ["--gpus", "all"]} + if image: + entry["image"] = image + entries.append(entry) + doc = {"nodes": entries} + if catalog: + doc["site_images"] = str(catalog) + path = tmp_path / "inventory.yaml" + path.write_text(yaml.safe_dump(doc)) + return path + + +def _args(inventory, **kw): + base = {"training_mode": "rl", "rl_backend": None, "rl_image": None, "gpu": "ssh:2x8xB300", + "rl_node_inventory": str(inventory), "model": "moonshotai/Kimi-K3.1-Pro", "rl_model_recipe": None, + "tuning": None} + return argparse.Namespace(**{**base, **kw}) + + +def test_an_ssh_trainer_island_without_an_image_takes_the_site_record(tmp_path, capsys): + from yeto.launch.rl_backend import resolve_default_rl_image + + catalog = write_catalog(tmp_path / "c.yaml", record()) + args = _args(_inventory(tmp_path, catalog=catalog, nodes=2)) + resolve_default_rl_image(args) + assert args.rl_image == "docker:" + REF1 + err = capsys.readouterr().err + assert f"[launcher] ssh trainer image {REF1} (adopted 2026-11-26T10:00:00Z on b300-0) (source: site image " \ + f"catalog {catalog})" in err + + +def test_no_site_record_falls_back_to_the_built_in_default_and_says_so(tmp_path, capsys): + from yeto.launch.rl_backend import _builtin_rl_image, resolve_default_rl_image + + catalog = write_catalog(tmp_path / "c.yaml", record(model="Qwen/Qwen3-8B")) + args = _args(_inventory(tmp_path, catalog=catalog)) + resolve_default_rl_image(args) + assert args.rl_image == _builtin_rl_image(_args(tmp_path)) + assert "(source: built-in default; no verified-smoke record in" in capsys.readouterr().err + + +@pytest.mark.parametrize("kw", [ + {"rl_image": "docker:ghcr.io/x/explicit@sha256:" + D3}, # --rl-image (the customer's configs) + {"gpu": "modal:1x8xB300"}, # not an ssh: island + {"rl_node_inventory": None}, +]) +def test_an_explicit_image_or_another_island_is_unchanged_and_reads_no_catalog(tmp_path, capsys, kw): + from yeto.launch.rl_backend import _builtin_rl_image, resolve_default_rl_image + + bad = tmp_path / "bad.yaml" + bad.write_text("images: [") # would refuse the launch if it were read + args = _args(_inventory(tmp_path, catalog=bad), **kw) + expect = kw.get("rl_image") or _builtin_rl_image(args) + resolve_default_rl_image(args) + assert args.rl_image == expect + assert capsys.readouterr().err == "" + + +def test_an_inventory_image_is_explicit(tmp_path, capsys): + from yeto.launch.rl_backend import _builtin_rl_image, resolve_default_rl_image + + bad = tmp_path / "bad.yaml" + bad.write_text("images: [") + args = _args(_inventory(tmp_path, catalog=bad, image="ghcr.io/x/inv@sha256:" + D3)) + resolve_default_rl_image(args) + assert args.rl_image == _builtin_rl_image(args) # unchanged: run_image compares the two as before + assert capsys.readouterr().err == "" + + +def test_a_broken_catalog_refuses_an_island_that_reads_it(tmp_path): + from yeto.launch.rl_backend import resolve_default_rl_image + + bad = tmp_path / "bad.yaml" + bad.write_text("images: [") + with pytest.raises(ValueError, match="not valid YAML"): + resolve_default_rl_image(_args(_inventory(tmp_path, catalog=bad))) + + +# -- the ssh sampler pool (7.4) ------------------------------------------------------ + + +def _pool(catalog, *, image="auto", node_image=None): + node = b300(**({"image": node_image} if node_image else {})) + sec = {"kind": "ssh", "nodes": ["b300-0"], "workdir": "/srv/yeto/run0", "runtime": "container", + "container": {"engine": "docker", "image": image}, "store": "/srv/yeto/run0/store"} + conf = sp.parse_config({"provider": sec}, inventory=[node]) + return sp.SshPoolConf(**{**conf.__dict__, "site_images": str(catalog)}) + + +def test_an_auto_pool_node_takes_the_site_sampler_record_and_the_dry_run_names_it(tmp_path, capsys): + spec = json.loads(K31_SPEC.read_text()) + catalog = write_catalog(tmp_path / "c.yaml", record(role="sampler", engine="vllm", ref=REF3)) + conf = _pool(catalog) + assert sp.node_image(conf, conf.nodes[0], spec) == REF3 + assert sp.image_problems(conf, spec) == [] # a site image is the site's + assert f"ssh provider: node b300-0: sampler image {REF3} (adopted" in capsys.readouterr().out + + +def test_an_auto_pool_without_a_site_record_keeps_the_engine_catalog_choice(tmp_path, capsys): + from yeto.rl import sampler_pins as pins + + spec = json.loads(K31_SPEC.read_text()) + restart = dict(spec, engine=dict(spec["engine"], server=dict(spec["engine"]["server"], in_place_reload=False))) + conf = _pool(tmp_path / "none.yaml") + assert sp.node_image(conf, conf.nodes[0], restart) == pins.VLLM_SAMPLER_IMAGE_CUDA.removeprefix("docker:") + assert sp.image_problems(conf, restart) == [] + assert "(source: built-in default; no catalog at" in capsys.readouterr().out + + +def test_a_named_pool_image_reads_no_catalog_and_prints_nothing_new(tmp_path, capsys): + spec = json.loads(K31_SPEC.read_text()) + bad = tmp_path / "bad.yaml" + bad.write_text("images: [") + for conf in (_pool(bad, image="ghcr.io/x/pool@sha256:" + D1), + _pool(bad, node_image="ghcr.io/x/node@sha256:" + D2)): + assert sp.image_problems(conf, spec) == [] + assert sp.node_image(_pool(bad, image="ghcr.io/x/pool@sha256:" + D1), b300(), spec) == "ghcr.io/x/pool@sha256:" + D1 + assert capsys.readouterr().out == "" + problems = sp.image_problems(_pool(bad), spec) + assert len(problems) == 1 and "not valid YAML" in problems[0] + + +def test_the_pool_reads_the_catalog_its_inventory_names(tmp_path, monkeypatch): + monkeypatch.setattr(sp, "load_profiles", lambda _p: [b300()]) + inv = tmp_path / "inventory.yaml" + inv.write_text(yaml.safe_dump({"site_images": "images.yaml", "nodes": []})) + sec = {"kind": "ssh", "inventory": str(inv), "nodes": ["b300-0"], "workdir": "/srv/yeto/run0", + "runtime": "container", "container": {"engine": "docker", "image": "auto"}} + assert sp.parse_config({"provider": sec}).site_images == str(tmp_path / "images.yaml") + + +def test_an_unquoted_yaml_timestamp_reads_as_its_iso_text(tmp_path): + path = tmp_path / "c.yaml" + path.write_text(yaml.safe_dump({"version": 1, "images": [record()]}).replace( + "'2026-11-26T10:00:00Z'", "2026-11-26T10:00:00Z")) + assert "at: 2026-11-26T10:00:00Z" in path.read_text() + (r,) = si.load(path) + assert r.at == "2026-11-26T10:00:00Z" diff --git a/yeto/launch/node_inventory.py b/yeto/launch/node_inventory.py index 8a7043b2c..e2f84ecfe 100644 --- a/yeto/launch/node_inventory.py +++ b/yeto/launch/node_inventory.py @@ -14,7 +14,10 @@ of a file without ``images:`` may have no image: an ``ssh:`` trainer island runs the run's ``--rl-image`` (an inventory image must then name the same one), an SSH sampler pool its ``container.image``. The trainer preflight also compares ``uname -m`` with -``cpu_arch``. +``cpu_arch``. The top-level ``site_images:`` names the site image catalog +(:mod:`yeto.launch.site_images`, default ``~/.yeto/site-images.yaml``; a relative path +is taken from the inventory's directory): an island or pool of these nodes that names +no image takes the catalog's verified image for its model there. Example:: @@ -481,14 +484,17 @@ def parse_inventory(document: Any) -> NodeList: if isinstance(document, list): entries = document elif isinstance(document, dict): - unknown = sorted(set(document) - {"nodes", "images", "node_health", "lease_store"}) + unknown = sorted(set(document) - {"nodes", "images", "node_health", "lease_store", "site_images"}) if unknown: raise InventoryError(f"unknown top-level inventory field(s) {unknown} " - f"(known: ['images', 'lease_store', 'node_health', 'nodes'])") + f"(known: ['images', 'lease_store', 'node_health', 'nodes', 'site_images'])") entries = document.get("nodes") images = parse_images(document.get("images")) health = parse_node_health(document.get("node_health"), "inventory") lease_store = parse_lease_store(document.get("lease_store")) + catalog = document.get("site_images") # the site image catalog's path (yeto.launch.site_images) + if catalog is not None and (not isinstance(catalog, str) or not catalog.strip()): + raise InventoryError(f"inventory site_images: must be a file path, not {catalog!r}") else: raise InventoryError(f"the inventory must be a mapping with a nodes list, got " f"{type(document).__name__}") diff --git a/yeto/launch/rl_backend.py b/yeto/launch/rl_backend.py index 923a01da9..9b68e19d6 100644 --- a/yeto/launch/rl_backend.py +++ b/yeto/launch/rl_backend.py @@ -19,14 +19,56 @@ def resolve_default_rl_image(args) -> None: except backends.UnknownBackend as exc: raise ValueError(str(exc)) from None if getattr(args, "rl_image", None) is None: - flags = _rl_backend_module(args, "launch_flags") - if getattr(flags, "DEFAULT_RL_IMAGE", None): # rl-verl-backend: Modal-built engine image - args.rl_image = flags.DEFAULT_RL_IMAGE + nodes = _site_catalog_trainer_nodes(args) + if nodes is not None: # an ssh: trainer island whose inventory names no image + import sys + + from . import site_images + + try: + choice = site_images.select( + None, getattr(args, "model", None), "trainer", nodes, + engine=getattr(args, "rl_backend", None) or backends.DEFAULT_BACKEND, + path=site_images.inventory_catalog_path(getattr(args, "rl_node_inventory", None)), + default=lambda: _builtin_rl_image(args)) + except site_images.SiteImagesError as exc: + raise ValueError(str(exc)) from None + args.rl_image = f"docker:{choice.ref}" if choice.source == site_images.SOURCE_SITE else choice.ref + print(f"[launcher] {choice.line('ssh trainer')}", file=sys.stderr, flush=True) return - from ..rl import default_rl_image + args.rl_image = _builtin_rl_image(args) - args.rl_image = default_rl_image(recipe=getattr(args, "rl_model_recipe", None), - tuning=getattr(args, "tuning", None)) + +def _builtin_rl_image(args) -> str: + """The engine's pinned default ``--rl-image``.""" + flags = _rl_backend_module(args, "launch_flags") + if getattr(flags, "DEFAULT_RL_IMAGE", None): # rl-verl-backend: Modal-built engine image + return flags.DEFAULT_RL_IMAGE + from ..rl import default_rl_image + + return default_rl_image(recipe=getattr(args, "rl_model_recipe", None), tuning=getattr(args, "tuning", None)) + + +def _site_catalog_trainer_nodes(args) -> list | None: + """The trainer nodes of an ``ssh:`` island of ``--gpu`` whose ``--rl-node-inventory`` + names no image for them (the site image catalog may then give one, + :mod:`yeto.launch.site_images`); None for any other launch (no ssh: island, no + inventory, an inventory image: the configuration names its image).""" + path = getattr(args, "rl_node_inventory", None) + if not path or not getattr(args, "gpu", None): + return None + from ..gpu_spec import parse_gpu_spec + from .node_inventory import InventoryError, island_nodes, load_inventory + + try: + if not any(spec.cloud == "ssh" for spec in parse_gpu_spec(args.gpu)): + return None + nodes = island_nodes(load_inventory(path), "trainer") + except (ValueError, InventoryError): # the launch's own checks name a bad --gpu or inventory + return None + if not nodes or any(n.image for n in nodes): + return None + return nodes def _rl_callable(value: str | None, flag: str, *, required: bool) -> None: diff --git a/yeto/launch/site_images.py b/yeto/launch/site_images.py new file mode 100644 index 000000000..fb70f6a53 --- /dev/null +++ b/yeto/launch/site_images.py @@ -0,0 +1,419 @@ +"""The site image catalog: images a site adopted for a model, with their smoke evidence. + +``yeto image adopt`` (:mod:`.image_adopt`) checks an image built for one model +(manifest, capabilities, fit to the nodes, pre-pull, a smoke run) and records it +here. A trainer island or a sampler pool that names no image then takes the newest +verified record that matches its model and its nodes, before the built-in default. + +The catalog is one YAML file, ``~/.yeto/site-images.yaml`` unless an SSH node +inventory names another with its top-level ``site_images:`` key:: + + version: 1 + images: + - model: moonshotai/Kimi-K3.1-Pro # any spelling engine_images.model_key knows + role: trainer # trainer | sampler + engine: miles # trainer: the --rl-backend; sampler: vllm | sglang | vllm-ascend + ref: ghcr.io/OWNER/IMAGE@sha256:<64 hex> + device_family: cuda # optional; checked when given + cpu_arch: x86_64 + card_archs: [sm103] # the card architectures the smoke ran on + versions: {python: 3.12.3, torch: 2.9.0, cuda: "13.0"} + evidence: {at: "2026-11-26T10:00:00Z", node: b300-0, seconds: 812.4, result: pass} + status: verified-smoke # verified-smoke | retired + +A record matches (model, role, node profile) when its model key, role and status +``verified-smoke`` agree and every node of the island or pool has the record's CPU +architecture, one of its card architectures and (when the record names one) its +device family. Several matches: the newest ``evidence.at`` wins, then the later +record in the file. + +The selection order (:func:`select`): an image the configuration names (``--rl-image``, +an inventory image, a pool's ``container.image``) as it is, without reading the +catalog; else the catalog's match; else the built-in default. A broken catalog is +refused (:class:`SiteImagesError`) only when it is read, never for a configuration +that names its image. +""" + +from __future__ import annotations + +import os +import re +import tempfile +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from . import engine_images + +DEFAULT_PATH = "~/.yeto/site-images.yaml" +INVENTORY_KEY = "site_images" +VERSION = 1 +VERIFIED = "verified-smoke" +RETIRED = "retired" +STATUSES = (VERIFIED, RETIRED) +ROLES = engine_images.ROLES +TRAINER_ENGINES = tuple(sorted({r.engine for r in engine_images.DEFAULT_IMAGES if r.role == "trainer"})) +SAMPLER_ENGINES = engine_images.ENGINES +SOURCE_EXPLICIT = "explicit" +SOURCE_SITE = "site image catalog" +SOURCE_DEFAULT = "built-in default" +_REQUIRED = ("model", "role", "engine", "ref", "cpu_arch", "card_archs", "status") +_OPTIONAL = ("device_family", "versions", "evidence") +_EVIDENCE_REQUIRED = ("at", "node", "seconds", "result") +_DIGEST_REF = re.compile(r"[^\s@]+@sha256:[0-9a-f]{64}") + + +class SiteImagesError(ValueError): + """The site image catalog cannot be read or a record is not valid.""" + + +@dataclass(frozen=True) +class SiteImage: + """One record of the catalog (:data:`_REQUIRED` and :data:`_OPTIONAL` keys).""" + + model: str + role: str + engine: str + ref: str + cpu_arch: str + card_archs: tuple[str, ...] + status: str + device_family: str | None = None + versions: Mapping[str, str] = field(default_factory=dict) + evidence: Mapping[str, Any] = field(default_factory=dict) + + @property + def model_key(self) -> str: + return engine_images.model_key(self.model) + + @property + def at(self) -> str: + return str(self.evidence.get("at") or "") + + def same_image(self, other: SiteImage) -> bool: + """The same (model, role, engine, ref): a newer adoption replaces the older record.""" + return (self.model_key, self.role, self.engine, self.ref) == \ + (other.model_key, other.role, other.engine, other.ref) + + def problems(self, profile: Any) -> list[str]: + """Why this record does not fit the node ``profile`` (empty: it does).""" + facts = profile_facts(profile) + out = [] + if facts["cpu_arch"] != self.cpu_arch: + out.append(f"it is a {self.cpu_arch} image, node {facts['name']} is {facts['cpu_arch']}") + if facts["card_arch"] not in self.card_archs: + out.append(f"it was smoked on {'/'.join(self.card_archs)} cards, node {facts['name']} has " + f"{facts['card_arch'] or 'cards of an unknown architecture'}") + if self.device_family and facts["family"] != self.device_family: + out.append(f"it is a {self.device_family} image, node {facts['name']} is {facts['family']}") + return out + + def to_doc(self) -> dict[str, Any]: + doc: dict[str, Any] = {"model": self.model, "role": self.role, "engine": self.engine, "ref": self.ref} + if self.device_family: + doc["device_family"] = self.device_family + doc.update({"cpu_arch": self.cpu_arch, "card_archs": list(self.card_archs)}) + if self.versions: + doc["versions"] = dict(self.versions) + if self.evidence: + doc["evidence"] = dict(self.evidence) + doc["status"] = self.status + return doc + + def describe(self) -> str: + """`` (adopted on )`` for a dry-run line.""" + how = " ".join(x for x in (f"adopted {self.at}" if self.at else "", + f"on {self.evidence['node']}" if self.evidence.get("node") else "") if x) + return f"{self.ref}" + (f" ({how})" if how else "") + + +@dataclass(frozen=True) +class Choice: + """What :func:`select` chose: the reference (None: no image at all), where it came + from (:data:`SOURCE_EXPLICIT` / :data:`SOURCE_SITE` / :data:`SOURCE_DEFAULT`), the + catalog record (site only), the catalog path read (None: not read) and why the + catalog gave nothing (default only).""" + + ref: str | None + source: str + record: SiteImage | None = None + path: Path | None = None + why: str = "" + + def line(self, what: str) -> str: + """A dry-run line: `` image (source: ...)``.""" + if self.source == SOURCE_SITE: + assert self.record is not None + return f"{what} image {self.record.describe()} (source: {SOURCE_SITE} {self.path})" + ref = self.ref or "(none)" + if self.source == SOURCE_DEFAULT: + return f"{what} image {ref} (source: {SOURCE_DEFAULT}; {self.why})" + return f"{what} image {ref} (source: {self.source})" + + def __iter__(self): # (ref, source), the contract's shape + return iter((self.ref, self.source)) + + +# --- paths ------------------------------------------------------------------------- + + +def default_path() -> Path: + return Path(os.path.expanduser(DEFAULT_PATH)) + + +def catalog_path(value: str | os.PathLike[str] | None = None, *, base: Path | None = None) -> Path: + """The catalog file: ``value`` (``~`` expanded; a relative path is taken from ``base``, + the inventory's directory), else :data:`DEFAULT_PATH`.""" + if value is None or not str(value).strip(): + return default_path() + path = Path(os.path.expanduser(str(value))) + if not path.is_absolute() and base is not None: + path = Path(base) / path + return path + + +def inventory_value(document: Any) -> str | None: + """The inventory document's ``site_images:`` (None: not given). Refuses a non-string.""" + if not isinstance(document, Mapping) or document.get(INVENTORY_KEY) is None: + return None + value = document[INVENTORY_KEY] + if not isinstance(value, str) or not value.strip(): + raise SiteImagesError(f"inventory {INVENTORY_KEY}: must be a file path, not {value!r}") + return value + + +def inventory_catalog_path(inventory: str | os.PathLike[str] | None) -> Path: + """The catalog of the SSH node inventory file ``inventory`` (its ``site_images:``, + relative to the file's directory), else the default. An unreadable inventory reads as + the default here: the inventory's own loader reports it.""" + if not inventory: + return default_path() + import yaml # noqa: PLC0415 + + file = Path(os.path.expanduser(str(inventory))) + try: + document = yaml.safe_load(file.read_text()) + except (OSError, yaml.YAMLError): + return default_path() + return catalog_path(inventory_value(document), base=file.parent) + + +# --- schema ------------------------------------------------------------------------ + + +def _text(raw: Mapping[str, Any], key: str, where: str) -> str: + value = raw.get(key) + if not isinstance(value, str) or not value.strip(): + raise SiteImagesError(f"{where}: {key} must be a non-empty string, not {value!r}") + return value.strip() + + +def parse_record(raw: Any, *, where: str = "record") -> SiteImage: + """One catalog record, validated (:class:`SiteImagesError` names the key).""" + if not isinstance(raw, Mapping): + raise SiteImagesError(f"{where}: must be a mapping, not {type(raw).__name__}") + unknown = sorted(set(raw) - set(_REQUIRED) - set(_OPTIONAL)) + if unknown: + raise SiteImagesError(f"{where}: unknown key(s) {unknown} (known: {sorted(_REQUIRED + _OPTIONAL)})") + missing = [k for k in _REQUIRED if k not in raw] + if missing: + raise SiteImagesError(f"{where}: missing key(s) {missing}") + model = _text(raw, "model", where) + role = _text(raw, "role", where) + if role not in ROLES: + raise SiteImagesError(f"{where}: role {role!r} is unknown (known: {list(ROLES)})") + engine = _text(raw, "engine", where).lower() + engines = TRAINER_ENGINES if role == "trainer" else SAMPLER_ENGINES + if engine not in engines: + raise SiteImagesError(f"{where}: {role} engine {engine!r} is unknown (known: {list(engines)})") + ref = _text(raw, "ref", where).removeprefix("docker:") + if not _DIGEST_REF.fullmatch(ref): + raise SiteImagesError(f"{where}: ref {ref!r} must be pinned by digest (REGISTRY/IMAGE@sha256:<64 hex>)") + try: + cpu_arch = engine_images.canonical_cpu_arch(_text(raw, "cpu_arch", where)) + except engine_images.UnknownCpuArch as error: + raise SiteImagesError(f"{where}: {error}") from None + archs = raw.get("card_archs") + if isinstance(archs, str) or not isinstance(archs, (list, tuple)) or not archs \ + or not all(isinstance(a, str) and a.strip() for a in archs): + raise SiteImagesError(f"{where}: card_archs must be a non-empty list of card architectures " + f"(sm103, gfx950, ascend910b ...), not {archs!r}") + family = raw.get("device_family") + if family is not None: + try: + family = engine_images.canonical_device_family(str(family)) + except ValueError as error: + raise SiteImagesError(f"{where}: {error}") from None + status = _text(raw, "status", where) + if status not in STATUSES: + raise SiteImagesError(f"{where}: status {status!r} is unknown (known: {list(STATUSES)})") + versions = raw.get("versions") or {} + if not isinstance(versions, Mapping): + raise SiteImagesError(f"{where}: versions must be a mapping, not {type(versions).__name__}") + evidence = raw.get("evidence") or {} + if not isinstance(evidence, Mapping): + raise SiteImagesError(f"{where}: evidence must be a mapping, not {type(evidence).__name__}") + if status == VERIFIED: + lacking = [k for k in _EVIDENCE_REQUIRED if evidence.get(k) in (None, "")] + if lacking: + raise SiteImagesError(f"{where}: a {VERIFIED} record needs evidence {lacking}") + if str(evidence.get("result")) != "pass": + raise SiteImagesError(f"{where}: a {VERIFIED} record needs evidence.result pass, " + f"not {evidence.get('result')!r}") + evidence = {str(k): _plain(v) for k, v in evidence.items()} + return SiteImage(model=model, role=role, engine=engine, ref=ref, cpu_arch=cpu_arch, + card_archs=tuple(a.strip().lower() for a in archs), status=status, device_family=family, + versions={str(k): str(v) for k, v in versions.items()}, + evidence=evidence) + + +def _plain(value: Any) -> Any: + """A YAML timestamp (``at: 2026-11-26T10:00:00Z`` unquoted) as its ISO text, so records + order by ``evidence.at`` and write back as they were read.""" + import datetime # noqa: PLC0415 + + if isinstance(value, datetime.datetime): + if value.tzinfo is not None and value.utcoffset() == datetime.timedelta(0): + return value.replace(tzinfo=None).isoformat() + "Z" + return value.isoformat() + if isinstance(value, datetime.date): + return value.isoformat() + return value + + +def parse_catalog(document: Any, *, where: str = "site image catalog") -> list[SiteImage]: + if document is None: + return [] + if not isinstance(document, Mapping): + raise SiteImagesError(f"{where}: must be a mapping with version and images, not {type(document).__name__}") + unknown = sorted(set(document) - {"version", "images"}) + if unknown: + raise SiteImagesError(f"{where}: unknown top-level key(s) {unknown} (known: ['images', 'version'])") + if document.get("version", VERSION) != VERSION: + raise SiteImagesError(f"{where}: version {document.get('version')!r} is not {VERSION}") + images = document.get("images") or [] + if not isinstance(images, list): + raise SiteImagesError(f"{where}: images must be a list, not {type(images).__name__}") + return [parse_record(raw, where=f"{where}: images[{i}]") for i, raw in enumerate(images)] + + +def load(path: str | os.PathLike[str] | None = None) -> list[SiteImage]: + """Every record of the catalog at ``path`` (default :data:`DEFAULT_PATH`); a missing + file is an empty catalog, a broken one :class:`SiteImagesError`.""" + import yaml # noqa: PLC0415 + + file = catalog_path(path) + try: + text = file.read_text() + except FileNotFoundError: + return [] + except OSError as error: + raise SiteImagesError(f"cannot read the site image catalog {file}: {error}") from None + try: + document = yaml.safe_load(text) + except yaml.YAMLError as error: + raise SiteImagesError(f"the site image catalog {file} is not valid YAML: {error}") from None + return parse_catalog(document, where=str(file)) + + +def save(records: Sequence[SiteImage], path: str | os.PathLike[str] | None = None) -> Path: + """Write ``records`` to the catalog (a temporary file renamed over it).""" + import yaml # noqa: PLC0415 + + file = catalog_path(path) + file.parent.mkdir(parents=True, exist_ok=True) + body = yaml.safe_dump({"version": VERSION, "images": [r.to_doc() for r in records]}, sort_keys=False) + fd, tmp = tempfile.mkstemp(prefix=f".{file.name}.", dir=str(file.parent)) + try: + with os.fdopen(fd, "w") as handle: + handle.write(body) + os.replace(tmp, file) + except BaseException: + Path(tmp).unlink(missing_ok=True) + raise + return file + + +def add(record: SiteImage | Mapping[str, Any], path: str | os.PathLike[str] | None = None) -> Path: + """Add ``record`` (validated) to the catalog; it replaces a record of the same image + (:meth:`SiteImage.same_image`). A broken catalog is refused, never overwritten.""" + new = record if isinstance(record, SiteImage) else parse_record(record) + parse_record(new.to_doc()) # the record as it will be read back + records = [r for r in load(path) if not r.same_image(new)] + return save([*records, new], path) + + +# --- matching ---------------------------------------------------------------------- + + +def profile_facts(profile: Any) -> dict[str, Any]: + """name / unified family / CPU and card architecture of a node profile, a plain + inventory ``Node`` (card architecture from its card) or any object with those fields.""" + from .node_inventory import card_arch_of # noqa: PLC0415 - node_inventory imports engine_images + + family = getattr(profile, "family", None) or getattr(profile, "device_family", None) + card_arch = getattr(profile, "card_arch", None) + if not card_arch and getattr(profile, "card", None): + try: + card_arch = card_arch_of(profile.card) + except Exception: # noqa: BLE001 - an unknown card has no architecture + card_arch = None + return {"name": getattr(profile, "name", "?"), + "family": engine_images.canonical_device_family(family) if family else None, + "cpu_arch": engine_images.canonical_cpu_arch(profile.cpu_arch), + "card_arch": str(card_arch).lower() if card_arch else None} + + +def _profiles(profile: Any) -> list[Any]: + if isinstance(profile, (list, tuple)): + return list(profile) + return [profile] + + +def match(model: str | None, role: str, profile: Any, *, engine: str | None = None, + records: Iterable[SiteImage] | None = None, path: str | os.PathLike[str] | None = None) -> list[SiteImage]: + """The verified records for ``model`` in ``role`` that fit every node of ``profile`` + (one profile or a list: an island's or a pool's nodes), best first: the newest + ``evidence.at``, then the later record in the file. ``engine``: only that engine's + records. No model: nothing matches.""" + if role not in ROLES: + raise ValueError(f"role {role!r} is unknown (known: {list(ROLES)})") + if model is None or not str(model).strip(): + return [] + key = engine_images.model_key(model) + nodes = _profiles(profile) + found = [] + for index, record in enumerate(load(path) if records is None else records): + if record.status != VERIFIED or record.role != role or record.model_key != key: + continue + if engine is not None and record.engine != str(engine).lower(): + continue + if nodes and any(record.problems(node) for node in nodes): + continue + found.append((record.at, index, record)) + return [r for _, _, r in sorted(found, key=lambda t: (t[0], t[1]), reverse=True)] + + +def select(explicit: str | None, model: str | None, role: str, profile: Any, *, engine: str | None = None, + path: str | os.PathLike[str] | None = None, + default: str | Callable[[], str | None] | None = None) -> Choice: + """The image of an island or a pool: ``explicit`` as it is (the catalog is not read), + else the catalog's best match (:func:`match`), else ``default`` (a reference or a + function that returns one; None: no default). Unpacks as ``(ref, source)``.""" + if explicit: + return Choice(str(explicit), SOURCE_EXPLICIT) + file = catalog_path(path) + records = load(file) + found = match(model, role, profile, engine=engine, records=records) + if found: + return Choice(found[0].ref, SOURCE_SITE, found[0], file) + if not records: + why = f"no catalog at {file}" if not file.exists() else f"{file} has no record" + elif model is None or not str(model).strip(): + why = "no model to match" + else: + what = f"{engine_images.model_key(model)} {role}" + (f" ({engine})" if engine else "") + why = f"no {VERIFIED} record in {file} for {what} on these nodes" + ref = default() if callable(default) else default + return Choice(ref, SOURCE_DEFAULT, None, file, why) diff --git a/yeto/launch/ssh_sampler_pool.py b/yeto/launch/ssh_sampler_pool.py index a65ba2091..0d1bac98b 100644 --- a/yeto/launch/ssh_sampler_pool.py +++ b/yeto/launch/ssh_sampler_pool.py @@ -233,6 +233,9 @@ class SshPoolConf: node_health: str | None = None # the inventory's top-level lease_store (yeto.launch.node_lease); None: nodes not leased lease_store: str | None = None + # the site image catalog a ``container.image: auto`` node without an inventory image reads + # (the inventory's top-level site_images:, else ~/.yeto/site-images.yaml; yeto.launch.site_images) + site_images: str | None = None def _strs(value: Any, key: str) -> tuple[str, ...]: @@ -258,6 +261,9 @@ def parse_config(cfg: Mapping[str, Any], *, inventory: Sequence[Node] | None = N raise ValueError("ssh provider: inventory (an SSH node inventory file) is required") inventory = load_profiles(os.path.expanduser(str(section["inventory"]))) lease_store = lease_store_of(inventory) + from .site_images import inventory_catalog_path # noqa: PLC0415 + + site_catalog = str(inventory_catalog_path(section.get("inventory"))) inventory = [profile_of(n) for n in inventory] by_name = nodes_by_name(list(inventory)) names = section.get("nodes") @@ -354,7 +360,8 @@ def parse_config(cfg: Mapping[str, Any], *, inventory: Sequence[Node] | None = N min_cards=int(pre["min_cards"]) if pre.get("min_cards") is not None else None, grace_s=int(section.get("grace_s", 120)), price_usd_h=float(price) if price is not None else None, lost_node_hold_s=float(hold), - node_runtime=node_runtime, node_health=health, lease_store=lease_store) + node_runtime=node_runtime, node_health=health, lease_store=lease_store, + site_images=site_catalog) # -- node shell ----------------------------------------------------------------- @@ -1791,16 +1798,29 @@ def spec_of(cfg: Mapping[str, Any]) -> dict[str, Any]: def node_image(conf: SshPoolConf, node: Node, spec: Mapping[str, Any]) -> str: """The image ``node`` runs (container runtime): ``container.image`` unless it is - ``auto``; then the node's inventory image, else the engine image catalog's choice - for what ``spec`` asks (raises ``ImageIncompatible`` when none serves it).""" + ``auto``; then the node's inventory image, else the site image catalog's verified + image for the spec's model on this node, else the engine image catalog's choice for + what ``spec`` asks (raises ``ImageIncompatible`` when none serves it).""" + return str(node_image_choice(conf, node, spec).ref) + + +def node_image_choice(conf: SshPoolConf, node: Node, spec: Mapping[str, Any]): # -> site_images.Choice + """:func:`node_image` with where it came from (``site_images.Choice``): the pool's or + the inventory's image (explicit), the site image catalog, or the engine image catalog + (the built-in default). A broken site catalog raises ``SiteImagesError``.""" + from . import site_images # noqa: PLC0415 + assert conf.container is not None if conf.container.image and conf.container.image != AUTO_IMAGE: - return conf.container.image + return site_images.Choice(conf.container.image, site_images.SOURCE_EXPLICIT) if node.image: - return node.image + return site_images.Choice(node.image, site_images.SOURCE_EXPLICIT) needs = engine_images.spec_needs(spec) - return engine_images.resolve(profile_of(node), needs.pop("model"), needs.pop("engine_pref"), - **needs).image.pull_ref # type: ignore[union-attr] + model, pref = needs.pop("model"), needs.pop("engine_pref") + return site_images.select( + None, model, "sampler", profile_of(node), engine=pref, path=conf.site_images, + default=lambda: engine_images.resolve(profile_of(node), model, pref, + **needs).image.pull_ref) # type: ignore[union-attr] def image_problems(conf: SshPoolConf, spec: Mapping[str, Any]) -> list[str]: @@ -1812,11 +1832,15 @@ def image_problems(conf: SshPoolConf, spec: Mapping[str, Any]) -> list[str]: needs = engine_images.spec_needs(spec) model, pref = needs.pop("model"), needs.pop("engine_pref") out = [] + from .site_images import SOURCE_EXPLICIT, SiteImagesError # noqa: PLC0415 + for node in conf.nodes: try: - image = node_image(conf, node, spec) - engine_images.resolve(profile_of(node), model, pref, image=image, **needs) - except engine_images.ImageIncompatible as error: + choice = node_image_choice(conf, node, spec) + if choice.source != SOURCE_EXPLICIT: # the dry-run names an image the pool chose itself + print(f"ssh provider: node {node.name}: {choice.line('sampler')}") + engine_images.resolve(profile_of(node), model, pref, image=str(choice.ref), **needs) + except (engine_images.ImageIncompatible, SiteImagesError) as error: out.append(f"ssh provider: node {node.name}: {error}") return out From 4eea6d1c5d3332ab9c5c040e9d7b9dd78432547c Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 17:20:24 +0800 Subject: [PATCH 2/4] Lock the site image catalog across processes and flush its writes Two image adopt runs writing one catalog could each read the old file and the later rename would drop the other's record. add() now reads and writes under an flock on a lock file next to the catalog, and save() fsyncs the temporary file and the directory around the rename. Co-Authored-By: Claude Opus 5.5 --- tests/test_site_images.py | 51 ++++++++++++++++++++++++++++++++++++- yeto/launch/site_images.py | 52 ++++++++++++++++++++++++++++++++++---- 2 files changed, 97 insertions(+), 6 deletions(-) diff --git a/tests/test_site_images.py b/tests/test_site_images.py index 5668d205d..d7c97b275 100644 --- a/tests/test_site_images.py +++ b/tests/test_site_images.py @@ -121,7 +121,56 @@ def test_add_replaces_the_same_image_keeps_the_others_and_never_overwrites_a_bro with pytest.raises(si.SiteImagesError, match="not valid YAML"): si.add(record(ref=REF3), path) assert path.read_text() == "images: [" - assert not [p for p in path.parent.iterdir() if p.name.startswith(".")] # no temporary file left + leftovers = [p.name for p in path.parent.iterdir() if p.name.startswith(".")] + assert leftovers == [si.lock_path(path).name] # no temporary file left, only the lock + + +def _add_one(path: str, index: int) -> None: + si.add(record(ref=f"registry.example/site/miles-new@sha256:{index:064x}"), path) + + +def test_concurrent_adds_from_separate_processes_keep_every_record(tmp_path): + import multiprocessing # noqa: PLC0415 + + path = tmp_path / "site-images.yaml" + ctx = multiprocessing.get_context("spawn") + procs = [ctx.Process(target=_add_one, args=(str(path), i)) for i in range(8)] + for proc in procs: + proc.start() + for proc in procs: + proc.join(60) + assert [proc.exitcode for proc in procs] == [0] * 8 + assert sorted(r.ref for r in si.load(path)) == sorted( + f"registry.example/site/miles-new@sha256:{i:064x}" for i in range(8)) + + +def test_an_add_waits_for_the_catalog_lock(tmp_path): + import threading # noqa: PLC0415 + + path = tmp_path / "site-images.yaml" + si.add(record(), path) + done = threading.Event() + + def writer(): + si.add(record(ref=REF2), path) + done.set() + + with si.locked(path) as held: + assert held == path + thread = threading.Thread(target=writer) + thread.start() + assert not done.wait(0.5) # blocked on the lock another holder has + assert [r.ref for r in si.load(path)] == [REF1] + thread.join(10) + assert done.is_set() and [r.ref for r in si.load(path)] == [REF1, REF2] + + +def test_save_flushes_the_file_and_its_directory(tmp_path, monkeypatch): + synced = [] + real = si.os.fsync + monkeypatch.setattr(si.os, "fsync", lambda fd: (synced.append(fd), real(fd))[1]) + si.save([si.parse_record(record())], tmp_path / "site-images.yaml") + assert len(synced) == 2 # the temporary file before the rename, the directory after # -- matching (7.1) ------------------------------------------------------------------ diff --git a/yeto/launch/site_images.py b/yeto/launch/site_images.py index fb70f6a53..0d1e6e426 100644 --- a/yeto/launch/site_images.py +++ b/yeto/launch/site_images.py @@ -36,10 +36,12 @@ from __future__ import annotations +import contextlib +import fcntl import os import re import tempfile -from collections.abc import Callable, Iterable, Mapping, Sequence +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from dataclasses import dataclass, field from pathlib import Path from typing import Any @@ -318,7 +320,8 @@ def load(path: str | os.PathLike[str] | None = None) -> list[SiteImage]: def save(records: Sequence[SiteImage], path: str | os.PathLike[str] | None = None) -> Path: - """Write ``records`` to the catalog (a temporary file renamed over it).""" + """Write ``records`` to the catalog: a temporary file, flushed to disk, renamed over + it, and the directory flushed, so a crash leaves the old catalog or the new one.""" import yaml # noqa: PLC0415 file = catalog_path(path) @@ -328,20 +331,59 @@ def save(records: Sequence[SiteImage], path: str | os.PathLike[str] | None = Non try: with os.fdopen(fd, "w") as handle: handle.write(body) + handle.flush() + os.fsync(handle.fileno()) os.replace(tmp, file) except BaseException: Path(tmp).unlink(missing_ok=True) raise + _fsync_dir(file.parent) return file +def _fsync_dir(directory: Path) -> None: + try: + fd = os.open(str(directory), os.O_RDONLY) + except OSError: + return + try: + os.fsync(fd) + except OSError: # a directory some filesystems cannot flush + pass + finally: + os.close(fd) + + +def lock_path(path: str | os.PathLike[str] | None = None) -> Path: + """The lock file next to the catalog (``..lock``).""" + file = catalog_path(path) + return file.parent / f".{file.name}.lock" + + +@contextlib.contextmanager +def locked(path: str | os.PathLike[str] | None = None) -> Iterator[Path]: + """Hold the catalog's exclusive lock (``flock`` on :func:`lock_path`): two + ``yeto image adopt`` runs writing the same catalog take turns, so neither loses the + other's record.""" + lock = lock_path(path) + lock.parent.mkdir(parents=True, exist_ok=True) + with open(lock, "a") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + try: + yield catalog_path(path) + finally: + fcntl.flock(handle, fcntl.LOCK_UN) + + def add(record: SiteImage | Mapping[str, Any], path: str | os.PathLike[str] | None = None) -> Path: """Add ``record`` (validated) to the catalog; it replaces a record of the same image - (:meth:`SiteImage.same_image`). A broken catalog is refused, never overwritten.""" + (:meth:`SiteImage.same_image`). The read and the write happen under the catalog's + lock (:func:`locked`). A broken catalog is refused, never overwritten.""" new = record if isinstance(record, SiteImage) else parse_record(record) parse_record(new.to_doc()) # the record as it will be read back - records = [r for r in load(path) if not r.same_image(new)] - return save([*records, new], path) + with locked(path): + records = [r for r in load(path) if not r.same_image(new)] + return save([*records, new], path) # --- matching ---------------------------------------------------------------------- From 3db1e7e54b52dd1d028f88df0ebbd926ca4fbcd3 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 17:32:55 +0800 Subject: [PATCH 3/4] Site image catalog: review fixes for matching, records and the pool - read the catalog for a trainer only when every --gpu entry is ssh:; a mixed fleet takes the built-in default and prints why - a record is one image on one hardware: same_image keys on the CPU and card architectures too - evidence.at must be an ISO-8601 time with a zone; it is read as UTC and records order by the time; a bad one names the catalog and the entry - an ssh sampler pool chooses its images once for all its nodes (a spare starts the same image), keeps them in its state, and the dry-run prints the same choice - YETO_SITE_IMAGES_PATH moves the default catalog; the test home guard points it into the session tree - card_archs are checked against the known architectures; a fallback names the closest records and why they do not fit - ref follows the docker reference grammar; no node matches nothing; the catalog keeps its file mode (a new one is 0644); the model alias is resolved before matching; errors start with "[yeto] site image catalog:" - unknown keys and a newer catalog version are warnings, read as far as they go; the inventory key is checked by node_inventory and reused Co-Authored-By: Claude Opus 5.5 --- tests/test_site_images.py | 183 +++++++++++++++++++++++-- tests/yeto_home_guard.py | 1 + yeto/launch/node_inventory.py | 15 ++- yeto/launch/rl_backend.py | 40 ++++-- yeto/launch/site_images.py | 232 +++++++++++++++++++++++--------- yeto/launch/ssh_sampler_pool.py | 114 ++++++++++++++-- 6 files changed, 486 insertions(+), 99 deletions(-) diff --git a/tests/test_site_images.py b/tests/test_site_images.py index d7c97b275..9b47a247f 100644 --- a/tests/test_site_images.py +++ b/tests/test_site_images.py @@ -48,6 +48,7 @@ def b300(name="b300-0", **kw): def _home(tmp_path, monkeypatch): """No developer catalog leaks in: the default path is under a fresh home.""" monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.delenv(si.PATH_ENV, raising=False) # -- schema (7.1) -------------------------------------------------------------------- @@ -64,14 +65,24 @@ def test_a_record_round_trips_and_normalizes(): ({"role": "syncer"}, "role 'syncer' is unknown"), ({"engine": "deepspeed"}, "trainer engine 'deepspeed' is unknown"), ({"role": "sampler", "engine": "miles"}, "sampler engine 'miles' is unknown"), - ({"ref": "registry.example/site/miles-new:latest"}, "must be pinned by digest"), + ({"ref": "registry.example/site/miles-new:latest"}, "must be a docker reference pinned by digest"), + ({"ref": "Registry/Site/miles@sha256:" + D1}, "must be a docker reference"), # upper-case path + ({"ref": "Registry/site/miles@sha256:" + D1}, "must be a docker reference"), # a dotless first part is path + ({"ref": "registry.example/site/miles new@sha256:" + D1}, "must be a docker reference"), + ({"ref": "registry.example/site/miles@sha256:" + "A" * 64}, "must be a docker reference"), + ({"ref": "registry.example/-bad/miles@sha256:" + D1}, "must be a docker reference"), + ({"card_archs": ["sm999"]}, r"card_archs \['sm999'\] unknown \(known: \["), + ({"evidence": {"at": "2026-11-26T10:00:00", "node": "n", "seconds": 1, "result": "pass"}}, "has no time zone"), + ({"evidence": {"at": "2026-11-26", "node": "n", "seconds": 1, "result": "pass"}}, "is not an ISO-8601 time"), + ({"evidence": {"at": "yesterday", "node": "n", "seconds": 1, "result": "pass"}}, "is not an ISO-8601 time"), + ({"evidence": {"at": "2026-13-40T10:00:00Z", "node": "n", "seconds": 1, "result": "pass"}}, + "is not an ISO-8601 time"), ({"cpu_arch": "riscv64"}, "cpu_arch 'riscv64' is unknown"), ({"card_archs": []}, "card_archs must be a non-empty list"), ({"card_archs": "sm103"}, "card_archs must be a non-empty list"), ({"status": "smoked"}, "status 'smoked' is unknown"), ({"evidence": {"at": "x", "node": "n"}}, r"needs evidence \['seconds', 'result'\]"), ({"evidence": {"at": "x", "node": "n", "seconds": 1, "result": "fail"}}, "needs evidence.result pass"), - ({"colour": "red"}, r"unknown key\(s\) \['colour'\]"), ({"model": None}, r"missing key\(s\) \['model'\]"), ({"device_family": "quantum"}, "device family 'quantum' is unknown"), ]) @@ -83,6 +94,43 @@ def test_bad_records_are_refused_by_key(change, message): si.parse_record(raw, where="images[0]") +def test_an_unknown_key_is_a_warning_and_the_record_is_read(capsys): + r = si.parse_record(record(colour="red"), where="images[0]") + assert r.ref == REF1 + assert "[yeto] site image catalog: WARNING: images[0]: unknown key(s) ['colour'] ignored" in capsys.readouterr().err + + +@pytest.mark.parametrize("ref", [ + REF1, f"localhost:5000/miles@sha256:{D1}", f"miles@sha256:{D1}", f"reg.example:443/a/b_c.d-e:t1.2@sha256:{D1}", + f"ghcr.io/owner/yeto__x@sha256:{D1}", +]) +def test_docker_references_pinned_by_digest_are_taken(ref): + assert si.parse_record(record(ref=ref)).ref == ref + assert si.valid_reference(ref) and not si.valid_reference(ref.split("@")[0]) + assert si.valid_reference(ref.split("@")[0], digest=False) + + +def test_evidence_at_is_read_as_utc_and_records_order_by_the_time(tmp_path): + east = si.parse_record(record(evidence={"at": "2026-11-26T18:00:00+08:00", "node": "n", "seconds": 1, + "result": "pass"})) + assert east.at == "2026-11-26T10:00:00Z" and east.at_time.isoformat() == "2026-11-26T10:00:00+00:00" + # 09:30 UTC is earlier than 10:00Z although its text sorts later + later_text = record(ref=REF2, evidence={"at": "2026-11-26T11:30:00+02:00", "node": "n", "seconds": 1, + "result": "pass"}) + path = write_catalog(tmp_path / "c.yaml", record(ref=REF1), later_text) + assert [r.ref for r in si.match("kimi_k31", "trainer", b300(), path=path)] == [REF1, REF2] + # half a second later is newer, although "10:00:00.500000Z" sorts before "10:00:00Z" as text + half = record(ref=REF2, evidence={"at": "2026-11-26T10:00:00.5Z", "node": "n", "seconds": 1, "result": "pass"}) + path = write_catalog(tmp_path / "c2.yaml", half, record(ref=REF1)) + assert si.load(path)[0].at == "2026-11-26T10:00:00.500000Z" + assert [r.ref for r in si.match("kimi_k31", "trainer", b300(), path=path)] == [REF2, REF1] + bad = write_catalog(tmp_path / "bad.yaml", record(), record(evidence={"at": "2026-11-26T10:00:00", "node": "n", + "seconds": 1, "result": "pass"})) + with pytest.raises(si.SiteImagesError, match=rf"^\[yeto\] site image catalog: {bad}: images\[1\]: evidence.at " + r"'2026-11-26T10:00:00' has no time zone"): + si.load(bad) + + def test_a_retired_record_needs_no_evidence(): assert si.parse_record(record(status="retired", evidence=None)).status == "retired" @@ -91,20 +139,58 @@ def test_a_missing_catalog_is_empty_and_a_broken_one_names_its_path(tmp_path): assert si.load(tmp_path / "none.yaml") == [] bad = tmp_path / "bad.yaml" bad.write_text("images: [ {model: x\n") - with pytest.raises(si.SiteImagesError, match=f"{bad} is not valid YAML"): + with pytest.raises(si.SiteImagesError, match=rf"^\[yeto\] site image catalog: {bad} is not valid YAML"): si.load(bad) bad.write_text(yaml.safe_dump({"version": 1, "images": [record(), record(role="pilot")]})) - with pytest.raises(si.SiteImagesError, match=rf"{bad}: images\[1\]: role 'pilot'"): - si.load(bad) - bad.write_text(yaml.safe_dump({"version": 2, "images": []})) - with pytest.raises(si.SiteImagesError, match="version 2 is not 1"): + with pytest.raises(si.SiteImagesError, match=rf"^\[yeto\] site image catalog: {bad}: images\[1\]: role 'pilot'"): si.load(bad) bad.write_text(yaml.safe_dump(["not", "a", "mapping"])) with pytest.raises(si.SiteImagesError, match="must be a mapping"): si.load(bad) - bad.write_text(yaml.safe_dump({"version": 1, "images": [], "extra": 1})) - with pytest.raises(si.SiteImagesError, match=r"unknown top-level key\(s\) \['extra'\]"): - si.load(bad) + for version in (0, "1", True): + bad.write_text(yaml.safe_dump({"version": version, "images": []})) + with pytest.raises(si.SiteImagesError, match="version must be a positive integer"): + si.load(bad) + + +def test_a_newer_catalog_and_unknown_top_level_keys_are_read_with_a_warning(tmp_path, capsys): + path = write_catalog(tmp_path / "c.yaml", record()) + path.write_text(yaml.safe_dump({"version": 2, "images": [record()], "extra": 1})) + assert [r.ref for r in si.load(path)] == [REF1] + err = capsys.readouterr().err + assert f"WARNING: {path}: version 2 is newer than this reader's 1; read as far as it goes" in err + assert f"WARNING: {path}: unknown top-level key(s) ['extra'] ignored" in err + + +def test_one_image_adopted_on_two_kinds_of_card_keeps_two_records(tmp_path): + path = tmp_path / "site-images.yaml" + si.add(record(), path) + si.add(record(card_archs=["sm100"]), path) + si.add(record(cpu_arch="aarch64"), path) + si.add(record(card_archs=["sm100"], evidence={"at": "2026-11-27T00:00:00Z", "node": "b200-0", "seconds": 2, + "result": "pass"}), path) + assert [(r.card_archs, r.cpu_arch, r.evidence["node"]) for r in si.load(path)] == [ + (("sm103",), "x86_64", "b300-0"), (("sm103",), "aarch64", "b300-0"), (("sm100",), "x86_64", "b200-0")] + + +def test_the_catalog_keeps_its_mode_and_a_new_one_is_0644(tmp_path): + import stat + + path = tmp_path / "site-images.yaml" + si.add(record(), path) + assert stat.S_IMODE(path.stat().st_mode) == 0o644 + path.chmod(0o640) + si.add(record(ref=REF2), path) + assert stat.S_IMODE(path.stat().st_mode) == 0o640 + + +def test_the_environment_moves_the_default_catalog(tmp_path, monkeypatch): + monkeypatch.setenv(si.PATH_ENV, str(tmp_path / "elsewhere" / "c.yaml")) + assert si.default_path() == tmp_path / "elsewhere" / "c.yaml" + si.add(record()) + assert [r.ref for r in si.load()] == [REF1] and (tmp_path / "elsewhere" / "c.yaml").exists() + monkeypatch.setenv(si.PATH_ENV, " ") + assert si.default_path() == tmp_path / "home" / ".yeto" / "site-images.yaml" def test_add_replaces_the_same_image_keeps_the_others_and_never_overwrites_a_broken_catalog(tmp_path): @@ -195,7 +281,10 @@ def test_match_takes_the_newest_verified_record_that_fits_every_node(tmp_path): assert si.match("kimi_k31", "trainer", [b300(), h200], path=path) == [] assert si.match("kimi_k31", "trainer", b300(), engine="verl", path=path) == [] assert si.match(None, "trainer", b300(), path=path) == [] + assert si.match("kimi_k31", "trainer", [], path=path) == [] # no node: nothing to fit assert [r.ref for r in si.match("kimi_k31", "sampler", b300(), path=path)] == [REF3] + assert [r.ref for r in si.match("kimi-k31", "trainer", b300(), path=path)] == [REF2, REF1] # an alias + assert [r.ref for r in si.match("qwen3-8b", "trainer", b300(), path=path)] == [REF3] # yeto.models alias def test_records_of_one_date_prefer_the_later_entry(tmp_path): @@ -230,6 +319,19 @@ def test_select_order_explicit_then_site_then_default(tmp_path): assert missing.source == si.SOURCE_DEFAULT and "no catalog at" in missing.why +def test_a_fallback_names_the_closest_records_and_why_they_do_not_fit(tmp_path): + path = write_catalog(tmp_path / "c.yaml", record(card_archs=["sm90"]), + record(ref=REF2, cpu_arch="aarch64", + evidence={"at": "2026-11-27T00:00:00Z", "node": "g", "seconds": 1, "result": "pass"}), + record(ref=REF3, model="Qwen/Qwen3-8B")) + choice = si.select(None, "kimi_k31", "trainer", b300(), engine="miles", path=path, default="d") + assert choice.source == si.SOURCE_DEFAULT + assert choice.why.endswith(f"(closest: {REF2}: it is a aarch64 image, node b300-0 is x86_64 | {REF1}: it was " + "smoked on sm90 cards, node b300-0 has sm103)") + other = si.select(None, "kimi_k31", "trainer", b300(), engine="verl", path=path, default="d") + assert f"{REF1}: it is a miles image, not verl; it was smoked on sm90" in other.why + + def test_an_explicit_image_never_reads_the_catalog(tmp_path): bad = tmp_path / "bad.yaml" bad.write_text("images: [") @@ -311,6 +413,20 @@ def test_no_site_record_falls_back_to_the_built_in_default_and_says_so(tmp_path, assert "(source: built-in default; no verified-smoke record in" in capsys.readouterr().err +def test_a_mixed_fleet_takes_the_built_in_default_and_says_why(tmp_path, capsys): + from yeto.launch.rl_backend import MIXED_FLEET, _builtin_rl_image, resolve_default_rl_image + + catalog = write_catalog(tmp_path / "c.yaml", record()) # it would match the ssh: nodes + args = _args(_inventory(tmp_path, catalog=catalog), gpu="ssh:2x8xB300,modal:1x8xB300") + resolve_default_rl_image(args) + assert args.rl_image == _builtin_rl_image(args) + assert capsys.readouterr().err == (f"[launcher] trainer image {args.rl_image} (source: built-in default; " + f"{MIXED_FLEET})\n") + both = _args(_inventory(tmp_path, catalog=catalog), gpu="ssh:1x8xB300,ssh:1x8xB300") + resolve_default_rl_image(both) + assert both.rl_image == "docker:" + REF1 # every entry ssh: the catalog is read + + @pytest.mark.parametrize("kw", [ {"rl_image": "docker:ghcr.io/x/explicit@sha256:" + D3}, # --rl-image (the customer's configs) {"gpu": "modal:1x8xB300"}, # not an ssh: island @@ -392,6 +508,53 @@ def test_a_named_pool_image_reads_no_catalog_and_prints_nothing_new(tmp_path, ca assert len(problems) == 1 and "not valid YAML" in problems[0] +def test_the_pool_matches_the_site_record_against_all_its_nodes(tmp_path, capsys): + spec = json.loads(K31_SPEC.read_text()) + spec = dict(spec, engine=dict(spec["engine"], server=dict(spec["engine"]["server"], in_place_reload=False))) + catalog = write_catalog(tmp_path / "c.yaml", record(role="sampler", engine="vllm", ref=REF3)) + nodes = [b300(), b300("h200-0", card="H200", hbm_gib=141)] + sec = {"kind": "ssh", "nodes": ["b300-0", "h200-0"], "workdir": "/srv/yeto/run0", "runtime": "container", + "container": {"engine": "docker", "image": "auto"}, "store": "/srv/yeto/run0/store"} + conf = sp.SshPoolConf(**{**sp.parse_config({"provider": sec}, inventory=nodes).__dict__, + "site_images": str(catalog)}) + choices = sp.pool_image_choices(conf, spec) + # the record fits b300-0 only: a spare of the other card would start another image, so none takes it + assert choices["b300-0"].source == si.SOURCE_DEFAULT + assert sp.node_image_choice(conf, nodes[0], spec).source == si.SOURCE_DEFAULT + alone = sp.SshPoolConf(**{**conf.__dict__, "nodes": (nodes[0],)}) + assert sp.node_image(alone, nodes[0], spec) == REF3 + + +def test_the_pool_fixes_its_images_at_the_first_start_and_keeps_them(tmp_path, monkeypatch): + spec = json.loads(K31_SPEC.read_text()) + catalog = write_catalog(tmp_path / "c.yaml", record(role="sampler", engine="vllm", ref=REF3)) + conf = _pool(catalog) + monkeypatch.setattr(sp, "spec_of", lambda cfg: spec) + + def ops(): + o = sp.SshSamplerPoolOps.__new__(sp.SshSamplerPoolOps) + o.cfg, o.conf, o.run_id, o.state_dir, o._images = {}, conf, "run1", tmp_path / "state", None + return o + + first = ops() + assert first.image_for(conf.nodes[0]) == REF3 + newer = record(role="sampler", engine="vllm", ref=f"registry.example/site/vllm-newer@sha256:{D1}", + evidence={"at": "2027-01-01T00:00:00Z", "node": "b300-0", "seconds": 1, "result": "pass"}) + write_catalog(catalog, record(role="sampler", engine="vllm", ref=REF3), newer) + assert first.image_for(conf.nodes[0]) == REF3 # not read again in the run + kept = json.loads(first.images_path().read_text()) + assert kept["images"] == {"b300-0": {"ref": REF3, "source": si.SOURCE_SITE}} + logs = [] + monkeypatch.setattr(sp, "_log", logs.append) + assert ops().image_for(conf.nodes[0]) == REF3 # a restarted controller starts the same image + assert logs == [f"ssh pool: node b300-0: sampler image {REF3} (source: site image catalog; kept from the " + "pool's start (ssh-pool-run1-images.json))"] + first.images_path().unlink() + assert ops().image_for(conf.nodes[0]) == newer["ref"] # a new pool takes the newest record + first.images_path().unlink() + assert first.image_for(conf.nodes[0]) == REF3 # chosen once per pool process, whatever the state file says + + def test_the_pool_reads_the_catalog_its_inventory_names(tmp_path, monkeypatch): monkeypatch.setattr(sp, "load_profiles", lambda _p: [b300()]) inv = tmp_path / "inventory.yaml" diff --git a/tests/yeto_home_guard.py b/tests/yeto_home_guard.py index bbcd9fac8..c4c3f61a2 100644 --- a/tests/yeto_home_guard.py +++ b/tests/yeto_home_guard.py @@ -42,6 +42,7 @@ "YETO_ISLANDS_LOG_DIR": "islands", # yeto.rl.trainer_worker.LocalLaunchOps launch logs "YETO_SSH_RUNS_DIR": "ssh-runs", # yeto.rl.ssh_harness.prepare plans "YETO_VERDA_IDS_PATH": "verda-instance-ids.json", # yeto.sky_patches.verda + "YETO_SITE_IMAGES_PATH": "site-images.yaml", # yeto.launch.site_images.default_path } # Points into one real run's ledger when inherited from an operator shell. CLEARED_ENV = ("YETO_RESOURCE_LEDGER",) diff --git a/yeto/launch/node_inventory.py b/yeto/launch/node_inventory.py index e2f84ecfe..175bcd0a3 100644 --- a/yeto/launch/node_inventory.py +++ b/yeto/launch/node_inventory.py @@ -475,6 +475,17 @@ def parse_node(raw: Any, *, index: int, images: Mapping[str, str] | None = None, return node +def site_images_value(document: Any) -> str | None: + """The inventory document's top-level ``site_images:``, the site image catalog's path + (:mod:`yeto.launch.site_images`; None: not given). Refuses a value that is not a path.""" + if not isinstance(document, Mapping) or document.get("site_images") is None: + return None + value = document["site_images"] + if not isinstance(value, str) or not value.strip(): + raise InventoryError(f"inventory site_images: must be a file path, not {value!r}") + return value + + def parse_inventory(document: Any) -> NodeList: """The ``nodes:`` list of a loaded inventory document (a :class:`NodeList`: with the top-level ``lease_store``).""" @@ -492,9 +503,7 @@ def parse_inventory(document: Any) -> NodeList: images = parse_images(document.get("images")) health = parse_node_health(document.get("node_health"), "inventory") lease_store = parse_lease_store(document.get("lease_store")) - catalog = document.get("site_images") # the site image catalog's path (yeto.launch.site_images) - if catalog is not None and (not isinstance(catalog, str) or not catalog.strip()): - raise InventoryError(f"inventory site_images: must be a file path, not {catalog!r}") + site_images_value(document) else: raise InventoryError(f"the inventory must be a mapping with a nodes list, got " f"{type(document).__name__}") diff --git a/yeto/launch/rl_backend.py b/yeto/launch/rl_backend.py index 9b68e19d6..b6d756ccb 100644 --- a/yeto/launch/rl_backend.py +++ b/yeto/launch/rl_backend.py @@ -19,10 +19,10 @@ def resolve_default_rl_image(args) -> None: except backends.UnknownBackend as exc: raise ValueError(str(exc)) from None if getattr(args, "rl_image", None) is None: - nodes = _site_catalog_trainer_nodes(args) - if nodes is not None: # an ssh: trainer island whose inventory names no image - import sys + import sys + nodes, why = _site_catalog_trainer_nodes(args) + if nodes is not None: # an all-ssh: trainer fleet whose inventory names no image from . import site_images try: @@ -37,6 +37,9 @@ def resolve_default_rl_image(args) -> None: print(f"[launcher] {choice.line('ssh trainer')}", file=sys.stderr, flush=True) return args.rl_image = _builtin_rl_image(args) + if why: + print(f"[launcher] trainer image {args.rl_image} (source: built-in default; {why})", file=sys.stderr, + flush=True) def _builtin_rl_image(args) -> str: @@ -49,26 +52,35 @@ def _builtin_rl_image(args) -> str: return default_rl_image(recipe=getattr(args, "rl_model_recipe", None), tuning=getattr(args, "tuning", None)) -def _site_catalog_trainer_nodes(args) -> list | None: - """The trainer nodes of an ``ssh:`` island of ``--gpu`` whose ``--rl-node-inventory`` - names no image for them (the site image catalog may then give one, - :mod:`yeto.launch.site_images`); None for any other launch (no ssh: island, no - inventory, an inventory image: the configuration names its image).""" +MIXED_FLEET = ("the --gpu fleet mixes ssh: and cloud islands: the site image catalog is read only when every " + "--gpu entry is ssh:") + + +def _site_catalog_trainer_nodes(args) -> tuple[list | None, str]: + """``(nodes, why)``: the trainer nodes of a ``--gpu`` whose every entry is an ``ssh:`` + island and whose ``--rl-node-inventory`` names no image for them (the site image + catalog may then give one, :mod:`yeto.launch.site_images`); None for any other launch + (no ssh: island, no inventory, an inventory image: the configuration names its image). + ``why``: the line a mixed fleet (ssh: and cloud islands) prints for its built-in + default (a cloud island's cards do not take part in a site match).""" path = getattr(args, "rl_node_inventory", None) if not path or not getattr(args, "gpu", None): - return None + return None, "" from ..gpu_spec import parse_gpu_spec from .node_inventory import InventoryError, island_nodes, load_inventory try: - if not any(spec.cloud == "ssh" for spec in parse_gpu_spec(args.gpu)): - return None + clouds = [spec.cloud for spec in parse_gpu_spec(args.gpu)] + if "ssh" not in clouds: + return None, "" nodes = island_nodes(load_inventory(path), "trainer") except (ValueError, InventoryError): # the launch's own checks name a bad --gpu or inventory - return None + return None, "" if not nodes or any(n.image for n in nodes): - return None - return nodes + return None, "" + if not all(cloud == "ssh" for cloud in clouds): + return None, MIXED_FLEET + return nodes, "" def _rl_callable(value: str | None, flag: str, *, required: bool) -> None: diff --git a/yeto/launch/site_images.py b/yeto/launch/site_images.py index 0d1e6e426..905bc1742 100644 --- a/yeto/launch/site_images.py +++ b/yeto/launch/site_images.py @@ -5,24 +5,31 @@ here. A trainer island or a sampler pool that names no image then takes the newest verified record that matches its model and its nodes, before the built-in default. -The catalog is one YAML file, ``~/.yeto/site-images.yaml`` unless an SSH node -inventory names another with its top-level ``site_images:`` key:: +The catalog is one YAML file, ``~/.yeto/site-images.yaml`` (``$YETO_SITE_IMAGES_PATH`` +overrides it) unless an SSH node inventory names another with its top-level +``site_images:`` key:: version: 1 images: - model: moonshotai/Kimi-K3.1-Pro # any spelling engine_images.model_key knows role: trainer # trainer | sampler engine: miles # trainer: the --rl-backend; sampler: vllm | sglang | vllm-ascend - ref: ghcr.io/OWNER/IMAGE@sha256:<64 hex> + ref: ghcr.io/OWNER/IMAGE@sha256:<64 hex> # a docker reference pinned by digest device_family: cuda # optional; checked when given cpu_arch: x86_64 - card_archs: [sm103] # the card architectures the smoke ran on + card_archs: [sm103] # the card architectures the smoke ran on (known ones) versions: {python: 3.12.3, torch: 2.9.0, cuda: "13.0"} evidence: {at: "2026-11-26T10:00:00Z", node: b300-0, seconds: 812.4, result: pass} status: verified-smoke # verified-smoke | retired -A record matches (model, role, node profile) when its model key, role and status -``verified-smoke`` agree and every node of the island or pool has the record's CPU +``evidence.at`` is an ISO-8601 time with its time zone (read as UTC). One record per +image and hardware: a record replaces the one of the same model, role, engine, ref, +CPU and card architectures. A key the reader does not know is a warning, not an error, +and so is a catalog ``version`` above this reader's (read as far as it goes). + +A record matches (model, role, node profile) when its model key (the model's alias +resolved first, :func:`yeto.models.resolve`), role and status ``verified-smoke`` +agree and every node of the island or pool (at least one) has the record's CPU architecture, one of its card architectures and (when the record names one) its device family. Several matches: the newest ``evidence.at`` wins, then the later record in the file. @@ -37,18 +44,27 @@ from __future__ import annotations import contextlib +import datetime import fcntl import os import re +import stat +import sys import tempfile from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from dataclasses import dataclass, field from pathlib import Path from typing import Any +import yaml + +from ..models import resolve as resolve_model from . import engine_images +from .node_inventory import CARD_ARCHES, InventoryError, card_arch_of, site_images_value DEFAULT_PATH = "~/.yeto/site-images.yaml" +PATH_ENV = "YETO_SITE_IMAGES_PATH" # overrides DEFAULT_PATH (tests point it into their own tree) +PREFIX = "[yeto] site image catalog:" INVENTORY_KEY = "site_images" VERSION = 1 VERIFIED = "verified-smoke" @@ -63,13 +79,37 @@ _REQUIRED = ("model", "role", "engine", "ref", "cpu_arch", "card_archs", "status") _OPTIONAL = ("device_family", "versions", "evidence") _EVIDENCE_REQUIRED = ("at", "node", "seconds", "result") -_DIGEST_REF = re.compile(r"[^\s@]+@sha256:[0-9a-f]{64}") +# the docker reference grammar (distribution/reference): [domain[:port]/]path[:tag]@sha256:<64 hex> +_DOMAIN = r"(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*(?::[0-9]+)?" +_PATH_PART = r"[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*" +_TAG = r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}" +REFERENCE = re.compile(rf"(?:(?P{_DOMAIN})/)?(?P{_PATH_PART}(?:/{_PATH_PART})*)" + rf"(?::(?P{_TAG}))?(?:@(?Psha256:[0-9a-f]{{64}}))?") +KNOWN_CARD_ARCHS = tuple(sorted({a for a in CARD_ARCHES.values() if a})) class SiteImagesError(ValueError): """The site image catalog cannot be read or a record is not valid.""" +def valid_reference(ref: str, *, digest: bool = True) -> bool: + """``ref`` follows the docker reference grammar (:data:`REFERENCE`; ``digest``: and is + pinned by a sha256 digest). The domain part is only taken as one when it has a dot, + a port or is ``localhost``, as docker reads it.""" + m = REFERENCE.fullmatch(ref or "") + if not m or len(ref) > 512 or (digest and not m.group("digest")): + return False + domain = m.group("domain") + if domain and not ("." in domain or ":" in domain or domain == "localhost"): + # docker reads a dotless first component as part of the path: it must be lower case + return re.fullmatch(_PATH_PART, domain) is not None + return True + + +def _warn(message: str) -> None: + print(f"{PREFIX} WARNING: {message}", file=sys.stderr, flush=True) + + @dataclass(frozen=True) class SiteImage: """One record of the catalog (:data:`_REQUIRED` and :data:`_OPTIONAL` keys).""" @@ -87,16 +127,23 @@ class SiteImage: @property def model_key(self) -> str: - return engine_images.model_key(self.model) + return model_key(self.model) @property def at(self) -> str: return str(self.evidence.get("at") or "") + @property + def at_time(self) -> datetime.datetime: + """``evidence.at`` as a UTC time (the earliest time: none).""" + return _utc(self.evidence.get("at")) if self.evidence.get("at") else _EPOCH + def same_image(self, other: SiteImage) -> bool: - """The same (model, role, engine, ref): a newer adoption replaces the older record.""" - return (self.model_key, self.role, self.engine, self.ref) == \ - (other.model_key, other.role, other.engine, other.ref) + """The same (model, role, engine, ref) on the same hardware (CPU and card + architectures): a newer adoption replaces the older record; the same image adopted + on other cards is a record of its own.""" + return (self.model_key, self.role, self.engine, self.ref, self.cpu_arch, tuple(sorted(self.card_archs))) == \ + (other.model_key, other.role, other.engine, other.ref, other.cpu_arch, tuple(sorted(other.card_archs))) def problems(self, profile: Any) -> list[str]: """Why this record does not fit the node ``profile`` (empty: it does).""" @@ -145,12 +192,11 @@ class Choice: def line(self, what: str) -> str: """A dry-run line: `` image (source: ...)``.""" - if self.source == SOURCE_SITE: - assert self.record is not None + if self.source == SOURCE_SITE and self.record is not None: return f"{what} image {self.record.describe()} (source: {SOURCE_SITE} {self.path})" ref = self.ref or "(none)" - if self.source == SOURCE_DEFAULT: - return f"{what} image {ref} (source: {SOURCE_DEFAULT}; {self.why})" + if self.source in (SOURCE_DEFAULT, SOURCE_SITE): # a site choice without its record: kept from before + return f"{what} image {ref} (source: {self.source}; {self.why})" return f"{what} image {ref} (source: {self.source})" def __iter__(self): # (ref, source), the contract's shape @@ -160,8 +206,17 @@ def __iter__(self): # (ref, source), the contract's shape # --- paths ------------------------------------------------------------------------- +def model_key(model: str | None) -> str: + """The catalog key of a model name, its alias resolved first (``kimi-k31`` and + ``moonshotai/Kimi-K3.1-Pro`` are one key).""" + name = str(model).strip() if model is not None else "" + return engine_images.model_key(resolve_model(name) if name else model) + + def default_path() -> Path: - return Path(os.path.expanduser(DEFAULT_PATH)) + """``$YETO_SITE_IMAGES_PATH``, else :data:`DEFAULT_PATH`.""" + value = os.environ.get(PATH_ENV, "").strip() + return Path(os.path.expanduser(value or DEFAULT_PATH)) def catalog_path(value: str | os.PathLike[str] | None = None, *, base: Path | None = None) -> Path: @@ -176,13 +231,12 @@ def catalog_path(value: str | os.PathLike[str] | None = None, *, base: Path | No def inventory_value(document: Any) -> str | None: - """The inventory document's ``site_images:`` (None: not given). Refuses a non-string.""" - if not isinstance(document, Mapping) or document.get(INVENTORY_KEY) is None: - return None - value = document[INVENTORY_KEY] - if not isinstance(value, str) or not value.strip(): - raise SiteImagesError(f"inventory {INVENTORY_KEY}: must be a file path, not {value!r}") - return value + """The inventory document's ``site_images:`` (None: not given); the inventory's own + check (:func:`.node_inventory.site_images_value`). Refuses a non-string.""" + try: + return site_images_value(document) + except InventoryError as error: + raise SiteImagesError(str(error)) from None def inventory_catalog_path(inventory: str | os.PathLike[str] | None) -> Path: @@ -191,8 +245,6 @@ def inventory_catalog_path(inventory: str | os.PathLike[str] | None) -> Path: the default here: the inventory's own loader reports it.""" if not inventory: return default_path() - import yaml # noqa: PLC0415 - file = Path(os.path.expanduser(str(inventory))) try: document = yaml.safe_load(file.read_text()) @@ -215,9 +267,9 @@ def parse_record(raw: Any, *, where: str = "record") -> SiteImage: """One catalog record, validated (:class:`SiteImagesError` names the key).""" if not isinstance(raw, Mapping): raise SiteImagesError(f"{where}: must be a mapping, not {type(raw).__name__}") - unknown = sorted(set(raw) - set(_REQUIRED) - set(_OPTIONAL)) - if unknown: - raise SiteImagesError(f"{where}: unknown key(s) {unknown} (known: {sorted(_REQUIRED + _OPTIONAL)})") + unknown = sorted(str(k) for k in set(raw) - set(_REQUIRED) - set(_OPTIONAL)) + if unknown: # a key of a newer writer: read the record without it + _warn(f"{where}: unknown key(s) {unknown} ignored (known: {sorted(_REQUIRED + _OPTIONAL)})") missing = [k for k in _REQUIRED if k not in raw] if missing: raise SiteImagesError(f"{where}: missing key(s) {missing}") @@ -230,8 +282,9 @@ def parse_record(raw: Any, *, where: str = "record") -> SiteImage: if engine not in engines: raise SiteImagesError(f"{where}: {role} engine {engine!r} is unknown (known: {list(engines)})") ref = _text(raw, "ref", where).removeprefix("docker:") - if not _DIGEST_REF.fullmatch(ref): - raise SiteImagesError(f"{where}: ref {ref!r} must be pinned by digest (REGISTRY/IMAGE@sha256:<64 hex>)") + if not valid_reference(ref): + raise SiteImagesError(f"{where}: ref {ref!r} must be a docker reference pinned by digest " + "(REGISTRY/IMAGE@sha256:<64 hex>)") try: cpu_arch = engine_images.canonical_cpu_arch(_text(raw, "cpu_arch", where)) except engine_images.UnknownCpuArch as error: @@ -241,6 +294,10 @@ def parse_record(raw: Any, *, where: str = "record") -> SiteImage: or not all(isinstance(a, str) and a.strip() for a in archs): raise SiteImagesError(f"{where}: card_archs must be a non-empty list of card architectures " f"(sm103, gfx950, ascend910b ...), not {archs!r}") + card_archs = tuple(a.strip().lower() for a in archs) + strange = [a for a in card_archs if a not in KNOWN_CARD_ARCHS] + if strange: + raise SiteImagesError(f"{where}: card_archs {strange} unknown (known: {list(KNOWN_CARD_ARCHS)})") family = raw.get("device_family") if family is not None: try: @@ -264,21 +321,48 @@ def parse_record(raw: Any, *, where: str = "record") -> SiteImage: raise SiteImagesError(f"{where}: a {VERIFIED} record needs evidence.result pass, " f"not {evidence.get('result')!r}") evidence = {str(k): _plain(v) for k, v in evidence.items()} + if evidence.get("at") not in (None, ""): + try: + evidence["at"] = _iso(_utc(evidence["at"])) + except ValueError as error: + raise SiteImagesError(f"{where}: evidence.at {evidence['at']!r} {error}") from None return SiteImage(model=model, role=role, engine=engine, ref=ref, cpu_arch=cpu_arch, - card_archs=tuple(a.strip().lower() for a in archs), status=status, device_family=family, + card_archs=card_archs, status=status, device_family=family, versions={str(k): str(v) for k, v in versions.items()}, evidence=evidence) -def _plain(value: Any) -> Any: - """A YAML timestamp (``at: 2026-11-26T10:00:00Z`` unquoted) as its ISO text, so records - order by ``evidence.at`` and write back as they were read.""" - import datetime # noqa: PLC0415 +_EPOCH = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc) + +def _utc(value: Any) -> datetime.datetime: + """An ISO-8601 time with its time zone (``2026-11-26T10:00:00Z``, + ``...+08:00``) as UTC; ValueError for a date, a time without a zone or no time.""" if isinstance(value, datetime.datetime): - if value.tzinfo is not None and value.utcoffset() == datetime.timedelta(0): - return value.replace(tzinfo=None).isoformat() + "Z" - return value.isoformat() + moment = value + elif isinstance(value, str) and "T" in value.strip().upper(): + try: + moment = datetime.datetime.fromisoformat(value.strip().replace("z", "Z").replace("Z", "+00:00")) + except ValueError: + raise ValueError("is not an ISO-8601 time (2026-11-26T10:00:00Z)") from None + else: + raise ValueError("is not an ISO-8601 time with a time zone (2026-11-26T10:00:00Z)") + if moment.tzinfo is None or moment.utcoffset() is None: + raise ValueError("has no time zone (write 2026-11-26T10:00:00Z or an offset such as +08:00)") + return moment.astimezone(datetime.timezone.utc) + + +def _iso(moment: datetime.datetime) -> str: + """A UTC time as ``2026-11-26T10:00:00Z`` (microseconds kept when there are any).""" + spec = "microseconds" if moment.microsecond else "seconds" + return moment.replace(tzinfo=None).isoformat(timespec=spec) + "Z" + + +def _plain(value: Any) -> Any: + """A YAML timestamp of the evidence as it is (``at`` is checked on its own); a date + as its ISO text.""" + if isinstance(value, datetime.datetime): + return value if isinstance(value, datetime.date): return value.isoformat() return value @@ -289,11 +373,14 @@ def parse_catalog(document: Any, *, where: str = "site image catalog") -> list[S return [] if not isinstance(document, Mapping): raise SiteImagesError(f"{where}: must be a mapping with version and images, not {type(document).__name__}") - unknown = sorted(set(document) - {"version", "images"}) + unknown = sorted(str(k) for k in set(document) - {"version", "images"}) if unknown: - raise SiteImagesError(f"{where}: unknown top-level key(s) {unknown} (known: ['images', 'version'])") - if document.get("version", VERSION) != VERSION: - raise SiteImagesError(f"{where}: version {document.get('version')!r} is not {VERSION}") + _warn(f"{where}: unknown top-level key(s) {unknown} ignored (known: ['images', 'version'])") + version = document.get("version", VERSION) + if isinstance(version, bool) or not isinstance(version, int) or version < 1: + raise SiteImagesError(f"{where}: version must be a positive integer, not {version!r}") + if version > VERSION: + _warn(f"{where}: version {version} is newer than this reader's {VERSION}; read as far as it goes") images = document.get("images") or [] if not isinstance(images, list): raise SiteImagesError(f"{where}: images must be a list, not {type(images).__name__}") @@ -301,34 +388,39 @@ def parse_catalog(document: Any, *, where: str = "site image catalog") -> list[S def load(path: str | os.PathLike[str] | None = None) -> list[SiteImage]: - """Every record of the catalog at ``path`` (default :data:`DEFAULT_PATH`); a missing - file is an empty catalog, a broken one :class:`SiteImagesError`.""" - import yaml # noqa: PLC0415 - + """Every record of the catalog at ``path`` (default :func:`default_path`); a missing + file is an empty catalog, a broken one :class:`SiteImagesError` (``[yeto] site image + catalog: : ...``).""" file = catalog_path(path) try: text = file.read_text() except FileNotFoundError: return [] except OSError as error: - raise SiteImagesError(f"cannot read the site image catalog {file}: {error}") from None + raise SiteImagesError(f"{PREFIX} cannot read {file}: {error}") from None try: document = yaml.safe_load(text) except yaml.YAMLError as error: - raise SiteImagesError(f"the site image catalog {file} is not valid YAML: {error}") from None - return parse_catalog(document, where=str(file)) + raise SiteImagesError(f"{PREFIX} {file} is not valid YAML: {error}") from None + try: + return parse_catalog(document, where=str(file)) + except SiteImagesError as error: + raise SiteImagesError(f"{PREFIX} {error}") from None def save(records: Sequence[SiteImage], path: str | os.PathLike[str] | None = None) -> Path: """Write ``records`` to the catalog: a temporary file, flushed to disk, renamed over it, and the directory flushed, so a crash leaves the old catalog or the new one.""" - import yaml # noqa: PLC0415 - file = catalog_path(path) file.parent.mkdir(parents=True, exist_ok=True) body = yaml.safe_dump({"version": VERSION, "images": [r.to_doc() for r in records]}, sort_keys=False) + try: + mode = stat.S_IMODE(file.stat().st_mode) # the catalog keeps its mode + except FileNotFoundError: + mode = 0o644 fd, tmp = tempfile.mkstemp(prefix=f".{file.name}.", dir=str(file.parent)) try: + os.fchmod(fd, mode) with os.fdopen(fd, "w") as handle: handle.write(body) handle.flush() @@ -392,8 +484,6 @@ def add(record: SiteImage | Mapping[str, Any], path: str | os.PathLike[str] | No def profile_facts(profile: Any) -> dict[str, Any]: """name / unified family / CPU and card architecture of a node profile, a plain inventory ``Node`` (card architecture from its card) or any object with those fields.""" - from .node_inventory import card_arch_of # noqa: PLC0415 - node_inventory imports engine_images - family = getattr(profile, "family", None) or getattr(profile, "device_family", None) card_arch = getattr(profile, "card_arch", None) if not card_arch and getattr(profile, "card", None): @@ -418,25 +508,44 @@ def match(model: str | None, role: str, profile: Any, *, engine: str | None = No """The verified records for ``model`` in ``role`` that fit every node of ``profile`` (one profile or a list: an island's or a pool's nodes), best first: the newest ``evidence.at``, then the later record in the file. ``engine``: only that engine's - records. No model: nothing matches.""" + records. No model or no node: nothing matches.""" if role not in ROLES: raise ValueError(f"role {role!r} is unknown (known: {list(ROLES)})") - if model is None or not str(model).strip(): - return [] - key = engine_images.model_key(model) nodes = _profiles(profile) + if model is None or not str(model).strip() or not nodes: + return [] + key = model_key(model) found = [] for index, record in enumerate(load(path) if records is None else records): if record.status != VERIFIED or record.role != role or record.model_key != key: continue if engine is not None and record.engine != str(engine).lower(): continue - if nodes and any(record.problems(node) for node in nodes): + if any(record.problems(node) for node in nodes): continue - found.append((record.at, index, record)) + found.append((record.at_time, index, record)) return [r for _, _, r in sorted(found, key=lambda t: (t[0], t[1]), reverse=True)] +def near_misses(model: str | None, role: str, profile: Any, *, engine: str | None = None, + records: Iterable[SiteImage], limit: int = 3) -> list[str]: + """The closest records that did not match (same model and role, verified, newest + first) with why not (:meth:`SiteImage.problems`, the engine), for a fallback reason.""" + if model is None or not str(model).strip(): + return [] + key = model_key(model) + nodes = _profiles(profile) + near = [(r.at_time, i, r) for i, r in enumerate(records) + if r.status == VERIFIED and r.role == role and r.model_key == key] + out = [] + for _, _, record in sorted(near, key=lambda t: (t[0], t[1]), reverse=True)[:limit]: + why = [f"it is a {record.engine} image, not {str(engine).lower()}"] \ + if engine is not None and record.engine != str(engine).lower() else [] + why += sorted({p for node in nodes for p in record.problems(node)}) + out.append(f"{record.ref}: {'; '.join(why) or 'no node to match'}") + return out + + def select(explicit: str | None, model: str | None, role: str, profile: Any, *, engine: str | None = None, path: str | os.PathLike[str] | None = None, default: str | Callable[[], str | None] | None = None) -> Choice: @@ -455,7 +564,10 @@ def select(explicit: str | None, model: str | None, role: str, profile: Any, *, elif model is None or not str(model).strip(): why = "no model to match" else: - what = f"{engine_images.model_key(model)} {role}" + (f" ({engine})" if engine else "") + what = f"{model_key(model)} {role}" + (f" ({engine})" if engine else "") why = f"no {VERIFIED} record in {file} for {what} on these nodes" + near = near_misses(model, role, profile, engine=engine, records=records) + if near: + why += " (closest: " + " | ".join(near) + ")" ref = default() if callable(default) else default return Choice(ref, SOURCE_DEFAULT, None, file, why) diff --git a/yeto/launch/ssh_sampler_pool.py b/yeto/launch/ssh_sampler_pool.py index 0d1bac98b..40d5a2cac 100644 --- a/yeto/launch/ssh_sampler_pool.py +++ b/yeto/launch/ssh_sampler_pool.py @@ -1269,6 +1269,7 @@ def __init__(self, cfg: dict[str, Any], *, conf: SshPoolConf | None = None, self._node_route: Any = None self._health_generation: dict[str, int] = {} # ticket -> the assignment its health check is of self._health_lost: set[str] = set() # tickets whose node's health read lost (drain holds its slot) + self._images: dict[str, Any] | None = None # node -> site_images.Choice, fixed at the first start def attach_control(self, control: Any) -> dict[str, Any]: """The store control plane (``store_state.PoolControl``): the provider's tickets, holds @@ -1479,8 +1480,54 @@ def event(self, name: str, **detail: Any) -> None: def image_for(self, node: Node) -> str: """The image a node runs: ``container.image`` (``auto``: the node's inventory - image, else the catalog's for what the spec asks), else the node's image.""" - return node_image(self.conf, node, spec_of(self.cfg)) + image, else the site image catalog's, else the engine image catalog's for what the + spec asks), else the node's image. An image the pool chose itself is chosen once + for every node (:func:`pool_image_choices`, what the dry-run prints) and kept in + the pool's state (:meth:`images_path`): a replacement node and a restarted pool + controller start the same image, the catalog is not read again.""" + if self._images is None: + self._images = self._pin_images() + choice = self._images.get(node.name) + if choice is None: + return node_image(self.conf, node, spec_of(self.cfg)) + if isinstance(choice, Exception): + raise choice + return str(choice.ref) + + def images_path(self) -> Path: + return self.state_dir / f"ssh-pool-{self.run_id}-images.json" + + def _pin_images(self) -> dict[str, Any]: + from . import site_images # noqa: PLC0415 + + spec = spec_of(self.cfg) + choices = pool_image_choices(self.conf, spec) + needs = engine_images.spec_needs(spec) + key = {"model": needs.get("model"), "engine": needs.get("engine_pref"), "catalog": self.conf.site_images} + path = self.images_path() + try: + kept = json.loads(path.read_text()) + except (OSError, ValueError): + kept = None + if isinstance(kept, dict) and kept.get("key") == key: + for name, row in (kept.get("images") or {}).items(): + if name in choices and not _explicit(choices[name]): + choices[name] = site_images.Choice(str(row["ref"]), str(row["source"]), + why=f"kept from the pool's start ({path.name})") + pinned = {name: {"ref": c.ref, "source": c.source} for name, c in choices.items() + if not isinstance(c, Exception) and not _explicit(c)} + if pinned: + try: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(".tmp") + tmp.write_text(json.dumps({"key": key, "images": pinned}, indent=1, sort_keys=True)) + tmp.replace(path) + except OSError as error: # the pool runs; a restarted controller chooses again + _log(f"ssh pool: the chosen images were not kept in {path}: {error}") + for name, c in sorted(choices.items()): + if not isinstance(c, Exception) and not _explicit(c): + _log(f"ssh pool: node {name}: {c.line('sampler')}") + return choices def start_node_runtime(self, route: Any, node: Node, m, shards: list[str], spec: Mapping[str, Any], *, python: str, env_file: str | None) -> str: @@ -1799,28 +1846,68 @@ def spec_of(cfg: Mapping[str, Any]) -> dict[str, Any]: def node_image(conf: SshPoolConf, node: Node, spec: Mapping[str, Any]) -> str: """The image ``node`` runs (container runtime): ``container.image`` unless it is ``auto``; then the node's inventory image, else the site image catalog's verified - image for the spec's model on this node, else the engine image catalog's choice for - what ``spec`` asks (raises ``ImageIncompatible`` when none serves it).""" + image for the spec's model on the pool's nodes, else the engine image catalog's choice + for what ``spec`` asks (raises ``ImageIncompatible`` when none serves it).""" return str(node_image_choice(conf, node, spec).ref) +def _explicit(choice: Any) -> bool: + from .site_images import SOURCE_EXPLICIT # noqa: PLC0415 + + return not isinstance(choice, Exception) and choice.source == SOURCE_EXPLICIT + + def node_image_choice(conf: SshPoolConf, node: Node, spec: Mapping[str, Any]): # -> site_images.Choice """:func:`node_image` with where it came from (``site_images.Choice``): the pool's or the inventory's image (explicit), the site image catalog, or the engine image catalog (the built-in default). A broken site catalog raises ``SiteImagesError``.""" + choices = pool_image_choices(conf, spec, only=node) + choice = choices[node.name] + if isinstance(choice, Exception): + raise choice + return choice + + +def pool_image_choices(conf: SshPoolConf, spec: Mapping[str, Any], *, + only: Node | None = None) -> dict[str, Any]: + """Every node's image choice (``site_images.Choice``, or the exception that refuses + the node), the pool's nodes at once: the site catalog is read once and matched against + all of them (``auto`` nodes without an inventory image), so a spare that replaces a + node starts the same site image. ``only``: just that node's entry (a node outside + the pool is matched alone).""" from . import site_images # noqa: PLC0415 assert conf.container is not None + nodes = list(conf.nodes) + if only is not None and only.name not in {n.name for n in nodes}: + nodes = [only] + wanted = [only] if only is not None else nodes if conf.container.image and conf.container.image != AUTO_IMAGE: - return site_images.Choice(conf.container.image, site_images.SOURCE_EXPLICIT) - if node.image: - return site_images.Choice(node.image, site_images.SOURCE_EXPLICIT) + return {n.name: site_images.Choice(conf.container.image, site_images.SOURCE_EXPLICIT) for n in wanted} + out: dict[str, Any] = {n.name: site_images.Choice(n.image, site_images.SOURCE_EXPLICIT) for n in wanted if n.image} + auto = [n for n in nodes if not n.image] + if not [n for n in wanted if not n.image]: + return out needs = engine_images.spec_needs(spec) model, pref = needs.pop("model"), needs.pop("engine_pref") - return site_images.select( - None, model, "sampler", profile_of(node), engine=pref, path=conf.site_images, - default=lambda: engine_images.resolve(profile_of(node), model, pref, - **needs).image.pull_ref) # type: ignore[union-attr] + try: + site = site_images.select(None, model, "sampler", [profile_of(n) for n in auto], engine=pref, + path=conf.site_images, default=None) + except site_images.SiteImagesError as error: + return {**out, **{n.name: error for n in wanted if not n.image}} + for node in wanted: + if node.image: + continue + if site.source == site_images.SOURCE_SITE: + out[node.name] = site + continue + try: + ref = engine_images.resolve(profile_of(node), model, pref, **needs).image.pull_ref # type: ignore[union-attr] + except engine_images.ImageIncompatible as error: + out[node.name] = error + continue + out[node.name] = site_images.Choice(ref, site_images.SOURCE_DEFAULT, None, site.path, site.why) + return out def image_problems(conf: SshPoolConf, spec: Mapping[str, Any]) -> list[str]: @@ -1834,9 +1921,12 @@ def image_problems(conf: SshPoolConf, spec: Mapping[str, Any]) -> list[str]: out = [] from .site_images import SOURCE_EXPLICIT, SiteImagesError # noqa: PLC0415 + choices = pool_image_choices(conf, spec) # what the pool's first start fixes (SshSamplerPoolOps.image_for) for node in conf.nodes: try: - choice = node_image_choice(conf, node, spec) + choice = choices[node.name] + if isinstance(choice, Exception): + raise choice if choice.source != SOURCE_EXPLICIT: # the dry-run names an image the pool chose itself print(f"ssh provider: node {node.name}: {choice.line('sampler')}") engine_images.resolve(profile_of(node), model, pref, image=str(choice.ref), **needs) From 0970f1eebfc1a65cc86c994309d3ad315ce067ad Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 19:00:12 +0800 Subject: [PATCH 4/4] Site image catalog: choose a pool's images once under parallel starts; spares in the trainer match - SshSamplerPoolOps.image_for chooses the pool's images under a lock (double-checked): parallel starts of an IslandPool take one choice, and the kept file names the image the nodes run; it is written through a temporary file of its own (mkstemp in the same directory) and os.replace - the ssh: trainer island's catalog match covers the trainer nodes and every node of a trainer-* role (a trainer-spare starts the island's image) - tests for the kept file never replacing a named image or another model's choice, and for a record of another device family Co-Authored-By: Claude Opus 5.5 --- tests/test_node_lease.py | 3 +- tests/test_site_images.py | 112 ++++++++++++++++++++++++++++++-- yeto/launch/rl_backend.py | 7 +- yeto/launch/ssh_sampler_pool.py | 24 +++++-- 4 files changed, 133 insertions(+), 13 deletions(-) diff --git a/tests/test_node_lease.py b/tests/test_node_lease.py index 31725d11d..b9e55aa57 100644 --- a/tests/test_node_lease.py +++ b/tests/test_node_lease.py @@ -91,7 +91,8 @@ def test_a_bad_lease_store_is_refused(value): def test_the_unknown_field_message_names_lease_store(): - with pytest.raises(InventoryError, match=r"known: \['images', 'lease_store', 'node_health', 'nodes'\]"): + with pytest.raises(InventoryError, + match=r"known: \['images', 'lease_store', 'node_health', 'nodes', 'site_images'\]"): parse_inventory({"lease": "s3://x", "nodes": [_raw(0)]}) diff --git a/tests/test_site_images.py b/tests/test_site_images.py index 9b47a247f..d1b44ee70 100644 --- a/tests/test_site_images.py +++ b/tests/test_site_images.py @@ -360,7 +360,8 @@ def test_the_inventory_accepts_site_images_and_refuses_a_non_path(): assert [n.name for n in parse_inventory({"site_images": "/etc/yeto/images.yaml", "nodes": [node]})] == ["b300-0"] with pytest.raises(InventoryError, match="site_images: must be a file path"): parse_inventory({"site_images": ["a"], "nodes": [node]}) - with pytest.raises(InventoryError, match=r"known: \['images', 'node_health', 'nodes', 'site_images'\]"): + with pytest.raises(InventoryError, + match=r"known: \['images', 'lease_store', 'node_health', 'nodes', 'site_images'\]"): parse_inventory({"lease": "x", "nodes": [node]}) @@ -532,9 +533,7 @@ def test_the_pool_fixes_its_images_at_the_first_start_and_keeps_them(tmp_path, m monkeypatch.setattr(sp, "spec_of", lambda cfg: spec) def ops(): - o = sp.SshSamplerPoolOps.__new__(sp.SshSamplerPoolOps) - o.cfg, o.conf, o.run_id, o.state_dir, o._images = {}, conf, "run1", tmp_path / "state", None - return o + return _pool_ops(conf, tmp_path) first = ops() assert first.image_for(conf.nodes[0]) == REF3 @@ -571,3 +570,108 @@ def test_an_unquoted_yaml_timestamp_reads_as_its_iso_text(tmp_path): assert "at: 2026-11-26T10:00:00Z" in path.read_text() (r,) = si.load(path) assert r.at == "2026-11-26T10:00:00Z" + + +def _pool_ops(conf, tmp_path): + o = sp.SshSamplerPoolOps.__new__(sp.SshSamplerPoolOps) + o.cfg, o.conf, o.run_id, o.state_dir, o._images = {}, conf, "run1", tmp_path / "state", None + import threading + + o._images_lock = threading.Lock() + return o + + +def test_parallel_starts_choose_the_pool_images_once(tmp_path, monkeypatch): + import threading + import time as _time + + spec = json.loads(K31_SPEC.read_text()) + monkeypatch.setattr(sp, "spec_of", lambda cfg: spec) + conf = _pool(write_catalog(tmp_path / "c.yaml", record(role="sampler", engine="vllm", ref=REF3))) + calls = [] + + def choices(conf_, spec_, *, only=None): # each call would see a newer catalog (an adopt in between) + calls.append(1) + _time.sleep(0.2) + ref = f"registry.example/site/vllm-{len(calls)}@sha256:{D1}" + return {"b300-0": si.Choice(ref, si.SOURCE_SITE, why="test")} + + monkeypatch.setattr(sp, "pool_image_choices", choices) + ops = _pool_ops(conf, tmp_path) + barrier, got, errors = threading.Barrier(6), [], [] + + def start(): + barrier.wait() + try: + got.append(ops.image_for(conf.nodes[0])) + except Exception as error: # noqa: BLE001 + errors.append(error) + + threads = [threading.Thread(target=start) for _ in range(6)] + for t in threads: + t.start() + for t in threads: + t.join(10) + assert errors == [] and len(calls) == 1 and set(got) == {f"registry.example/site/vllm-1@sha256:{D1}"} + kept = json.loads(ops.images_path().read_text()) + assert kept["images"]["b300-0"]["ref"] == got[0] # the state file names the image the nodes run + assert [p.name for p in ops.images_path().parent.iterdir()] == [ops.images_path().name] # no temporary file + + +def _kept(ops, spec, images, **key): + from yeto.launch import engine_images + + needs = engine_images.spec_needs(spec) + doc = {"key": {"model": needs.get("model"), "engine": needs.get("engine_pref"), "catalog": ops.conf.site_images, + **key}, "images": images} + ops.images_path().parent.mkdir(parents=True, exist_ok=True) + ops.images_path().write_text(json.dumps(doc)) + + +def test_a_kept_image_never_replaces_a_named_one_or_another_model(tmp_path, monkeypatch): + spec = json.loads(K31_SPEC.read_text()) + monkeypatch.setattr(sp, "spec_of", lambda cfg: spec) + catalog = write_catalog(tmp_path / "c.yaml", record(role="sampler", engine="vllm", ref=REF3)) + kept = {"b300-0": {"ref": f"registry.example/site/kept@sha256:{D2}", "source": si.SOURCE_SITE}} + named = _pool_ops(_pool(catalog, image=f"ghcr.io/x/pool@sha256:{D1}"), tmp_path) + _kept(named, spec, kept) + assert named.image_for(named.conf.nodes[0]) == f"ghcr.io/x/pool@sha256:{D1}" # the configuration names it + auto = _pool_ops(_pool(catalog), tmp_path / "b") + _kept(auto, spec, kept) + assert auto.image_for(auto.conf.nodes[0]) == kept["b300-0"]["ref"] # the same pool: its start's image + other = _pool_ops(_pool(catalog), tmp_path / "c") + _kept(other, spec, kept, model="Qwen/Qwen3-8B") + assert other.image_for(other.conf.nodes[0]) == REF3 # kept for another model: chosen again + + +def test_a_record_of_another_device_family_does_not_fit(): + from types import SimpleNamespace + + r = si.parse_record(record(device_family="cuda")) + ppu = SimpleNamespace(name="p0", family="ppu", cpu_arch="x86_64", card_arch="sm103") + assert r.problems(ppu) == ["it is a cuda image, node p0 is ppu"] + assert si.parse_record(record(device_family=None)).problems(ppu) == [] + + +def test_the_trainer_match_takes_the_spares_too(tmp_path, capsys): + from yeto.launch.rl_backend import _builtin_rl_image, resolve_default_rl_image + + inv = _inventory(tmp_path, catalog=write_catalog(tmp_path / "c.yaml", record()), nodes=2) + doc = yaml.safe_load(inv.read_text()) + doc["nodes"][0]["roles"] = ["trainer"] + doc["nodes"][1].update(roles=["trainer-spare"], card="H200", hbm_gib=141) # the record does not fit the spare + inv.write_text(yaml.safe_dump(doc)) + args = _args(inv) + resolve_default_rl_image(args) + assert args.rl_image == _builtin_rl_image(args) + assert "b300-1 has sm90" in capsys.readouterr().err + + +def test_the_kept_file_is_written_through_a_temporary_file_of_its_own(tmp_path, monkeypatch): + spec = json.loads(K31_SPEC.read_text()) + monkeypatch.setattr(sp, "spec_of", lambda cfg: spec) + ops = _pool_ops(_pool(write_catalog(tmp_path / "c.yaml", record(role="sampler", engine="vllm", ref=REF3))), + tmp_path) + ops.images_path().with_suffix(".tmp").mkdir(parents=True) # another writer's fixed temporary path + assert ops.image_for(ops.conf.nodes[0]) == REF3 + assert json.loads(ops.images_path().read_text())["images"]["b300-0"]["ref"] == REF3 diff --git a/yeto/launch/rl_backend.py b/yeto/launch/rl_backend.py index b6d756ccb..0f5cc7207 100644 --- a/yeto/launch/rl_backend.py +++ b/yeto/launch/rl_backend.py @@ -67,13 +67,16 @@ def _site_catalog_trainer_nodes(args) -> tuple[list | None, str]: if not path or not getattr(args, "gpu", None): return None, "" from ..gpu_spec import parse_gpu_spec - from .node_inventory import InventoryError, island_nodes, load_inventory + from .node_inventory import InventoryError, load_inventory try: clouds = [spec.cloud for spec in parse_gpu_spec(args.gpu)] if "ssh" not in clouds: return None, "" - nodes = island_nodes(load_inventory(path), "trainer") + # the trainer nodes and their spares (a role of the trainer's kind: trainer-spare): a spare + # that replaces a node runs the island's image, so the record must fit it too + nodes = [n for n in load_inventory(path) + if not n.roles or any(r == "trainer" or r.startswith("trainer-") for r in n.roles)] except (ValueError, InventoryError): # the launch's own checks name a bad --gpu or inventory return None, "" if not nodes or any(n.image for n in nodes): diff --git a/yeto/launch/ssh_sampler_pool.py b/yeto/launch/ssh_sampler_pool.py index 40d5a2cac..01b1dac35 100644 --- a/yeto/launch/ssh_sampler_pool.py +++ b/yeto/launch/ssh_sampler_pool.py @@ -1270,6 +1270,7 @@ def __init__(self, cfg: dict[str, Any], *, conf: SshPoolConf | None = None, self._health_generation: dict[str, int] = {} # ticket -> the assignment its health check is of self._health_lost: set[str] = set() # tickets whose node's health read lost (drain holds its slot) self._images: dict[str, Any] | None = None # node -> site_images.Choice, fixed at the first start + self._images_lock = threading.Lock() # parallel starts (IslandPool) choose the images once def attach_control(self, control: Any) -> dict[str, Any]: """The store control plane (``store_state.PoolControl``): the provider's tickets, holds @@ -1485,9 +1486,13 @@ def image_for(self, node: Node) -> str: for every node (:func:`pool_image_choices`, what the dry-run prints) and kept in the pool's state (:meth:`images_path`): a replacement node and a restarted pool controller start the same image, the catalog is not read again.""" - if self._images is None: - self._images = self._pin_images() - choice = self._images.get(node.name) + images = self._images + if images is None: + with self._images_lock: # double-checked: one start chooses, the others take its choice + if self._images is None: + self._images = self._pin_images() + images = self._images + choice = images.get(node.name) if choice is None: return node_image(self.conf, node, spec_of(self.cfg)) if isinstance(choice, Exception): @@ -1518,10 +1523,17 @@ def _pin_images(self) -> dict[str, Any]: if not isinstance(c, Exception) and not _explicit(c)} if pinned: try: + import tempfile # noqa: PLC0415 + path.parent.mkdir(parents=True, exist_ok=True) - tmp = path.with_suffix(".tmp") - tmp.write_text(json.dumps({"key": key, "images": pinned}, indent=1, sort_keys=True)) - tmp.replace(path) + fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent)) + try: + with os.fdopen(fd, "w") as handle: + handle.write(json.dumps({"key": key, "images": pinned}, indent=1, sort_keys=True)) + os.replace(tmp, path) + except BaseException: + Path(tmp).unlink(missing_ok=True) + raise except OSError as error: # the pool runs; a restarted controller chooses again _log(f"ssh pool: the chosen images were not kept in {path}: {error}") for name, c in sorted(choices.items()):