Files
WebApi/tests/test_training_jobs.py
T

104 lines
5.5 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
@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