"""Cover TEA training options and compatibility through the governance route. Fixtures: training_client uses a temporary job directory and captures subprocess launches. Fails if request options stop controlling argv, the child environment, or persisted state. """ import json import os import sys from types import SimpleNamespace import pytest from flask import Flask from webapi import training_jobs from webapi.blueprints.governance import governance_bp TRAIN_URL = "/governance/model-versions/tea/eeg/train-jobs" @pytest.fixture def training_client(tmp_path, monkeypatch): """Capture training launches. Real subprocesses would bypass the captured argv and environment.""" for variable in (*training_jobs.REFERENCE_ENV.values(), "TEA_REFERENCE_ROOT", "DASK_SCHEDULER_ADDRESS", "EEG_ANALYSIS_CLUSTER"): monkeypatch.delenv(variable, raising=False) monkeypatch.setenv("INDICADORES_DIR", str(tmp_path)) launches = [] def popen(argv, **kwargs): launches.append((argv[4:], kwargs["env"])) return SimpleNamespace(pid=os.getpid()) monkeypatch.setattr(training_jobs.subprocess, "Popen", popen) app = Flask(__name__) app.register_blueprint(governance_bp, url_prefix="/governance") return app.test_client(), launches def test_body_overrides_reference_environment(training_client, monkeypatch, tmp_path): """Pin body precedence and persisted choices. Fail if an override or flag is lost.""" client, launches = training_client monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path)) monkeypatch.setenv("TEA_REFERENCE_NAME", "fallback") monkeypatch.setenv("TEA_REFERENCE_DIR", str(tmp_path / "fallback")) monkeypatch.setenv("TEA_REFERENCE_AGES", str(tmp_path / "fallback.csv")) monkeypatch.setenv("TEA_REFERENCE_LINE_HZ", "60") body = { "reference_name": "cohort-1", "reference_dir": str(tmp_path / "cohort"), "reference_ages": str(tmp_path / "ages.csv"), "line_hz": 50, "promote": False, "cluster": {"mode": "local"}, } response = client.post(TRAIN_URL, json=body) assert response.status_code == 202 job = response.json["job"] assert job["cluster"] == body["cluster"] argv, _ = launches[0] assert argv == [ sys.executable, "-m", "models", "run", "tea", "eeg", "--environment", "prod", "--train", "--reference-dir", body["reference_dir"], "--reference-ages", body["reference_ages"], "--line-hz", "50", "--reference-name", "cohort-1", ] folder = tmp_path / "entrenamientos" / job["id"] saved = json.loads((folder / "job.json").read_text()) assert saved["parameters"] == {key: value for key, value in body.items() if key != "cluster"} assert saved["cluster"] == body["cluster"] assert client.get(f"/governance/training-jobs/{job['id']}").json["job"]["cluster"] == body["cluster"] def test_reference_name_can_be_passed_without_a_directory(training_client): """Pin a name-only request. Fail if the flag becomes conditional on a reference directory.""" client, launches = training_client response = client.post(TRAIN_URL, json={"reference_name": "cohort-1", "promote": True}) assert response.status_code == 202 argv, _ = launches[0] assert argv[-2:] == ["--reference-name", "cohort-1"] assert "--reference-dir" not in argv assert "--promote" in argv @pytest.mark.parametrize("cluster,mode,scheduler", [ (None, "remote", "tcp://inherited:8786"), ({"mode": "auto"}, "remote", "tcp://inherited:8786"), ({"mode": "local"}, "local", None), ({"mode": "sync"}, "sync", "tcp://inherited:8786"), ({"mode": "remote"}, "remote", "tcp://inherited:8786"), ({"mode": "remote", "scheduler": "tcp://chosen:8786"}, "remote", "tcp://chosen:8786"), ]) def test_cluster_changes_only_the_child_environment(training_client, monkeypatch, cluster, mode, scheduler): """Pin cluster variables and scheduler fallback. Fail if mode leaks into argv or the parent.""" client, launches = training_client monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "remote") monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://inherited:8786") response = client.post(TRAIN_URL, json={"cluster": cluster} if cluster else {}) assert response.status_code == 202 choice = {"mode": "remote", "scheduler": scheduler} if cluster == {"mode": "remote"} else cluster assert response.json["job"]["cluster"] == choice argv, env = launches[0] assert argv == [sys.executable, "-m", "models", "run", "tea", "eeg", "--environment", "prod", "--train", "--promote"] assert env["EEG_ANALYSIS_CLUSTER"] == mode assert env.get("DASK_SCHEDULER_ADDRESS") == scheduler assert os.environ["EEG_ANALYSIS_CLUSTER"] == "remote" assert os.environ["DASK_SCHEDULER_ADDRESS"] == "tcp://inherited:8786" @pytest.mark.parametrize("field", ["reference_dir", "reference_ages"]) def test_reference_paths_must_resolve_inside_root(training_client, monkeypatch, tmp_path, field): """Pin containment after symlink resolution. Fail if a local path can escape the root.""" client, launches = training_client root = tmp_path / "reference" root.mkdir() (root / "escape").symlink_to(tmp_path, target_is_directory=True) monkeypatch.setenv("TEA_REFERENCE_ROOT", str(root)) response = client.post(TRAIN_URL, json={field: str(root / "escape")}) assert response.status_code == 400 assert field in response.json["error"] assert not launches def test_remote_reference_can_be_outside_root(training_client, monkeypatch, tmp_path): """Pin the remote path exemption. Fail if worker paths are rejected by the API root check.""" client, launches = training_client monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path)) response = client.post(TRAIN_URL, json={ "reference_dir": "/worker/reference", "cluster": {"mode": "remote", "scheduler": "tcp://chosen:8786"}, }) assert response.status_code == 202 assert "/worker/reference" in launches[0][0] def test_remote_requires_a_scheduler(training_client): """Pin the missing-scheduler response. Fail if an unconfigured remote job starts.""" client, launches = training_client response = client.post(TRAIN_URL, json={"cluster": {"mode": "remote"}}) assert response.status_code == 400 assert "DASK_SCHEDULER_ADDRESS" in response.json["error"] assert not launches @pytest.mark.parametrize("request_options", [{}, {"json": {}}]) def test_empty_body_keeps_environment_defaults(training_client, monkeypatch, tmp_path, request_options): """Pin launch defaults and the progress folder. Fail if either is lost for an empty request.""" client, launches = training_client monkeypatch.setenv("TEA_REFERENCE_DIR", "/reference") monkeypatch.setenv("TEA_REFERENCE_AGES", "/reference/ages.csv") monkeypatch.setenv("TEA_REFERENCE_LINE_HZ", "50") response = client.post(TRAIN_URL, **request_options) assert response.status_code == 202 assert response.json["job"]["cluster"] is None argv, env = launches[0] folder = tmp_path / "entrenamientos" / response.json["job"]["id"] assert env == {**os.environ, "RUN_PROGRESS_DIR": str(folder)} assert argv == [ sys.executable, "-m", "models", "run", "tea", "eeg", "--environment", "prod", "--train", "--promote", "--reference-dir", "/reference", "--reference-ages", "/reference/ages.csv", "--line-hz", "50", ] @pytest.mark.parametrize("body", [ {"reference_name": "nested/cohort"}, {"reference_name": "a" * 65}, {"reference_dir": "relative"}, {"line_hz": 55}, {"promote": "false"}, {"cluster": {"mode": "unknown"}}, [], ]) def test_invalid_body_options_are_rejected(training_client, body): """Pin JSON and option validation. Fail if an invalid value reaches the subprocess.""" client, launches = training_client response = client.post(TRAIN_URL, json=body) assert response.status_code == 400 assert response.json["error"] assert not launches def test_a_named_cohort_is_trained_from_its_folder_and_ages(training_client, monkeypatch, tmp_path): """Pin that a cohort name with a folder under `TEA_REFERENCE_ROOT` launches with that folder, its `edades.csv` and the chosen line frequency. Fail if the name stays a bare label, which the child rejects without a directory.""" client, launches = training_client cohort = tmp_path / "tiny" cohort.mkdir() (cohort / "edades.csv").write_text("archivo,edad_meses\na.edf,20\n") monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path)) response = client.post(TRAIN_URL, json={"reference_name": "tiny", "line_hz": 50, "promote": False}) assert response.status_code == 202 argv, _ = launches[0] assert argv[argv.index("--reference-dir") + 1] == str(cohort.resolve()) assert argv[argv.index("--reference-ages") + 1] == str((cohort / "edades.csv").resolve()) assert argv[argv.index("--line-hz") + 1] == "50" assert argv[argv.index("--reference-name") + 1] == "tiny" def test_an_explicit_directory_wins_over_the_cohort_folder(training_client, monkeypatch, tmp_path): """Pin that a request giving `reference_dir` is never redirected to the cohort named beside it. Fail if resolving a name overrides a directory the caller chose.""" client, launches = training_client (tmp_path / "tiny").mkdir() (tmp_path / "other").mkdir() monkeypatch.setenv("TEA_REFERENCE_ROOT", str(tmp_path)) client.post(TRAIN_URL, json={"reference_name": "tiny", "reference_dir": str(tmp_path / "other")}) argv, _ = launches[0] assert argv[argv.index("--reference-dir") + 1] == str((tmp_path / "other").resolve()) assert "--reference-ages" not in argv