129 lines
6.9 KiB
Python
129 lines
6.9 KiB
Python
"""What this module covers: the scenarios governance can train and the background training jobs (`webapi.training_jobs`
|
|
and their routes in `webapi.blueprints.governance`): the catalog, a job's states (running, completed, failed, trained but
|
|
not promoted, interrupted), and the refusal to start a second job of a scenario that is running.
|
|
|
|
Fixtures: `app_client`, the governance blueprint on a bare Flask app with `INDICADORES_DIR` in a temporary folder and the
|
|
job's command replaced by a Python one-liner the test chooses, so no model is trained. `esperar` waits for a job to leave
|
|
`en_curso`.
|
|
"""
|
|
|
|
import sys
|
|
import time
|
|
|
|
import pytest
|
|
from flask import Flask
|
|
|
|
from webapi import training_jobs
|
|
from webapi.blueprints.governance import governance_bp
|
|
|
|
|
|
@pytest.fixture
|
|
def app_client(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("INDICADORES_DIR", str(tmp_path))
|
|
monkeypatch.setenv("DBT_MANIFEST", str(tmp_path / "manifest.json"))
|
|
app = Flask(__name__)
|
|
app.register_blueprint(governance_bp, url_prefix="/governance")
|
|
with app.test_client() as client:
|
|
yield client
|
|
|
|
|
|
def _command_that(code: str):
|
|
return lambda domain, scenario: [sys.executable, "-c", code]
|
|
|
|
|
|
def esperar(client, job_id, timeout=20):
|
|
deadline = time.time() + timeout
|
|
while time.time() < deadline:
|
|
job = client.get(f"/governance/training-jobs/{job_id}").get_json()["job"]
|
|
if job["estado"] != "en_curso":
|
|
return job
|
|
time.sleep(0.1)
|
|
raise AssertionError("the job did not finish")
|
|
|
|
|
|
def test_the_catalog_lists_the_trainable_scenarios_and_not_the_pipeline_settings():
|
|
"""Pins down: every scenario with its own `model.toml` and a cohort is listed (CaCu, CaMa), TEA's EEG is listed as
|
|
trained on its reference, and the SEER pipeline's settings file is not a scenario. Fails if a scenario stops being
|
|
discoverable or a settings file starts showing as one."""
|
|
entries = {(s["domain"], s["scenario"]): s for s in training_jobs.catalog()}
|
|
|
|
assert ("cama", "survival") in entries and ("cacu", "cin2_logistic") in entries
|
|
assert entries[("tea", "eeg")]["kind"] == "referencia" and entries[("cama", "survival")]["kind"] == "cohorte"
|
|
assert ("cama", "seer_survival") not in entries
|
|
assert entries[("cama", "recurrence")]["kind"] == "cohorte" # the patients loaded from METABRIC and SCAN-B
|
|
|
|
|
|
@pytest.mark.parametrize("code,estado", [
|
|
("print('trained: version 4')", "completado"),
|
|
("import sys; print('boom', file=sys.stderr); sys.exit(1)", "fallido"),
|
|
("import sys; print('version 4 not promoted, missing MLD-01', file=sys.stderr); sys.exit(1)", "entrenado_sin_promover"),
|
|
])
|
|
def test_a_job_ends_as_completed_failed_or_trained_without_promotion(app_client, monkeypatch, code, estado):
|
|
"""Pins down: the job's state comes from its exit code and its error output, and carries both outputs. Fails if a
|
|
failure is shown as done, or a version that only lacks its reports is shown as failed."""
|
|
monkeypatch.setattr(training_jobs, "_command", _command_that(code))
|
|
|
|
started = app_client.post("/governance/model-versions/cama/survival/train-jobs")
|
|
job = esperar(app_client, started.get_json()["job"]["id"])
|
|
|
|
assert started.status_code == 202 and job["estado"] == estado
|
|
assert ("trained" in job["salida"]) or ("boom" in job["error"]) or ("not promoted" in job["error"])
|
|
|
|
|
|
def test_a_second_job_of_a_running_scenario_is_refused_with_the_running_one(app_client, monkeypatch):
|
|
"""Pins down: while a scenario's job runs, starting another answers 409 with that job, and another scenario still
|
|
starts. Fails if two trainings of one model can run at once, which would register the same version twice."""
|
|
monkeypatch.setattr(training_jobs, "_command", _command_that("import time; time.sleep(3)"))
|
|
first = app_client.post("/governance/model-versions/cama/survival/train-jobs")
|
|
again = app_client.post("/governance/model-versions/cama/survival/train-jobs")
|
|
other = app_client.post("/governance/model-versions/cacu/cin2_logistic/train-jobs")
|
|
|
|
assert first.status_code == 202 and again.status_code == 409
|
|
assert again.get_json()["job"]["id"] == first.get_json()["job"]["id"]
|
|
assert other.status_code == 202
|
|
|
|
|
|
def test_a_job_whose_process_is_gone_without_an_exit_code_is_interrupted(app_client, tmp_path):
|
|
"""Pins down: a job file with no exit file and a dead process reads `interrumpido`, not `en_curso` forever. Fails if
|
|
a killed worker leaves its job running in the list."""
|
|
folder = tmp_path / "entrenamientos" / "20260101T000000-aaaaaa"
|
|
folder.mkdir(parents=True)
|
|
(folder / "job.json").write_text('{"id": "20260101T000000-aaaaaa", "domain": "cama", "scenario": "survival", '
|
|
'"pid": 2147483646, "iniciado": "2026-01-01T00:00:00+00:00"}')
|
|
|
|
assert app_client.get("/governance/training-jobs/20260101T000000-aaaaaa").get_json()["job"]["estado"] == "interrumpido"
|
|
assert [j["id"] for j in app_client.get("/governance/training-jobs").get_json()["jobs"]] == ["20260101T000000-aaaaaa"]
|
|
|
|
|
|
def test_an_unknown_scenario_or_job_is_a_404_and_no_manifest_is_a_503(app_client, monkeypatch):
|
|
"""Pins down: starting an unknown scenario, or reading an unknown job, is a 404; a cohort scenario with no dbt
|
|
manifest configured is a 503 and starts nothing. Fails if either becomes a 500 or starts a process."""
|
|
assert app_client.post("/governance/model-versions/cama/nope/train-jobs").status_code == 404
|
|
assert app_client.get("/governance/training-jobs/nada").status_code == 404
|
|
monkeypatch.delenv("DBT_MANIFEST")
|
|
assert app_client.post("/governance/model-versions/cama/survival/train-jobs").status_code == 503
|
|
|
|
|
|
def test_tea_trains_on_a_local_reference_folder_when_one_is_configured(monkeypatch):
|
|
"""Pins down: with `TEA_REFERENCE_DIR` (and its ages table) set, TEA's job passes them to `models run`, and CaMa's job
|
|
never does. Fails if the folder is ignored, which would send the training to storage the machine cannot reach."""
|
|
monkeypatch.setenv("DBT_MANIFEST", "m.json")
|
|
monkeypatch.setenv("TEA_REFERENCE_DIR", "/referencia")
|
|
monkeypatch.setenv("TEA_REFERENCE_AGES", "/referencia/edades.csv")
|
|
|
|
tea = training_jobs._command("tea", "eeg")
|
|
cama = training_jobs._command("cama", "survival")
|
|
|
|
assert tea[tea.index("--reference-dir") + 1] == "/referencia" and tea[tea.index("--reference-ages") + 1] == "/referencia/edades.csv"
|
|
assert "--manifest" not in tea and "--reference-dir" not in cama
|
|
|
|
|
|
def test_cama_recurrence_trains_on_the_cohort_export_like_survival(monkeypatch):
|
|
"""Pins down: CaMa's recurrence scenario, trained on the patients loaded from METABRIC and SCAN-B, is started with the
|
|
cohort export and the dbt manifest, as survival is. Fails if it is run without a database build, which would leave it
|
|
with no patients."""
|
|
monkeypatch.setenv("DBT_MANIFEST", "m.json")
|
|
|
|
recurrence = training_jobs._command("cama", "recurrence")
|
|
|
|
assert "--export" in recurrence and recurrence[recurrence.index("--manifest") + 1] == "m.json" |