Compare commits

...

2 Commits

6 changed files with 185 additions and 12 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()
+6
View File
@@ -102,6 +102,12 @@ def create_app() -> Flask:
from webapi.risk_batches import risk_batches_blueprint from webapi.risk_batches import risk_batches_blueprint
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu") 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_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(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu") app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
+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 pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
from sqlalchemy import func, select from sqlalchemy import Date, func, select, type_coerce
from sqlmodel import Session from sqlmodel import Session
from webapi.follow_up.silver import citologias, notas 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]: 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.""" """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]] = {} en_ventana: dict[int, dict[str, list]] = {}
for e in estudios: for e in estudios:
if desde <= e["fecha"] <= corte: de_la_paciente = en_ventana.setdefault(e["pac_id"], {"citologia": [], "vph": []})
de_la_paciente = en_ventana.setdefault(e["pac_id"], {"citologia": [], "vph": []}) if "citologia" in lista["estudios"]:
if "citologia" in lista["estudios"]: de_la_paciente["citologia"].append(e)
de_la_paciente["citologia"].append(e) if "vph" in lista["estudios"] and e["vph"] is not None:
if "vph" in lista["estudios"] and e["vph"] is not None: de_la_paciente["vph"].append(e)
de_la_paciente["vph"].append(e)
gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])} gravedad = {c["clave"]: i for i, c in enumerate(lista["catalogo"])}
edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas) edades = _grupo_de_edad(sesion, corte, lista["grupos_edad"], tablas)
notas_de = _notas_por_paciente(sesion, corte) notas_de = _notas_por_paciente(sesion, corte)
@@ -207,12 +206,16 @@ def _items(sesion, corte, desde, lista, estatus_de, tablas) -> list[dict]:
return items return items
def _estudios(sesion: Session, corte: date, fecha_estudio: str) -> list[dict]: def _estudios(sesion: Session, corte: date, desde: 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).""" """Citologías de la ventana, con los resultados conocidos al corte."""
c = citologias() 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, 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 = [] estudios = []
for pac_id, toma, reporte, calidad, resultado, vph, genotipo in filas: for pac_id, toma, reporte, calidad, resultado, vph, genotipo in filas:
toma, reporte = _fecha(toma), None if reporte is None else _fecha(reporte) toma, reporte = _fecha(toma), None if reporte is None else _fecha(reporte)