Compare commits

..

1 Commits

5 changed files with 28 additions and 103 deletions
+4 -51
View File
@@ -113,13 +113,13 @@ REPORTS = {"technical_validation_report_uri": "docs/tecnica.pdf", "clinical_vali
def test_model_version_lifecycle_over_http(client):
"""A version registered over HTTP carries no saved model, so it can't be promoted; trained ones can, and promoting
the second retires the first. Fails if the ML-01b check starts trusting what's declared over the API, or promotion
stops retiring the previous version."""
"""A version registered over HTTP carries no routine records or model, so it can't be promoted; trained ones can,
and promoting the second retires the first. Fails if the ML-01a/ML-01b checks start trusting what's declared
over the API, or promotion stops retiring the previous version."""
declared = _register(client, "v0", scenario="lifecycle")
checks = client.get(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/checks").get_json()
assert checks["ready"] is False
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01b"]
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01a", "ML-01b"]
blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/promote")
assert blocked.status_code == 409 and any(not c["passed"] for c in blocked.get_json()["checks"])
@@ -448,50 +448,3 @@ def test_bad_notebook_runs_are_refused(client, notebooks, fields, notebook):
refused before anything runs. Fails if `/experiments` stops checking any of them."""
response = _run(client, notebook or _notebook("1"), **fields)
assert response.status_code in (400, 404)
def _run_template(client, template, *, scenario):
form = {"template": template, "domain": "cacu", "scenario": scenario, "url": "cacu/cohorte_vigilancia",
"source": "dbt", "build": "4"}
return client.post("/governance/experiments", data=form, content_type="multipart/form-data")
def test_the_notebooks_kept_in_the_code_are_listed_with_their_scenarios(client, notebooks):
"""Fails if `/notebook-templates` stops listing the notebooks under `models/<domain>/<scenario>/notebooks/` or the
scenarios each can run for."""
found = {t["id"]: t for t in client.get("/governance/notebook-templates", query_string={"domain": "cacu"})
.get_json()["templates"]}
assert "cin2_pim_post_colposcopy" in found["cacu/cin2_pim/reporte_subgrupos"]["scenarios"]
assert found["cacu/survival/reporte_subgrupos"]["scenarios"] == ["survival"]
def test_a_template_runs_like_an_upload_with_the_notebook_read_from_the_code(client, notebooks, monkeypatch):
"""Pins down: a template answers 202 with a run whose notebook is the template's, read from the code (the run
itself is left queued here). Fails if the request's notebook could stand in for the template or the run loses its
name."""
from models.reports.rendering import notebook_sha256
from models.reports.templates import template_notebook
from webapi.blueprints import governance
monkeypatch.setattr(governance, "submit", lambda job, *args: None)
started = _run_template(client, "cacu/cin2_pim/reporte_subgrupos", scenario="cin2_pim_post_colposcopy")
assert started.status_code == 202, started.get_json()
run = started.get_json()
assert run["notebook"] == "reporte_subgrupos" and run["scenario"] == "cin2_pim_post_colposcopy"
assert run["notebook_sha256"] == notebook_sha256(template_notebook("cacu/cin2_pim/reporte_subgrupos")[1])
@pytest.mark.parametrize("template, scenario, status", [
("cacu/survival/reporte_subgrupos", "cin2_pim", 400), # not a scenario it serves
("cacu/../../etc/passwd", "cin2_pim", 400), # not a template id
("cacu/cin2_pim/no_existe", "cin2_pim", 404), # no such template
])
def test_a_template_that_does_not_serve_the_run_is_refused(client, notebooks, template, scenario, status):
"""Fails if a template runs for a scenario it doesn't serve, or an id reaches a file outside the templates."""
assert _run_template(client, template, scenario=scenario).status_code == status
def test_a_file_and_a_template_together_are_refused(client, notebooks):
"""Fails if a request with both a file and a template runs either."""
response = _run(client, _notebook("1"), template="cacu/survival/reporte_subgrupos", scenario="survival")
assert response.status_code == 400
+9
View File
@@ -125,6 +125,15 @@ def test_the_menu_offers_the_scenarios_with_a_summary_row_and_enough_patients(li
assert live_client.get("/cama/modelo/escenarios?paciente=500").status_code == 422
def test_a_patient_in_no_drawable_scenario_gets_no_default(live_client):
"""Pins down: a patient who belongs to none of the scenarios on the menu (patient 150 is outside `< 45 años`) gets
`predeterminado: null` while the menu is still offered. Fails if the default falls back to the first scenario and the dashboard
draws another subgroup's curve on her record."""
menu = live_client.get("/cama/modelo/escenarios?paciente=150").get_json()
assert menu["predeterminado"] is None and menu["escenarios"] == [{"nombre": "< 45 años", "n": 100}]
def test_a_scenarios_figure_comes_with_its_risk_factors_and_the_answer_is_kept(live_client):
"""Pins down: `POST /cama/modelo/curvas/consulta` returns the figure of the named scenario with its summary row (the risk-factor
label) and the version that scored it, and the same scenario a second time is answered without computing again; a scenario with
Generated
+3 -19
View File
@@ -1414,8 +1414,8 @@ name = "httpcore2"
version = "2.16.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "h11", marker = "sys_platform != 'emscripten'" },
{ name = "truststore", marker = "sys_platform != 'emscripten'" },
{ name = "h11" },
{ name = "truststore" },
]
sdist = { url = "https://files.pythonhosted.org/packages/92/9d/df40b41f7db0370f82019820709244e7b660c52aa3da3c9e5c4e8141f6e6/httpcore2-2.16.2.tar.gz", hash = "sha256:6c519d0f7b44f7269fa9bbb4d2763db395a4a2370f046d8e8e0a4b38227815d2", size = 70064, upload-time = "2026-11-16T10:12:19.491Z" }
wheels = [
@@ -2211,7 +2211,6 @@ seer-survival = [
]
survival-curves = [
{ name = "mpmath" },
{ name = "plotly" },
{ name = "scipy" },
]
@@ -2233,7 +2232,6 @@ requires-dist = [
{ name = "pandera", specifier = ">=0.20" },
{ name = "persistance", editable = "../Persistance" },
{ name = "pgmpy", marker = "extra == 'seer-survival'", specifier = ">=1.0" },
{ name = "plotly", marker = "extra == 'survival-curves'", specifier = ">=5.18" },
{ name = "pyarrow", specifier = ">=15" },
{ name = "scikit-learn", specifier = ">=1.4" },
{ name = "scipy", marker = "extra == 'seer-survival'", specifier = ">=1.11" },
@@ -2254,7 +2252,6 @@ dev = [
{ name = "nbconvert", specifier = ">=7.16" },
{ name = "networkx", specifier = ">=3.0" },
{ name = "pgmpy", specifier = ">=1.0" },
{ name = "plotly", specifier = ">=5.18" },
{ name = "pytest", specifier = ">=8.0.0" },
{ name = "reportlab", specifier = ">=4.0" },
{ name = "scipy", specifier = ">=1.11" },
@@ -2952,7 +2949,7 @@ name = "pexpect"
version = "4.9.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "ptyprocess", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" },
{ name = "ptyprocess" },
]
sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450, upload-time = "2023-11-25T09:07:26.339Z" }
wheels = [
@@ -3062,19 +3059,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/45/b8/fd1af06b079af236f5423f7c1821264419cc8f6b4803f79353acbb8bfa53/platformdirs-4.13.3-py3-none-any.whl", hash = "sha256:f6ad7f447f24f8a3b82cce5976387428bff894a0eca6c3488f4a17f153c130c4", size = 32762, upload-time = "2026-10-16T01:16:15.051Z" },
]
[[package]]
name = "plotly"
version = "7.1.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "narwhals" },
{ name = "packaging" },
]
sdist = { url = "https://files.pythonhosted.org/packages/49/c3/72b369f5ed7701b04ab0ea3dcf83e9bbce71c0b3bc6f07f87568550d09ea/plotly-7.1.0.tar.gz", hash = "sha256:f860166a4a3d78c69cb1f4a15f28a5c8283eade98a282a698f3bb853a449ace5", size = 6689315, upload-time = "2026-09-15T19:21:21.75Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e5/7d/905a3a3d51087515719058c94cfbda2ff0fc14417c20d557ae3e82d8b250/plotly-7.1.0-py3-none-any.whl", hash = "sha256:dbb7fa18afce40d0a8e80d1bf162eceb3faa0ce5a77fe741ad09a74cf78f53f3", size = 9692368, upload-time = "2026-09-15T19:21:18.331Z" },
]
[[package]]
name = "pluggy"
version = "1.6.0"
+9 -31
View File
@@ -228,15 +228,6 @@ def list_cohort_files():
return jsonify({"builds": exported_builds(_cohorts_root(domain), domain)})
@governance_bp.get("/notebook-templates")
def list_notebook_templates():
"""`?domain=`: the notebooks kept in the code (`models/<domain>/<scenario>/notebooks/`), with the scenarios each can
run for; `POST /experiments` runs one by its `id` as `template`."""
from models.reports.templates import notebook_templates
return jsonify({"templates": notebook_templates(request.args.get("domain") or None)})
@governance_bp.get("/experiments")
def list_experiments():
"""Notebook runs, newest first; `?domain=` and `?domain=&scenario=` narrow them."""
@@ -246,18 +237,13 @@ def list_experiments():
@governance_bp.post("/experiments")
def run_experiment():
"""Multipart `file` (a .ipynb) or `template` (the id of a notebook kept in the code, `/notebook-templates`), `domain`,
`scenario`, `url`, `source` (kit|dbt), `build` and optionally `version`: runs the notebook on that build's file in
the background and answers 202 with the run, still `en_curso`. A template is read from the code, never from the
request, and must be of the domain and serve the scenario."""
"""Multipart `file` (a .ipynb), `domain`, `scenario`, `url`, `source` (kit|dbt), `build` and optionally `version`:
runs the notebook on that build's file in the background and answers 202 with the run, still `en_curso`."""
upload = request.files.get("file")
form = request.form
template = form.get("template") or None
missing = [k for k in ("domain", "scenario", "url", "source", "build") if not form.get(k)]
if (upload is None and template is None) or missing:
return jsonify({"error": f"faltan campos: {(['file o template'] if upload is None and template is None else []) + missing}"}), 400
if upload is not None and template is not None:
return jsonify({"error": "elige un archivo o una plantilla, no ambos"}), 400
if upload is None or missing:
return jsonify({"error": f"faltan campos: {(['file'] if upload is None else []) + missing}"}), 400
domain, scenario, version = form["domain"], form["scenario"], form.get("version") or None
url = form["url"]
if url.split("/", 1)[0] != domain:
@@ -265,21 +251,13 @@ def run_experiment():
if not form["build"].isdigit():
return jsonify({"error": "build debe ser un número"}), 400
path = build_file(_cohorts_root(domain), url, form["source"], int(form["build"]))
if template is not None:
from models.reports.templates import notebook_templates, template_notebook
name, notebook = template_notebook(template)
found = {t["id"]: t for t in notebook_templates(domain)}.get(template)
if found is None or scenario not in found["scenarios"]:
return jsonify({"error": f"la plantilla {template!r} no corre para {domain}/{scenario}"}), 400
else:
try:
notebook = experiment.check_notebook(json.loads(upload.read()))
except (UnicodeDecodeError, json.JSONDecodeError):
return jsonify({"error": "el archivo no es un notebook de Jupyter (.ipynb)"}), 400
name = experiment.notebook_name(upload.filename or "notebook")
try:
notebook = experiment.check_notebook(json.loads(upload.read()))
except (UnicodeDecodeError, json.JSONDecodeError):
return jsonify({"error": "el archivo no es un notebook de Jupyter (.ipynb)"}), 400
if version:
registry.get(domain, scenario, version)
name = experiment.notebook_name(upload.filename or "notebook")
run_id = experiment.start(notebook, name, path, domain, scenario, version)
submit(experiment.execute, run_id, notebook, name, path, domain, scenario, version)
return jsonify(experiment.describe(run_id)), 202
+3 -2
View File
@@ -100,7 +100,7 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
def scenarios_menu():
"""The clinical scenarios the menu offers: those with a row in the version's summary and enough patients over the data
ingested so far to draw, in the pipeline's order, with their patients; `?paciente=<pac_id>` also names the one she
belongs to first as the default. 404 while there is no version in production."""
belongs to first as the default (`null` when she is in none). 404 while there is no version in production."""
from models.cama.survival import live
try:
@@ -117,7 +117,8 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
mine = live.patient_scenarios(labelled, int(paciente))
except live.QueryError as error:
return jsonify({"error": str(error)}), 422
default = next((m["nombre"] for m in menu if m["nombre"] in mine), default)
# Belonging to no drawable scenario leaves no default: showing another subgroup's curve would misdescribe her.
default = next((m["nombre"] for m in menu if m["nombre"] in mine), None)
return jsonify({"modelo": {"nombre": f"{domain}-{scenario}", "version": str(version)}, "escenarios": menu, "predeterminado": default})
@blueprint.post("/modelo/curvas/consulta")