From fac7c6994fb6e6700f0fd6f5e042b66109e7e0ad Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Thu, 26 Nov 2026 23:20:59 +0800 Subject: [PATCH 1/2] tests: rendered launch argv under production defaults tests/conftest.py relaxes production defaults for every test (the --inner-lr default reads as explicit; YETO_PREFLIGHT_MODEL, YETO_IMAGE_MANIFEST_CHECK and YETO_SKY_SERVER_CHECK are off; YETO_RL_COMPAT_GROUP is set), so an argv yeto renders for another process passes the suite even when that process refuses it. tests/prod_defaults.py puts the production defaults back for one test, with stub Hub, Modal volume, store, registry and sky server probes that answer "present", and runs a rendered argv through the real yeto.cli launch --dry-run. tests/test_prod_defaults_argv.py uses it on every render-and-hand-off path on main: run up of the own-cluster templates and the K3.1 bare-metal config, the K3.1 customer trainer launches, the Modal and ssh: island entry commands parsed with only the island's own environment, the NC pool dry run and the node spec it renders, a fleet's compiled trainer argv, each per-island launch, and a sky island's entry. Two negative tests show the check bites: a run config without --inner-lr and a launch whose model the Hub lacks pass under the conftest defaults and are refused under production's. conftest: opt-in production_defaults fixture, and a RISK note at each global override pointing at the new tests. The overrides stay global: about 70 % of tests/test_rl_launcher.py builds RL argv without --inner-lr. Co-Authored-By: Claude Opus 5.5 --- tests/conftest.py | 27 ++- tests/prod_defaults.py | 120 ++++++++++ tests/test_prod_defaults_argv.py | 378 +++++++++++++++++++++++++++++++ 3 files changed, 524 insertions(+), 1 deletion(-) create mode 100644 tests/prod_defaults.py create mode 100644 tests/test_prod_defaults_argv.py diff --git a/tests/conftest.py b/tests/conftest.py index e9044c3c9..51ae2f94e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -88,6 +88,11 @@ def ports_v1_pin(monkeypatch): # decoupling 7.7a: islands must declare a compat_group (no default in code). # Unit tests that build identities at import time run as one H100 island; # tests of the missing-value error delete it with monkeypatch. +# RISK (as every production default this file changes for every test: DEFAULT_INNER_LR, +# YETO_PREFLIGHT_MODEL, YETO_IMAGE_MANIFEST_CHECK, YETO_SKY_SERVER_CHECK): an island +# env or a rendered argv that lacks it still passes here. A test of an argv handed to +# another process takes the production_defaults fixture (tests/prod_defaults.py; +# tests/test_prod_defaults_argv.py). _os.environ.setdefault("YETO_RL_COMPAT_GROUP", "nvidia-h100") @@ -220,7 +225,11 @@ def _no_real_nebius_sg_cleanup(request, monkeypatch): @_pytest.fixture(autouse=True) def _no_real_model_preflight(monkeypatch): """The launch's model preflight asks the Hub / Modal / the bucket; unit tests - never reach them. Tests of the check set --preflight-model and fake the probes.""" + never reach them. Tests of the check set --preflight-model and fake the probes. + + RISK: a rendered launch argv that a real run refuses without --preflight-model off + passes every test (an image smoke's trainer argv did). production_defaults below + turns the check back on with stub probes.""" monkeypatch.setenv("YETO_PREFLIGHT_MODEL", "off") @@ -492,11 +501,27 @@ def pytest_sessionfinish(session, exitstatus): # (yeto.launch.rl_args.refuse_unset_inner_lr). Before any test module builds a # parser (some at import), the CLI default reads as an explicit value here; # tests/test_rl_inner_lr_guard.py puts the marked default back. +# RISK: an argv yeto renders without --inner-lr for another `yeto launch` (run up, a +# fleet island, an image smoke) passes here and is refused on the real run. Not made +# opt-in: about 70 % of tests/test_rl_launcher.py alone build RL argv without it. The +# rendered-argv tests take production_defaults instead (tests/test_prod_defaults_argv.py). import yeto.cli as _yeto_cli # noqa: E402 _yeto_cli.DEFAULT_INNER_LR = 3e-4 +@_pytest.fixture +def production_defaults(monkeypatch): + """Opt-in: undo, for this test, every production default this file changes that a + rendered argv's own process does not get (the --inner-lr default, the model / image + manifest / sky server checks, the compat group), with stub Hub, store, registry and + sky server probes that answer "present" (tests/prod_defaults.py). Returns the record + of the probes asked.""" + import prod_defaults + + return prod_defaults.apply(monkeypatch) + + @_pytest.fixture(autouse=True) def _no_release_download_spread(monkeypatch): """Background release downloads start at once in tests (production spreads them 0..5 s).""" diff --git a/tests/prod_defaults.py b/tests/prod_defaults.py new file mode 100644 index 000000000..3c0d838a1 --- /dev/null +++ b/tests/prod_defaults.py @@ -0,0 +1,120 @@ +"""Production defaults for a test that hands a rendered argv to the real parser. + +tests/conftest.py changes production defaults for every test: ``yeto.cli.DEFAULT_INNER_LR`` +is a plain float (an RL launch without ``--inner-lr`` is not refused), and +``YETO_PREFLIGHT_MODEL=off``, ``YETO_IMAGE_MANIFEST_CHECK=off``, ``YETO_SKY_SERVER_CHECK=off`` +and ``YETO_RL_COMPAT_GROUP=nvidia-h100`` are in the environment. An argv that yeto renders +for another process (``run up`` -> ``yeto launch``, a fleet island's launch, an island's +entry, a pool's node) runs there without any of them, so a missing flag passes the suite +and is refused on the real run. + +:func:`apply` puts the production defaults back for one test (monkeypatch, undone at its +end). The checks they switch back on reach no network: the Hub, a Modal volume, the +store, the registry and the sky API server answer from stubs that say the model and the +image exist. Everything else of conftest (the ~/.yeto guard, no ssh, no Ray) stays. +""" + +from __future__ import annotations + +import contextlib +import io +from typing import Any, Callable, Sequence + +# What tests/conftest.py sets for every test that a rendered argv's own process does not get. +CONFTEST_ENV = ("YETO_PREFLIGHT_MODEL", "YETO_IMAGE_MANIFEST_CHECK", "YETO_SKY_SERVER_CHECK", "YETO_RL_COMPAT_GROUP") +MODEL_FILES = ("config.json", "model.safetensors") +HUB_COMMIT = "e" * 40 # what the stub Hub resolves a moving revision (main) to + + +def _model_listing(*_args: Any, **_kwargs: Any) -> tuple[list[str], Callable[[str], bytes | None]]: + """A complete single-file checkpoint: the model exists and is readable.""" + return list(MODEL_FILES), lambda name: b"{}" if name in MODEL_FILES else None + + +def apply(monkeypatch: Any) -> dict[str, list[str]]: + """Production defaults for this test; returns the record of every stubbed probe asked + (``hub``, ``volume``, ``store``, ``registry``), so a test can tell a check ran.""" + import yeto.cli as cli + from yeto import provenance, sky_patches + from yeto.launch import image_manifest, model_check + from yeto.launch.nc import pool_run + + asked: dict[str, list[str]] = {"hub": [], "volume": [], "store": [], "registry": []} + monkeypatch.setattr(cli, "DEFAULT_INNER_LR", cli._DefaultLR(3e-4)) + for name in CONFTEST_ENV: + monkeypatch.delenv(name, raising=False) + + def hub(repo, revision): + asked["hub"].append(f"{repo}@{revision}") + return _model_listing() + + def volume(vol, path): + asked["volume"].append(f"{vol}:{path}") + return None # no snapshot there: the trainer downloads from the Hub + + def store(uri, environ=None): # noqa: ARG001 + asked["store"].append(uri) + return [] + + def store_source(source, environ=None): # noqa: ARG001 + asked["store"].append(source) + return _model_listing() + + def bucket(uri, env_file): # noqa: ARG001 + asked["store"].append(uri) + return [] + + def registry(ref, login=None, **_kw): # noqa: ARG001 + asked["registry"].append(ref) + return image_manifest.PRESENT, "stub registry: present" + + monkeypatch.setattr(model_check, "hub_files", hub) + monkeypatch.setattr(model_check, "modal_volume_files", volume) + monkeypatch.setattr(model_check, "store_uri_problems", store) + monkeypatch.setattr(model_check, "model_store_source_files", store_source) + monkeypatch.setattr(pool_run, "model_problems", bucket) + monkeypatch.setattr(image_manifest, "manifest_status", registry) + monkeypatch.setattr(sky_patches, "api_server_version_problem", lambda *a, **k: None) # one sky version + real_resolve = provenance.resolve_hub_revision + + def resolve(repo_id, requested_revision, *, repo_type, api=None): + if api is not None or provenance.is_immutable_commit(requested_revision or ""): + return real_resolve(repo_id, requested_revision, repo_type=repo_type, api=api) + asked["hub"].append(f"{repo_type}:{repo_id}@{requested_revision or 'main'}") + return requested_revision or "main", HUB_COMMIT # a moving revision: the Hub's commit + + monkeypatch.setattr(provenance, "resolve_hub_revision", resolve) + monkeypatch.setenv("MODAL_DISABLE_API_PROXY", "1") # Modal is not asked; no proxy extra needed + return asked + + +def launch_dry_run(argv: Sequence[str]) -> tuple[int, str]: + """``yeto launch --dry-run`` through the real ``yeto.cli`` (its parser and the + launch's checks), as the process the argv is handed to runs it: (rc, stdout+stderr).""" + import yeto.cli as cli + + argv = [str(a) for a in argv] + if "--dry-run" not in argv: + argv.append("--dry-run") + out = io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out): + try: + rc = int(cli.main(["launch", *argv]) or 0) + except SystemExit as stop: # argparse: a missing or bad flag + rc = int(stop.code or 0) if not isinstance(stop.code, str) else 2 + out.write(f"\nSystemExit: {stop.code}\n") + except Exception as error: # noqa: BLE001 - a refusal of the launch's checks, shown to the test + rc = 1 + out.write(f"\n{type(error).__name__}: {error}\n") + return rc, out.getvalue() + + +def refusal(text: str, limit: int = 40) -> str: + """The lines of a dry run that say why it failed (for an assertion message).""" + import re + + marks = re.compile(r"INVALID|refus|rejected|required|the following arguments|error|Error|cannot|must |" + r"Traceback|SystemExit|inner-lr|preflight", re.I) + lines = [line for line in text.splitlines() if marks.search(line)] + return "\n".join(lines[:limit]) or text[-3000:] + diff --git a/tests/test_prod_defaults_argv.py b/tests/test_prod_defaults_argv.py new file mode 100644 index 000000000..64bba606f --- /dev/null +++ b/tests/test_prod_defaults_argv.py @@ -0,0 +1,378 @@ +"""Rendered argv under production defaults. + +tests/conftest.py relaxes production defaults for every test (tests/prod_defaults.py +lists them). With them, an argv that yeto renders for another process passes the suite +even when that process refuses it: an image smoke's trainer argv without ``--inner-lr`` +and without ``--preflight-model off`` was green here and refused on the node. Each test +here puts the production defaults back, renders the argv the way the product does and +hands it to the real parser of the process that receives it: + +* ``run up`` -> ``yeto launch --dry-run`` and ``python -m yeto.launch.nc pool --dry-run`` + (the own-cluster templates, the K3.1 customer configs); +* a fleet's compiled trainer argv and each island's own launch (``island_launches.launch_argv``, + what ``trainer_worker`` runs as ``python -m yeto.cli launch``); +* the island entry command of a Modal, a sky and an ``ssh:`` trainer island, parsed by the + island's own parser with only the environment that island is given; +* the sampler spec an NC pool renders for a node, read the way ``engine_sampler`` reads it. + +The image smoke's own trainer plan is not on main yet (image adopt); its argv goes through +the same :func:`prod_defaults.launch_dry_run` there.""" + +from __future__ import annotations + +import json +import shlex +import sys +import types +from pathlib import Path + +import prod_defaults +import pytest +from test_own_cluster_templates import TEMPLATES, kit # noqa: F401 - the fixture + +ROOT = Path(__file__).resolve().parents[1] +MILES_ENTRY = "yeto.rl.adapters.miles.island_entry" +SHELL_OPERATORS = ("&&", ";", "|", "||", ")") + + +@pytest.fixture +def fake_sky(monkeypatch): + """The sky module of tests/test_rl_launcher.py: tasks are built in memory, nothing is asked.""" + from test_rl_launcher import _Resources, _Storage, _StorageMode, _Task + + monkeypatch.setitem(sys.modules, "sky", types.SimpleNamespace( + Task=_Task, Resources=_Resources, Storage=_Storage, StorageMode=_StorageMode)) + monkeypatch.setattr("yeto.launch.modal_islands._list_modal_apps", lambda: []) + + +def _launches(commands): + return [c[4:] for c in commands if c[2] == "yeto.cli" and c[3] == "launch"] + + +def _without_inner_lr(argv): + argv = [str(a) for a in argv] + if "--inner-lr" in argv: + k = argv.index("--inner-lr") + del argv[k:k + 2] + return [a for a in argv if not a.startswith("--inner-lr=")] + + +# -- run up -> yeto launch / nc pool: the own-cluster templates ---------------------------------- + +@pytest.mark.parametrize("name", TEMPLATES) +def test_run_up_dry_run_of_each_own_cluster_template_passes_with_production_defaults( + kit, name, production_defaults, capsys): # noqa: F811 + from test_own_cluster_templates import _dry_run + + asked = production_defaults + rc, out = _dry_run(kit, name, capsys) + assert rc == 0, out.why + assert "dry run: preflight ok, nothing ordered" in out + assert _launches(kit.commands), kit.commands + assert asked["hub"] or asked["store"], "the trainer's model preflight did not run" + + +def test_a_run_config_without_inner_lr_is_refused_only_with_production_defaults(kit, monkeypatch, capsys): # noqa: F811 + """The check above can fail: the same template without --inner-lr passes under the + conftest defaults (what hid the image smoke's argv) and is refused under production's.""" + from test_own_cluster_templates import _dry_run + + name = "run.own-trainer-modal-sampler.json" + path = kit.files[name] + doc = json.loads(path.read_text()) + doc["trainer"]["argv"] = _without_inner_lr(doc["trainer"]["argv"]) + path.write_text(json.dumps(doc)) + rc, out = _dry_run(kit, name, capsys) + assert rc == 0, out.why # conftest: DEFAULT_INNER_LR is a plain float + prod_defaults.apply(monkeypatch) + rc, out = _dry_run(kit, name, capsys) + assert rc != 0 and "pass --inner-lr explicitly" in out + + +# -- the K3.1 customer: run up, its trainer launch, its island and its pool ------------------------ + +def test_the_customer_bare_metal_run_up_dry_run_passes_with_production_defaults(tmp_path, monkeypatch, capsys): + """examples/k31/run.baremetal-b300-262k.json through ``run up --dry-run`` as in + tests/test_k31_baremetal_run_up_dry_run.py, but with the production defaults put back + after that harness sets ``YETO_PREFLIGHT_MODEL=off``.""" + from test_k31_baremetal_run_up_dry_run import _run_up + from yeto.rl import up + + real_main = up.main + asked = {} + + def main(args): + asked.update(prod_defaults.apply(monkeypatch)) + return real_main(args) + + monkeypatch.setattr(up, "main", main) + lines = _run_up(tmp_path, monkeypatch, capsys) + assert "dry run: preflight ok, nothing ordered" in lines + assert asked["hub"] or asked["store"], "the trainer's model preflight did not run" + + +def _customer_launch(case, tmp_path, monkeypatch): + """The customer's trainer argv (tests/test_k31_customer_plan_golden.py) through + ``yeto launch --dry-run`` with production defaults; returns (rc, output, prepared args).""" + import yeto.cli as cli + import yeto.launcher as launcher + import yeto.modal_runner as modal_runner + from test_k31_customer_plan_golden import CASES, _argv, _hermetic_env + from yeto.cloud import s3_store + + _hermetic_env(tmp_path, monkeypatch) + for key, value in (("YETO_RL_STORE_S3_ACCESS_KEY_ID", "test"), ("YETO_RL_STORE_S3_SECRET_ACCESS_KEY", "test"), + ("HF_HUB_OFFLINE", "1"), ("HF_HUB_CACHE", str(tmp_path / "hf")), + ("HF_HOME", str(tmp_path / "hf-home"))): + monkeypatch.setenv(key, value) + for key in (s3_store.ENDPOINT_ENV, s3_store.REGION_ENV, s3_store.PROFILE_ENV, "AWS_ENDPOINT_URL", "AWS_PROFILE"): + monkeypatch.setenv(key, "") + monkeypatch.delenv(key) + monkeypatch.setattr(modal_runner, "modal_available", lambda: True) + ordered = [] + monkeypatch.setattr(launcher, "run", lambda *a, **k: ordered.append("run")) + monkeypatch.setattr(cli, "_spawn_worker", lambda *a, **k: ordered.append("spawn")) + monkeypatch.setattr(cli.runs, "create_run", lambda *a, **k: ordered.append("create")) + prepared = [] + real_plan = launcher.dry_run_plan + monkeypatch.setattr(launcher, "dry_run_plan", lambda args: prepared.append(args) or real_plan(args)) + asked = prod_defaults.apply(monkeypatch) + rc, out = prod_defaults.launch_dry_run(_argv(CASES[case], tmp_path)) + assert ordered == [] + return rc, out, (prepared[0] if prepared else None), asked + + +@pytest.mark.parametrize("case", ["examples/run.agentic-262k.json", "examples/run.baremetal-b300-262k.json", + "kit/run.json"]) +def test_the_customer_trainer_launch_passes_with_production_defaults(case, tmp_path, monkeypatch, fake_sky): + rc, out, args, asked = _customer_launch(case, tmp_path, monkeypatch) + assert rc == 0, prod_defaults.refusal(out) + assert args is not None and (asked["hub"] or asked["store"]) # the model preflight ran, in check mode + + +def _entry_argv(run: str, env: dict, module: str = MILES_ENTRY) -> list[str]: + """The island entry argv of a run script, with the shell variables the island's own + environment gives (``$LEARNER_ID``, ``$SYNCER_ADDR``) put in.""" + line = next(line for line in run.splitlines() if f"-m {module}" in line) + tokens = shlex.split(line.split(f"-m {module}", 1)[1]) + tokens = tokens[:next((i for i, t in enumerate(tokens) if t in SHELL_OPERATORS), len(tokens))] + return [env.get(t[1:], t) if t.startswith("$") and t[1:].isidentifier() else t for t in tokens] + + +def _island_parses(run: str, env: dict, monkeypatch, capsys) -> types.SimpleNamespace: + """The island's parser and its compat group, with only ``env`` of what this process + has from conftest (the island runs elsewhere).""" + from yeto.hw.catalog import COMPAT_GROUP_ENV + from yeto.rl.adapters.miles import island_entry + + for name in prod_defaults.CONFTEST_ENV: + monkeypatch.delenv(name, raising=False) + if env.get(COMPAT_GROUP_ENV): + monkeypatch.setenv(COMPAT_GROUP_ENV, str(env[COMPAT_GROUP_ENV])) + argv = _entry_argv(run, env) + try: + args = island_entry.parse_args(argv) + except SystemExit as stop: + raise AssertionError(f"the island entry refused its argv: {capsys.readouterr().err[-2000:]}") from stop + group = island_entry._island_compat_group(args) + return types.SimpleNamespace(args=args, group=group, argv=argv) + + +def _island_task(args): + from yeto.gpu_spec import parse_gpu_spec + from yeto.launch.rl_island_task import make_miles_island_task + from yeto.launcher import _island_overrides, _island_task as island_task + from yeto.rl.engine import sample_roles + + specs = parse_gpu_spec(args.gpu) + return specs[0], island_task(make_miles_island_task, args, specs[0], 0, + sample_roles.syncer_learner_count(args, len(specs)), "10.0.0.1:29400", + _island_overrides(args, specs)) + + +def test_the_customer_modal_island_entry_parses_with_only_its_own_environment(tmp_path, monkeypatch, fake_sky, + capsys): + from yeto.launch.modal_islands import build_modal_island_config + + rc, out, args, _ = _customer_launch("examples/run.agentic-262k.json", tmp_path, monkeypatch) + assert rc == 0, prod_defaults.refusal(out) + spec, task = _island_task(args) + assert spec.cloud == "modal" + cfg = build_modal_island_config(args, spec, 0, task, "10.0.0.1:29400") + island = _island_parses(cfg.run_script, {**cfg.envs, "LEARNER_ID": "0"}, monkeypatch, capsys) + assert island.group == "nvidia-b300" + assert island.args.rl_single_island_no_sync and island.args.inner_lr == float(args.inner_lr) + + +@pytest.mark.parametrize("case", ["examples/run.baremetal-b300-262k.json", "kit/run.json"]) +def test_the_customer_ssh_island_entry_parses_with_only_the_node_environment(case, tmp_path, monkeypatch, fake_sky, + capsys): + from yeto.launch import ssh_trainer_island as sti + from yeto.launch.trainer_provision import ssh_trainer_spec + + rc, out, args, _ = _customer_launch(case, tmp_path, monkeypatch) + assert rc == 0, prod_defaults.refusal(out) + spec, task = _island_task(args) + assert spec.cloud == "ssh" + ssh_spec = ssh_trainer_spec(args, spec, task, name="island-0") + env = sti.node_env(ssh_spec, 0, {}) + script = sti.start_script(ssh_spec, 0, env, sti.remote_paths("r", "island-0", 0), container="c0") + assert "export YETO_RL_COMPAT_GROUP=nvidia-b300" in script # the node's job gets it + island = _island_parses(ssh_spec.run_script, {**env, "LEARNER_ID": "0"}, monkeypatch, capsys) + assert island.group == "nvidia-b300" + + +def test_the_customer_pool_dry_run_and_the_node_spec_pass_with_production_defaults(tmp_path, monkeypatch, capsys): + """``python -m yeto.launch.nc pool --dry-run`` of examples/k31's pool (what run up runs), + then the spec it renders for a node read as ``engine_sampler`` reads it on the node.""" + from test_k31_baremetal_run_up_dry_run import _fill + from yeto.launch.nc import cli as nc_cli + from yeto.rl.engine import engine_sampler_entry as entry + from yeto.rl.engine.rollout_data_path import normalize_spec + + _fill(tmp_path) + config = tmp_path / "pool.nc-mi355x-agentic-262k.json" + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("YETO_NC_ACCOUNTS", "101,102,103,104") + monkeypatch.setenv("YETO_NC_STATE_DIR", str(tmp_path / "nc-state")) + asked = prod_defaults.apply(monkeypatch) + rc = nc_cli.main(["pool", "--config", str(config), "--dry-run"]) + out = capsys.readouterr() + assert rc in (0, None), prod_defaults.refusal(out.out + out.err) + assert asked["store"], "the pool's model check did not run" + from yeto.launch.pool.island_pool import Member + + raw = json.loads(config.read_text()) + pc = nc_cli.pool_config(raw, allowed=None) + member = Member(pc.accounts[0], "", f"{pc.shard_base}-0", + data_slot=f"0/{pc.data_slots}" if pc.data_slots else None) + spec_file = tmp_path / "node-spec.json" # the file the pool uploads; the node reads it back + spec_file.write_text(json.dumps(nc_cli.render_spec(raw, member, [f"{pc.shard_base}-{i}" + for i in range(pc.target)]))) + spec = entry.apply_rollout_quant(normalize_spec(entry.load_spec(spec_file))) + entry.island_config(spec) # the node builds its island config from it before the engine starts + + +# -- a fleet: the compiled trainer argv and each island's own launch ------------------------------ + +FLEETS = ("examples/fleet/run.two-islands.json", "examples/fleet/run.mixed-miles.json") + + +def _fleet(tmp_path, example: str, *, per_island: bool) -> dict: + from test_fleet_island_launches import example_doc + from yeto.rl import up + import test_fleet_island_launches as fleet_tests + + monkeypatched = fleet_tests.EXAMPLE + try: + fleet_tests.EXAMPLE = ROOT / example + doc = example_doc(tmp_path, per_island=per_island) + finally: + fleet_tests.EXAMPLE = monkeypatched + text = json.dumps(doc) + prompts = tmp_path / "prompts.jsonl" + prompts.write_text("".join(json.dumps({"q": f"{i}+1?", "a": str(i + 1)}) + "\n" for i in range(64))) + text = text.replace("", str(prompts)) + path = tmp_path / "run.json" + path.write_text(text) + return up.load_config(str(path)) + + +@pytest.fixture +def fleet_env(monkeypatch): + import yeto.launcher as launcher + import yeto.modal_runner as modal_runner + import yeto.cli as cli + + monkeypatch.setenv("YETO_ISLAND_HMAC_KEY", "fleet-prod-defaults-key") + monkeypatch.setenv("YETO_RL_STORE_S3_ACCESS_KEY_ID", "test-key-id") + monkeypatch.setenv("YETO_RL_STORE_S3_SECRET_ACCESS_KEY", "test-secret") + monkeypatch.setattr(modal_runner, "modal_available", lambda: True) + monkeypatch.setattr(launcher, "run", lambda *a, **k: pytest.fail("a dry run ordered")) + monkeypatch.setattr(cli, "_spawn_worker", lambda *a, **k: pytest.fail("a dry run spawned a worker")) + + +@pytest.mark.parametrize("example", FLEETS) +def test_a_fleet_s_compiled_trainer_argv_passes_with_production_defaults(example, tmp_path, fake_sky, fleet_env, + production_defaults): + cfg = _fleet(tmp_path, example, per_island=False) + asked = production_defaults + rc, out = prod_defaults.launch_dry_run([*cfg["trainer"]["argv"], "--controller", "local"]) + assert rc == 0, prod_defaults.refusal(out) + assert asked["hub"] + + +@pytest.mark.parametrize("example", FLEETS[:1]) # a Miles-sampler island is one launch with its trainer +def test_each_fleet_island_launch_passes_with_production_defaults(example, tmp_path, monkeypatch, fake_sky, + fleet_env, capsys): + """What ``trainer_worker`` runs per island (``python -m yeto.cli launch`` of + ``island_launches.launch_argv``), then that island's entry command parsed with only the + environment its Modal island config gives it.""" + import yeto.launcher as launcher + from yeto.launch.modal_islands import build_modal_island_config + from yeto.rl import fleet, island_launches + + cfg = _fleet(tmp_path, example, per_island=True) + plan = fleet.plan_of(cfg) + asked = prod_defaults.apply(monkeypatch) + rc, out = prod_defaults.launch_dry_run([*cfg["trainer"]["argv"], "--controller", "local"]) # the syncer launch + assert rc == 0, prod_defaults.refusal(out) + prepared = [] + real_plan = launcher.dry_run_plan + monkeypatch.setattr(launcher, "dry_run_plan", lambda args: prepared.append(args) or real_plan(args)) + members = island_launches.trainer_members(cfg, plan) + assert len(members) == len(plan.islands) >= 2 + for member, island in zip(members, plan.islands): + argv = island_launches.launch_argv(member, syncer={"addr": "10.0.0.1:29400", "syncer_epoch": 3}) + rc, out = prod_defaults.launch_dry_run(argv) + assert rc == 0, f"island {island.learner}: {prod_defaults.refusal(out)}" + args = prepared[-1] + spec, task = _island_task(args) + modal = build_modal_island_config(args, spec, 0, task, "10.0.0.1:29400") + parsed = _island_parses(modal.run_script, {**modal.envs, "LEARNER_ID": str(island.learner)}, + monkeypatch, capsys) + assert int(parsed.args.learner_id) == island.learner + assert parsed.group == "nvidia-h100" + assert asked["hub"] + + +def test_a_sky_island_entry_parses_with_only_the_task_environment(tmp_path, monkeypatch, fake_sky, fleet_env, + capsys): + """A sky trainer island (island 0 of the per-island two-island fleet moved to an AWS + cluster): its launch dry run, then the task's run script parsed with only the task's envs.""" + import yeto.launcher as launcher + from yeto.rl import fleet, island_launches + + cfg = _fleet(tmp_path, FLEETS[0], per_island=True) + member = dict(island_launches.trainer_members(cfg, fleet.plan_of(cfg))[0], gpu="aws:1x2xh100@us-east-2") + prepared = [] + real_plan = launcher.dry_run_plan + monkeypatch.setattr(launcher, "dry_run_plan", lambda args: prepared.append(args) or real_plan(args)) + prod_defaults.apply(monkeypatch) + rc, out = prod_defaults.launch_dry_run(island_launches.launch_argv(member, syncer={"addr": "10.0.0.1:29400"})) + assert rc == 0, prod_defaults.refusal(out) + spec, task = _island_task(prepared[-1]) + assert spec.cloud == "aws" + envs = {**task.envs, **{k: str(v) for k, v in (getattr(task, "secrets", None) or {}).items()}} + parsed = _island_parses(task.run, {**envs, "LEARNER_ID": "0", "SYNCER_ADDR": "10.0.0.1:29400"}, + monkeypatch, capsys) + assert parsed.group == "nvidia-h100" + + +def test_a_missing_model_passes_under_conftest_and_is_refused_with_production_defaults(tmp_path, monkeypatch, + fake_sky, fleet_env): + """The model preflight half of the image smoke's miss: conftest's YETO_PREFLIGHT_MODEL=off + lets a launch whose model the Hub does not have pass; production refuses it before any + order, so a rendered argv that must skip the check has to carry --preflight-model off.""" + from yeto.launch import model_check + + argv = [*_fleet(tmp_path, FLEETS[0], per_island=False)["trainer"]["argv"], "--controller", "local"] + prod_defaults.apply(monkeypatch) + monkeypatch.setattr(model_check, "hub_files", lambda repo, revision: ([], lambda name: None)) # no such files + rc, out = prod_defaults.launch_dry_run(argv) + assert rc != 0 and "trainer model" in out, prod_defaults.refusal(out) + rc, out = prod_defaults.launch_dry_run([*argv, "--preflight-model", "off"]) + assert rc == 0, prod_defaults.refusal(out) + monkeypatch.setenv(model_check.MODE_ENV, "off") # what conftest sets for every test + rc, out = prod_defaults.launch_dry_run(argv) + assert rc == 0, prod_defaults.refusal(out) From 999257a6cf076921523225e0b2c374aa92168239 Mon Sep 17 00:00:00 2001 From: Michael Chung Date: Fri, 27 Nov 2026 00:00:54 +0800 Subject: [PATCH 2/2] tests: the pool dry-run test brings its own NC tool stubs The pool dry run checks with shutil.which that nc-manage and nc-query are on this host; the test took them from the developer's PATH, so it passed locally and failed on the CI runner, which has neither. The test now points NC_MANAGE / NC_QUERY at executable stubs in its tmp dir (recording any call, which the dry run must not make) and clears NC_TOOL_DIR / NC_NODE_BIN. The refusal summary also lists the pool's "problem:" lines. Co-Authored-By: Claude Opus 5.5 --- tests/prod_defaults.py | 2 +- tests/test_prod_defaults_argv.py | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/tests/prod_defaults.py b/tests/prod_defaults.py index 3c0d838a1..0954656e5 100644 --- a/tests/prod_defaults.py +++ b/tests/prod_defaults.py @@ -114,7 +114,7 @@ def refusal(text: str, limit: int = 40) -> str: import re marks = re.compile(r"INVALID|refus|rejected|required|the following arguments|error|Error|cannot|must |" - r"Traceback|SystemExit|inner-lr|preflight", re.I) + r"Traceback|SystemExit|inner-lr|preflight|problem", re.I) lines = [line for line in text.splitlines() if marks.search(line)] return "\n".join(lines[:limit]) or text[-3000:] diff --git a/tests/test_prod_defaults_argv.py b/tests/test_prod_defaults_argv.py index 64bba606f..c3521afa0 100644 --- a/tests/test_prod_defaults_argv.py +++ b/tests/test_prod_defaults_argv.py @@ -235,10 +235,23 @@ def test_the_customer_pool_dry_run_and_the_node_spec_pass_with_production_defaul monkeypatch.setenv("HOME", str(tmp_path / "home")) monkeypatch.setenv("YETO_NC_ACCOUNTS", "101,102,103,104") monkeypatch.setenv("YETO_NC_STATE_DIR", str(tmp_path / "nc-state")) + # The dry run checks that the NC tools are on this host (shutil.which) and runs neither: + # stubs of its own, not whatever this host has on PATH (a CI runner has none). A stub + # that runs records it. + called = tmp_path / "nc-tool-called" + for tool, env in (("nc-manage", "NC_MANAGE"), ("nc-query", "NC_QUERY")): + stub = tmp_path / "bin" / tool + stub.parent.mkdir(exist_ok=True) + stub.write_text(f"#!/bin/sh\necho {tool} \"$@\" >> {shlex.quote(str(called))}\nexit 1\n") + stub.chmod(0o755) + monkeypatch.setenv(env, str(stub)) + for env in ("NC_TOOL_DIR", "NC_NODE_BIN"): + monkeypatch.delenv(env, raising=False) asked = prod_defaults.apply(monkeypatch) rc = nc_cli.main(["pool", "--config", str(config), "--dry-run"]) out = capsys.readouterr() assert rc in (0, None), prod_defaults.refusal(out.out + out.err) + assert not called.exists(), f"the pool dry run ran an NC tool: {called.read_text()}" assert asked["store"], "the pool's model check did not run" from yeto.launch.pool.island_pool import Member