Compare commits

..

1 Commits

9 changed files with 28 additions and 191 deletions
-22
View File
@@ -1,22 +0,0 @@
# 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
@@ -1,52 +0,0 @@
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
@@ -1,37 +0,0 @@
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()
+4 -4
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"])
+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
-6
View File
@@ -102,12 +102,6 @@ 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")
-53
View File
@@ -1,53 +0,0 @@
"""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
+12 -15
View File
@@ -23,7 +23,7 @@ from datetime import date, timedelta
from pathlib import Path
from types import SimpleNamespace
from sqlalchemy import Date, func, select, type_coerce
from sqlalchemy import func, select
from sqlmodel import Session
from webapi.follow_up.silver import citologias, notas
@@ -166,14 +166,15 @@ 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, desde, lista["fecha_estudio"])
estudios = _estudios(sesion, corte, lista["fecha_estudio"])
en_ventana: dict[int, dict[str, list]] = {}
for e in estudios:
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)
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)
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)
@@ -206,16 +207,12 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
return items
def _estudios(sesion: Session, corte: date, desde: date, fecha_estudio: str) -> list[dict]:
"""Citologías de la ventana, con los resultados conocidos al corte."""
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)."""
c = citologias()
# 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(
filas = sesion.execute(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,
).where(fecha_toma <= corte, fecha.between(desde, corte))
filas = sesion.execute(rows)
)).all()
estudios = []
for pac_id, toma, reporte, calidad, resultado, vph, genotipo in filas:
toma, reporte = _fecha(toma), None if reporte is None else _fecha(reporte)
+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")