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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")


Expand Down Expand Up @@ -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")


Expand Down Expand Up @@ -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)."""
Expand Down
120 changes: 120 additions & 0 deletions tests/prod_defaults.py
Original file line number Diff line number Diff line change
@@ -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 <argv> --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|problem", re.I)
lines = [line for line in text.splitlines() if marks.search(line)]
return "\n".join(lines[:limit]) or text[-3000:]

Loading
Loading