Compare commits

..

2 Commits

9 changed files with 197 additions and 109 deletions
+22
View File
@@ -0,0 +1,22 @@
# CaCu follow-up benchmarks
The `feature/cacu-seguimiento-instances` branch introduces an indexed, opt-in follow-up list for simulated data. It also moves the study-date filter for the existing patient-level list into SQL.
| Test | Requests per path | Baseline median / p95 | New median / p95 |
|---|---:|---:|---:|
| Existing `/cacu/seguimiento` on the synthetic CaCu fixture with 25,000 extra cytologies outside the requested six-month window | 15 | 203.69 ms / 379.72 ms | 97.02 ms / 141.29 ms |
| `/cacu/seguimiento/instancias`, first filtered 50-row page from a publication with 120,000 instances | 20 | 934.36 ms / 1,091.52 ms | 3.20 ms / 5.11 ms |
Both experiments used local SQLite and Flask's in-process HTTP client. Each comparison checked that the baseline and new path returned the same JSON before measuring request times. The existing endpoint uses WebApi commit `4840bd3` as its baseline. The instance endpoint uses the same response and publication on both paths, comparing a full read with Python filtering and paging against indexed SQL pagination.
The existing endpoint's median fell by 52% in this fixture. Building and indexing the complete synthetic publication took 4.71 seconds, measured separately from requests. Live publication time and deployed API latency remain unmeasured.
## Verify endpoint behavior
Use the Models checkout on `feature/cacu-seguimiento-instances` and make it importable by the WebApi test environment. Run the regression tests in the WebApi checkout with `DBT_MANIFEST` set to a compiled CaCu manifest for the standard synthetic fixture.
```bash
python -m pytest -q tests/test_seguimiento.py tests/test_follow_up_instances.py tests/test_follow_up_study_window.py
```
The CaCu design and the PIM verification are documented in `models/docs/seguimiento_instancias_cacu.md` on the matching branch.
+52
View File
@@ -0,0 +1,52 @@
from datetime import date
from flask import Flask
from models.cacu.instance_publication import EpisodeStudies, FollowUpInstance, publish
from webapi.follow_up.instances import instance_follow_up_blueprint
def test_instance_list_links_to_studies_in_the_same_publication(tmp_path):
path = tmp_path / "simulated.sqlite"
cutoff = date(2026, 10, 20)
row = FollowUpInstance(
"ins-1", "P-DEMO", "cin2_pim_post_treatment", 526, date(2026, 10, 15),
"pendiente", "rules-v1", 301, "eoc-07", motivos=("vph_pendiente",),
)
studies = [
{"tipo": "citologia", "toma_ref": "pr-526", "resultados": [{"valor": "NORMAL"}]},
{"tipo": "vph", "toma_ref": "pr-526", "estado": "pendiente"},
{"tipo": "referencia_colposcopia", "orden_ref": "ord-1"},
{"tipo": "colposcopia", "procedimiento_ref": "pr-204", "orden_ref": "ord-1"},
{"tipo": "biopsia", "procedimiento_ref": "pr-240"},
{"tipo": "tratamiento", "procedimiento_ref": "pr-301"},
]
publish(path, "synthetic-1", cutoff, [row], [EpisodeStudies("eoc-07", "P-DEMO", studies)])
app = Flask(__name__)
app.register_blueprint(instance_follow_up_blueprint(path), url_prefix="/cacu")
client = app.test_client()
url = "/cacu/seguimiento/instancias"
response = client.get(url + "?escenario=cin2_pim_post_treatment&elegibilidad=pendiente")
assert response.status_code == 200
body = response.json
assert body["simulado"] and body["paginacion"]["total_items"] == 1
item, = body["items"]
assert "pac_id" not in item and item["candidato_procedimiento_ref"] == "pr-526"
assert client.get(item["estudios_url"]).json["estudios"] == studies
assert client.get(url + "?page_size=201").status_code == 400
assert client.get(url + "?publicacion_id=unknown").status_code == 404
assert client.get("/cacu/episodios/eoc-07/estudios").status_code == 400
def test_application_registers_instance_routes_only_when_enabled(monkeypatch, tmp_path):
from webapi import create_app
monkeypatch.delenv("CACU_SIMULATED_INSTANCE_PUBLICATION", raising=False)
assert not any(rule.rule == "/cacu/seguimiento/instancias" for rule in create_app().url_map.iter_rules())
path = tmp_path / "simulated.sqlite"
publish(path, "synthetic", date(2026, 10, 20), [])
monkeypatch.setenv("CACU_SIMULATED_INSTANCE_PUBLICATION", str(path))
response = create_app().test_client().get("/cacu/seguimiento/instancias")
assert response.status_code == 200 and response.json["publicacion_id"] == "synthetic"
+37
View File
@@ -0,0 +1,37 @@
from datetime import date
from sqlalchemy import Column, Date, Integer, MetaData, String, Table, create_engine, select
from sqlmodel import Session
from webapi.follow_up import listing
def test_study_window_filters_on_collection_or_report_date_without_exposing_future_results(monkeypatch):
metadata = MetaData()
studies = Table(
"study_fixture", metadata,
Column("pac_id", Integer), Column("fecha_toma", Date), Column("fecha_reporte", Date),
Column("calidad_muestra", String), Column("resultado", String), Column("vph", String),
Column("genotipo_16_18", Integer),
)
engine = create_engine("sqlite://")
metadata.create_all(engine)
monkeypatch.setattr(listing, "citologias", lambda: select(studies).subquery())
beginning, cutoff = date(2026, 1, 1), date(2026, 1, 31)
with Session(engine) as session:
session.execute(studies.insert(), [
{"pac_id": 1, "fecha_toma": beginning, "fecha_reporte": cutoff, "resultado": "NORMAL"},
{"pac_id": 2, "fecha_toma": date(2025, 12, 28), "fecha_reporte": cutoff, "resultado": "LIEBG"},
{"pac_id": 3, "fecha_toma": cutoff, "fecha_reporte": date(2026, 2, 3), "resultado": "NORMAL"},
{"pac_id": 4, "fecha_toma": cutoff, "fecha_reporte": None, "resultado": None},
])
by_collection = {row["pac_id"]: row for row in listing._estudios(session, cutoff, beginning, "toma")}
by_report = {row["pac_id"]: row for row in listing._estudios(session, cutoff, beginning, "reporte")}
assert set(by_collection) == {1, 3, 4}
assert by_collection[1]["resultado"] == "NORMAL"
assert by_collection[3]["resultado"] is None and by_collection[4]["resultado"] is None
assert set(by_report) == {1, 2}
assert by_report[2]["resultado"] == "LIEBG"
engine.dispose()
-47
View File
@@ -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
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"
+6
View File
@@ -102,6 +102,12 @@ def create_app() -> Flask:
from webapi.risk_batches import risk_batches_blueprint
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
if publication := os.environ.get("CACU_SIMULATED_INSTANCE_PUBLICATION"):
from pathlib import Path
from webapi.follow_up.instances import instance_follow_up_blueprint
app.register_blueprint(instance_follow_up_blueprint(Path(publication)), url_prefix="/cacu")
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
+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
+53
View File
@@ -0,0 +1,53 @@
"""Opt-in reads from a simulated CaCu instance publication."""
from datetime import date
from pathlib import Path
from flask import Blueprint, jsonify, request, url_for
from models.cacu.instance_publication import PublicationNotFound, episode_studies, follow_up_page
def instance_follow_up_blueprint(publication_path: Path) -> Blueprint:
blueprint = Blueprint("cacu_instance_follow_up", __name__)
@blueprint.get("/seguimiento/instancias")
def list_instances():
"""List scenario candidates at one published cutoff, including pending cases."""
try:
cutoff = request.args.get("corte")
selected = date.fromisoformat(cutoff) if cutoff else None
if selected is not None and selected.isoformat() != cutoff:
raise ValueError("corte debe usar AAAA-MM-DD")
response = follow_up_page(
publication_path,
publicacion_id=request.args.get("publicacion_id"),
corte=selected,
escenario=request.args.get("escenario"),
elegibilidad=request.args.get("elegibilidad"),
page=int(request.args.get("page", "1")),
page_size=int(request.args.get("page_size", "50")),
)
except ValueError as error:
return jsonify(error=str(error)), 400
except PublicationNotFound as error:
return jsonify(error=str(error)), 404
for item in response["items"]:
if episode := item["episodio_ref"]:
item["estudios_url"] = url_for(
".list_episode_studies", episodio_ref=episode, publicacion_id=response["publicacion_id"]
)
return jsonify(response)
@blueprint.get("/episodios/<episodio_ref>/estudios")
def list_episode_studies(episodio_ref):
"""Read the studies from the same publication as the candidate list."""
publication = request.args.get("publicacion_id")
if not publication:
return jsonify(error="publicacion_id es obligatorio"), 400
try:
return jsonify(episode_studies(publication_path, episodio_ref, publication))
except PublicationNotFound as error:
return jsonify(error=str(error)), 404
return blueprint
+15 -12
View File
@@ -23,7 +23,7 @@ from datetime import date, timedelta
from pathlib import Path
from types import SimpleNamespace
from sqlalchemy import func, select
from sqlalchemy import Date, func, select, type_coerce
from sqlmodel import Session
from webapi.follow_up.silver import citologias, notas
@@ -166,15 +166,14 @@ def _estatus_al_corte(sesion: Session, corte: date, valores: dict) -> dict[int,
def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
"""Una fila por paciente con estudio en la ventana, de la más reciente a la más antigua."""
estudios = _estudios(sesion, corte, lista["fecha_estudio"])
estudios = _estudios(sesion, corte, desde, lista["fecha_estudio"])
en_ventana: dict[int, dict[str, list]] = {}
for e in estudios:
if desde <= e["fecha"] <= corte:
de_la_paciente = en_ventana.setdefault(e["pac_id"], {"citologia": [], "vph": []})
if "citologia" in lista["estudios"]:
de_la_paciente["citologia"].append(e)
if "vph" in lista["estudios"] and e["vph"] is not None:
de_la_paciente["vph"].append(e)
de_la_paciente = en_ventana.setdefault(e["pac_id"], {"citologia": [], "vph": []})
if "citologia" in lista["estudios"]:
de_la_paciente["citologia"].append(e)
if "vph" in lista["estudios"] and e["vph"] is not None:
de_la_paciente["vph"].append(e)
gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])}
edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas)
notas_de = _notas_por_paciente(sesion, corte)
@@ -207,12 +206,16 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
return items
def _estudios(sesion: Session, corte: date, fecha_estudio: str) -> list[dict]:
"""Cada toma de citología hasta el corte, con lo que ya se sabía al corte (un resultado posterior no existe)."""
def _estudios(sesion: Session, corte: date, desde: date, fecha_estudio: str) -> list[dict]:
"""Citologías de la ventana, con los resultados conocidos al corte."""
c = citologias()
filas = sesion.execute(select(
# Restore date typing for the bound values without casting the database columns.
fecha_toma = type_coerce(c.c.fecha_toma, Date)
fecha = fecha_toma if fecha_estudio == "toma" else type_coerce(c.c.fecha_reporte, Date)
rows = select(
c.c.pac_id, c.c.fecha_toma, c.c.fecha_reporte, c.c.calidad_muestra, c.c.resultado, c.c.vph, c.c.genotipo_16_18,
)).all()
).where(fecha_toma <= corte, fecha.between(desde, corte))
filas = sesion.execute(rows)
estudios = []
for pac_id, toma, reporte, calidad, resultado, vph, genotipo in filas:
toma, reporte = _fecha(toma), None if reporte is None else _fecha(reporte)