From 63bb802116ee35a2f9512f0fabdf8597c489d66d Mon Sep 17 00:00:00 2001 From: edgar Date: Tue, 24 Nov 2026 19:17:47 -0600 Subject: [PATCH] Serve CaCu instance and episode publications with benchmark notes --- docs/cacu-follow-up-benchmarks.md | 22 +++++++++++++ tests/test_follow_up_instances.py | 52 ++++++++++++++++++++++++++++++ webapi/__init__.py | 6 ++++ webapi/follow_up/instances.py | 53 +++++++++++++++++++++++++++++++ 4 files changed, 133 insertions(+) create mode 100644 docs/cacu-follow-up-benchmarks.md create mode 100644 tests/test_follow_up_instances.py create mode 100644 webapi/follow_up/instances.py diff --git a/docs/cacu-follow-up-benchmarks.md b/docs/cacu-follow-up-benchmarks.md new file mode 100644 index 0000000..c65e018 --- /dev/null +++ b/docs/cacu-follow-up-benchmarks.md @@ -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. diff --git a/tests/test_follow_up_instances.py b/tests/test_follow_up_instances.py new file mode 100644 index 0000000..85ea428 --- /dev/null +++ b/tests/test_follow_up_instances.py @@ -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" diff --git a/webapi/__init__.py b/webapi/__init__.py index 82e564e..d75ba97 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -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") diff --git a/webapi/follow_up/instances.py b/webapi/follow_up/instances.py new file mode 100644 index 0000000..3761453 --- /dev/null +++ b/webapi/follow_up/instances.py @@ -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//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