From 6be42748acba7cd9bb70742a6a678e68fb841ce5 Mon Sep 17 00:00:00 2001 From: edgar Date: Sat, 21 Nov 2026 22:30:38 -0600 Subject: [PATCH] Governance: run the notebooks kept in the code; plotly in the lock for the survival reports GET /governance/notebook-templates?domain= lists the notebooks under models///notebooks/ with the scenarios each can run for (models.reports.templates: its folder's and any whose model.toml lists a module of it, so CaCu's PIM subgroup report serves cin2_pim and its post-colposcopy and post-treatment scenarios). POST /governance/experiments takes `template` (that id) instead of `file`: the notebook is read from the code, never from the request, and runs like an upload (its page sandboxed, its hash on the run). A template for a scenario it doesn't serve, an id outside the templates, or a file and a template together are refused. uv.lock adds plotly 7.1.0: models' `survival-curves` extra now draws the CaCu subgroup reports (models: cacu-survival/integration). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7 --- tests/test_governance_endpoints.py | 47 ++++++++++++++++++++++++++++++ uv.lock | 22 ++++++++++++-- webapi/blueprints/governance.py | 40 +++++++++++++++++++------ 3 files changed, 97 insertions(+), 12 deletions(-) diff --git a/tests/test_governance_endpoints.py b/tests/test_governance_endpoints.py index a342599..a7d2671 100644 --- a/tests/test_governance_endpoints.py +++ b/tests/test_governance_endpoints.py @@ -448,3 +448,50 @@ 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///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 diff --git a/uv.lock b/uv.lock index def2cb1..71ab4dd 100644 --- a/uv.lock +++ b/uv.lock @@ -1414,8 +1414,8 @@ name = "httpcore2" version = "2.16.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "h11" }, - { name = "truststore" }, + { name = "h11", marker = "sys_platform != 'emscripten'" }, + { name = "truststore", marker = "sys_platform != 'emscripten'" }, ] 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,6 +2211,7 @@ seer-survival = [ ] survival-curves = [ { name = "mpmath" }, + { name = "plotly" }, { name = "scipy" }, ] @@ -2232,6 +2233,7 @@ 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" }, @@ -2252,6 +2254,7 @@ 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" }, @@ -2949,7 +2952,7 @@ name = "pexpect" version = "4.9.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ptyprocess" }, + { name = "ptyprocess", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, ] 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 = [ @@ -3059,6 +3062,19 @@ 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" diff --git a/webapi/blueprints/governance.py b/webapi/blueprints/governance.py index dd7c11d..34f867d 100644 --- a/webapi/blueprints/governance.py +++ b/webapi/blueprints/governance.py @@ -228,6 +228,15 @@ 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///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.""" @@ -237,13 +246,18 @@ def list_experiments(): @governance_bp.post("/experiments") def run_experiment(): - """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`.""" + """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.""" 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 or missing: - return jsonify({"error": f"faltan campos: {(['file'] if upload is None else []) + missing}"}), 400 + 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 domain, scenario, version = form["domain"], form["scenario"], form.get("version") or None url = form["url"] if url.split("/", 1)[0] != domain: @@ -251,13 +265,21 @@ 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"])) - 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 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") 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