Compare commits

..

19 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 10f0c59975 Reject invalid optional access callbacks 2026-11-13 18:19:39 -06:00
Angel Capetillo Zavala 1d8cd264b8 Clarify optional cohort access boundary 2026-11-13 17:56:50 -06:00
Angel Capetillo Zavala 46eb3dfc31 Use shared access for synthetic breast follow-up 2026-11-13 17:54:56 -06:00
Angel Capetillo Zavala 9c0e03f947 Remove obsolete cohort example switch 2026-11-13 17:49:44 -06:00
Angel Capetillo Zavala 6d32115eca Check startup with retained cohort settings 2026-11-13 17:47:37 -06:00
Angel Capetillo Zavala 06dd74cdb6 Verify cervical patient identity contract 2026-11-13 17:43:50 -06:00
Angel Capetillo Zavala eeb55c4255 Use source patient identity for breast follow-up 2026-11-13 17:38:19 -06:00
edgar 2ca86232c9 Follow-up list without a salt: the kit identifies each patient by pac_id 2026-11-13 17:31:07 -06:00
Angel Capetillo Zavala 8b47f1522d Connect breast follow-up to the configured cohort 2026-11-13 15:16:14 -06:00
Angel Capetillo Zavala 7bc214b50c Validate patient identity in breast cohort links 2026-11-13 14:52:55 -06:00
Angel Capetillo Zavala 1d5f1e0cc4 Add synthetic breast cohort reconciliation 2026-11-13 13:27:18 -06:00
Angel Capetillo Zavala ca54656124 Add breast cancer follow-up export and patient endpoints 2026-11-12 22:40:22 -06:00
Angel Capetillo Zavala 102999c8de Verify CaMa publication without demonstration labels 2026-11-12 11:57:45 -06:00
Angel Capetillo Zavala 7798d007d1 Update synthetic diagnosis publication expectations 2026-11-12 11:15:36 -06:00
Angel Capetillo Zavala c72c03988e Align synthetic CaMa follow-up contract 2026-11-12 11:15:22 -06:00
Angel Capetillo Zavala 91537e9efd Test and document CaMa histopathology publication 2026-11-12 10:38:34 -06:00
Angel Capetillo Zavala f11abd8f6e Test publication of CaMa demonstration measures 2026-11-12 10:16:38 -06:00
Angel Capetillo Zavala 6afe329e52 Add synthetic CaMa follow-up endpoint 2026-11-12 10:06:17 -06:00
Roberto Treviño Cervantes 96a29cfb19 import files in columns 2026-11-11 11:09:48 -06:00
19 changed files with 1634 additions and 4 deletions
+9
View File
@@ -96,3 +96,12 @@ uv run pytest -q
Las pruebas contra MySQL en vivo se activan con `MYSQL_TEST_URL`; sin ella Las pruebas contra MySQL en vivo se activan con `MYSQL_TEST_URL`; sin ella
se omiten. se omiten.
### Seguimiento CaMa sintético
El lector usa la base configurada por `CAMA_DATABASE_URL` y publica el
`pac_id` de la plataforma como cadena decimal, con ámbito limitado a esa base
y dominio. Las rutas por paciente usan el mismo acceso de la aplicación que
Seguimiento CaCu. Los parámetros de corte, ventana y selección, la revisión, la
supresión y los ejemplos de listado, ficha y exportación se describen en
[el contrato de cohorte](docs/cama-cohort-api.md).
+477
View File
@@ -0,0 +1,477 @@
{
"id": "cama_histopatologia_birads",
"titulo": "Histopatología por BI-RADS (demostración sintética)",
"version": "0.1.0",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2025-S1"
],
"estrato": "birads",
"valores_estrato": [
"BIRADS_4",
"BIRADS_4A",
"BIRADS_4B",
"BIRADS_4C",
"BIRADS_5",
"BIRADS_6"
],
"etiquetas_estrato": {
"BIRADS_4": "BI-RADS 4 sin subtipo",
"BIRADS_4A": "BI-RADS 4A",
"BIRADS_4B": "BI-RADS 4B",
"BIRADS_4C": "BI-RADS 4C",
"BIRADS_5": "BI-RADS 5",
"BIRADS_6": "BI-RADS 6"
},
"grupos": {
"TOTAL": "Total"
},
"categorias": {
"BENIGNO": {
"etiqueta": "Benigno",
"color": "#9DBFE3",
"grupo": "NO_MALIGNO",
"gravedad": 1
},
"RIESGO_B3": {
"etiqueta": "Lesión de riesgo (B3)",
"color": "#2F6DB3",
"grupo": "NO_MALIGNO",
"gravedad": 2
},
"IN_SITU": {
"etiqueta": "Carcinoma in situ",
"color": "#D9822B",
"grupo": "MALIGNO",
"gravedad": 3
},
"INVASOR": {
"etiqueta": "Carcinoma invasor",
"color": "#B5482E",
"grupo": "MALIGNO",
"gravedad": 4
},
"SIN_BIOPSIA": {
"etiqueta": "Sin biopsia reportada",
"color": "#C9CDD2",
"grupo": null,
"gravedad": null
},
"SIN_DATO": {
"etiqueta": "Sin dato",
"color": "#C9CDD2",
"grupo": "SIN_DATO",
"gravedad": null
}
},
"grupos_de_categoria": {
"NO_MALIGNO": "No maligno",
"MALIGNO": "Maligno",
"SIN_DATO": "Sin dato"
},
"notas": [
"Convención provisional para datos sintéticos; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado."
],
"reportes": [
{
"periodo": "2025-S1",
"report_id": 141,
"periodo_inicio": "2025-01-01",
"periodo_fin": "2025-07-01",
"fecha_corte": "2025-12-31",
"generado_en": "2026-11-12T16:33:37.621606+00:00",
"kit_version": "0.8.0",
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
"parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe",
"parametros": {
"sql": {
"_catalogo": [
"BENIGNO",
"RIESGO_B3",
"IN_SITU",
"INVASOR"
],
"_grupos": [
"TOTAL"
],
"fecha_corte": "2025-12-31",
"periodo_fin": "2025-07-01",
"periodo_inicio": "2025-01-01"
},
"umbral_supresion": 5
}
}
],
"filas": [
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "BENIGNO",
"n": 2,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "RIESGO_B3",
"n": 0,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "INVASOR",
"n": 2,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "BENIGNO",
"n": 1,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "RIESGO_B3",
"n": 1,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "IN_SITU",
"n": 1,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "INVASOR",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "SIN_BIOPSIA",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"categoria": "SIN_DATO",
"n": 1,
"orden": 5,
"suprimido": 0
}
],
"totales_estrato": [
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4",
"n": 6,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4A",
"n": 7,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4B",
"n": 6,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_4C",
"n": 6,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_5",
"n": 6,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": "BIRADS_6",
"n": 6,
"suprimido": 0
}
]
}
+150
View File
@@ -0,0 +1,150 @@
{
"id": "cama_histopatologia_birads",
"titulo": "Histopatología por BI-RADS (demostración sintética)",
"version": "0.1.0",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2025-S1"
],
"estrato": null,
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"TOTAL": "Total"
},
"categorias": {
"BENIGNO": {
"etiqueta": "Benigno",
"color": "#9DBFE3",
"grupo": "NO_MALIGNO",
"gravedad": 1
},
"RIESGO_B3": {
"etiqueta": "Lesión de riesgo (B3)",
"color": "#2F6DB3",
"grupo": "NO_MALIGNO",
"gravedad": 2
},
"IN_SITU": {
"etiqueta": "Carcinoma in situ",
"color": "#D9822B",
"grupo": "MALIGNO",
"gravedad": 3
},
"INVASOR": {
"etiqueta": "Carcinoma invasor",
"color": "#B5482E",
"grupo": "MALIGNO",
"gravedad": 4
},
"SIN_BIOPSIA": {
"etiqueta": "Sin biopsia reportada",
"color": "#C9CDD2",
"grupo": null,
"gravedad": null
},
"SIN_DATO": {
"etiqueta": "Sin dato",
"color": "#C9CDD2",
"grupo": "SIN_DATO",
"gravedad": null
}
},
"grupos_de_categoria": {
"NO_MALIGNO": "No maligno",
"MALIGNO": "Maligno",
"SIN_DATO": "Sin dato"
},
"notas": [
"Convención provisional para datos sintéticos; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado."
],
"reportes": [
{
"periodo": "2025-S1",
"report_id": 141,
"periodo_inicio": "2025-01-01",
"periodo_fin": "2025-07-01",
"fecha_corte": "2025-12-31",
"generado_en": "2026-11-12T16:33:37.621606+00:00",
"kit_version": "0.8.0",
"toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d",
"parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe",
"parametros": {
"sql": {
"_catalogo": [
"BENIGNO",
"RIESGO_B3",
"IN_SITU",
"INVASOR"
],
"_grupos": [
"TOTAL"
],
"fecha_corte": "2025-12-31",
"periodo_fin": "2025-07-01",
"periodo_inicio": "2025-01-01"
},
"umbral_supresion": 5
}
}
],
"filas": [
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "BENIGNO",
"n": 7,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "RIESGO_B3",
"n": 5,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "IN_SITU",
"n": 6,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "INVASOR",
"n": 7,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "SIN_BIOPSIA",
"n": 6,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S1",
"grupo": "TOTAL",
"estrato": null,
"categoria": "SIN_DATO",
"n": 6,
"orden": 5,
"suprimido": 0
}
],
"totales_estrato": []
}
+75
View File
@@ -0,0 +1,75 @@
# Breast cohort: synthetic integration contract
This contract is for a synthetic source. The application reads the configured
CaMa database through the shared persistence settings. Patient routes have
the same application access boundary as CaCu follow-up; an optional access
callback can apply an additional boundary. An unavailable reader returns 503.
Authorization for real patient data has not been implemented.
`GET /cama/analisis/indicadores?corte=2026-10-20` returns a descriptive count
by BI-RADS. It includes `cohorte`, `revision`, `escenario`, `corte`,
`umbral_supresion`, `unidad`, `denominador` and `grupos`. A sample group is
`{"codigo":"BIRADS_5","n":6,"suprimido":false}`. A suppressed group's `n`
is null. The prototype's required `indicadores` array is empty: the new
`grupos` is a count distribution, not an incidence or survival estimate.
No survival, recurrence, subgroup grid or other analysis endpoints are supplied.
One patient contributes once: choose the latest mammogram with a BI-RADS report
available by cutoff; then include it if BI-RADS is 4, 4A, 4B, 4C, 5 or 6.
`revision` is a digest of the materialized cohort, including its data and stable
patient identifiers. It is an integrity marker, not an authorization credential.
For each patient request send `cohorte=cama_birads_v1`, `escenario=diagnostico`,
the exact `revision` and `corte` from the aggregate, `meses`, and any selected
`birads` or `grupo_edad`. For example:
```
GET /cama/seguimiento?cohorte=cama_birads_v1&escenario=diagnostico&revision=<revision>&corte=2026-10-20&meses=0&birads=BIRADS_5
```
For the same selected population use the same query on
`/cama/seguimiento/exportacion` or `/cama/pacientes/<pac_id>`; list
accepts `page` and `page_size` (maximum 200). Export is limited to 5,000.
`meses=0` means the whole eligible cohort through cutoff. Its inclusive
`desde` is the earliest eligible mammography date before filtering; when the
cohort is empty it is the cutoff. `hasta` is the inclusive cutoff. Windows 1,
3, 6 and 12 retain their calendar-month semantics.
Regular follow-up accepts the same window and filters without cohort context;
it reads the same source, checks access and returns its cohort context and
revision. When omitted, cutoff is the server's current date and the window is
three months. Quote the returned context in subsequent page, detail and export
requests to pin them to that revision. The old independent fixture, status and
priority filters are no longer served; these values cannot be derived safely
from the available records.
BI-RADS codes are `BIRADS_4`, `BIRADS_4A`, `BIRADS_4B`, `BIRADS_4C`,
`BIRADS_5`, `BIRADS_6`. Age options are `MENOR_40`, `40-49`, `50-59`,
`60-69`, `70+`, `SIN_DATO`. Filters combine with AND. Unknown, duplicated or
invalid parameters return 400. A filtered group with fewer than five patients,
or a nonempty whole cohort smaller than five, returns 403; empty unfiltered
cohorts return an empty page. A revision mismatch returns 409; absent detail
returns 404, an unavailable reader returns 503 and oversized exports return 413.
An optional access callback is checked independently of suppression. Responses
containing patient data carry `Cache-Control: no-store`.
The source uses the kit's silver mammography and biopsy queries. A biopsy must
be linked through its order to the selected mammogram and patient. Clinical
dates and load start timestamps are distinct fields. Procedure and observation
load timestamps must be no later than the UTC cutoff day. Silver stores only
the current row: a historical value overwritten later cannot be reconstructed,
and the person table does not version date of birth. Therefore this contract
does not certify a historical snapshot. Revision detects changes between
requests but does not persist the previous cohort. The current implementation
materializes the full cohort in memory and has not been sized for production.
The local example `examples/serve_cama_cohort.py` accepts an existing synthetic
SQLite file in `CAMA_SYNTHETIC_SQLITE`, opens it read-only, binds to loopback,
and does not require cohort-specific environment variables.
Other domain database URLs are set to isolated in-memory SQLite by the example.
The Windows-only `fcntl` shim raises if locking is attempted: this example does
not validate file-locking functionality.
`examples/serve_cama_integration.py` runs normal application configuration
against an existing disposable SQLite copy, bound to loopback. It is suitable only
for local synthetic integration and does not provide production authentication.
+51
View File
@@ -0,0 +1,51 @@
"""Run the cohort endpoints locally against an explicitly supplied synthetic SQLite file."""
import os
from pathlib import Path
import sqlite3
from urllib.parse import quote
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
if os.name == 'nt':
import sys
import types
fcntl = types.ModuleType('fcntl')
fcntl.LOCK_EX, fcntl.LOCK_UN = 2, 8
def unavailable(*args):
raise RuntimeError('File locking is unavailable in this local Windows example')
fcntl.flock = unavailable
sys.modules['fcntl'] = fcntl
path = Path(os.environ['CAMA_SYNTHETIC_SQLITE']).resolve(strict=True)
if not path.is_file():
raise ValueError('The synthetic SQLite database must already exist')
# The cohort reader can only open the named file in read-only mode.
uri = 'file:' + quote(path.as_posix(), safe='/:') + '?mode=ro'
engine = create_engine('sqlite://', creator=lambda: sqlite3.connect(uri, uri=True))
# The other application blueprints must not inherit a live database URL.
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE'):
os.environ[domain + '_DATABASE_URL'] = 'sqlite:///:memory:'
from webapi import create_app
from webapi.cama_cohort import CamaCohort
app = create_app()
def read(cutoff):
with Session(engine) as session:
return CamaCohort(session).rows(cutoff)
app.config['CAMA_COHORT_READER'] = read
if __name__ == '__main__':
app.run(host='127.0.0.1', port=int(os.environ.get('CAMA_COHORT_PORT', '5059')), debug=False)
+34
View File
@@ -0,0 +1,34 @@
"""Serve an isolated synthetic database through a loopback-only test proxy."""
import argparse
import os
from pathlib import Path
import sys
import types
parser = argparse.ArgumentParser()
parser.add_argument('--database', required=True, help='Existing disposable synthetic SQLite database')
parser.add_argument('--port', type=int, default=5059)
args = parser.parse_args()
database = Path(args.database).resolve(strict=True)
if not database.is_file():
raise ValueError('The synthetic database must be an existing file')
os.environ.update(CAMA_DATABASE_URL='sqlite:///' + database.as_posix(),
MLFLOW_DISABLE_AGENT_HINT='1',
MLFLOW_DISABLE_TELEMETRY='true')
for domain in ('CACU', 'TEA', 'GOVERNANCE'):
os.environ[domain + '_DATABASE_URL'] = 'sqlite:///:memory:'
if os.name == 'nt':
fcntl = types.ModuleType('fcntl')
fcntl.LOCK_EX, fcntl.LOCK_UN = 2, 8
def unavailable(*_args):
raise RuntimeError('POSIX locking is unavailable in this Windows test harness')
fcntl.flock = unavailable
sys.modules['fcntl'] = fcntl
from webapi import create_app
from werkzeug.serving import make_server
app = create_app()
print(f'Isolated synthetic test proxy: http://127.0.0.1:{args.port}', flush=True)
make_server('127.0.0.1', args.port, app, threaded=True).serve_forever()
+184
View File
@@ -0,0 +1,184 @@
"""Exercise cohort selection with isolated synthetic silver rows and Flask clients."""
from datetime import date, datetime, timezone
import pytest
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from indicadores_kit.cama.tablas import TABLAS
from webapi.cama_analysis import analysis
from webapi.cama_cohort import CamaCohort
from webapi.seguimiento_cama import blueprint_seguimiento_cama
@pytest.fixture
def cohort_db():
"""Six eligible people, one linked biopsy and one biopsy without a link."""
t = TABLAS
engine = create_engine('sqlite:///:memory:')
for model in (t.Persona, t.Carga, t.Procedimiento, t.Observacion):
model.__table__.create(engine)
with Session(engine) as session:
session.add_all([
t.Carga(carga_id=1, fuente='test', inicio=datetime(2025, 1, 1, tzinfo=timezone.utc)),
t.Carga(carga_id=2, fuente='test', inicio=datetime(2027, 1, 1, tzinfo=timezone.utc)),
])
for patient in range(1, 7):
session.add(t.Persona(pac_id=patient, pac_id_hospital=f'T-{patient}', fecha_nacimiento=date(1970, 1, 1)))
session.add(t.Procedimiento(procedimiento_id=patient * 10, fuente_tabla='mastografia', fuente_id=str(patient),
carga_id=1, pac_id=patient, estudio_id='mastografia', clase='toma', fecha=date(2025, 2, 1)))
session.add(t.Procedimiento(procedimiento_id=patient * 10 + 1, padre_id=patient * 10, fuente_tabla='mastografia',
fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='mastografia',
clase='reporte', fecha=date(2025, 2, 2)))
session.add(t.Observacion(observacion_id=patient, procedimiento_id=patient * 10 + 1, carga_id=1,
pac_id=patient, resultado_id='mastografia.birads', valor_fuente='B5'))
for patient, parent, load in ((1, 10, 1), (2, None, 1), (3, 30, 2), (4, 40, 1)):
report_date = date(2027, 2, 15) if patient == 4 else date(2025, 2, 15)
session.add(t.Procedimiento(procedimiento_id=100 + patient * 2, padre_id=parent, fuente_tabla='biopsiamama',
fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='biopsia',
clase='orden', fecha=date(2025, 2, 10)))
session.add(t.Procedimiento(procedimiento_id=101 + patient * 2, padre_id=100 + patient * 2,
fuente_tabla='biopsiamama', fuente_id=str(patient), carga_id=1, pac_id=patient,
estudio_id='biopsia', clase='reporte', fecha=report_date))
session.add(t.Observacion(observacion_id=100 + patient, procedimiento_id=101 + patient * 2, carga_id=load,
pac_id=patient, resultado_id='biopsia.grado', valor_fuente='BENIGNO'))
session.commit()
yield engine
engine.dispose()
@pytest.fixture
def client(cohort_db):
"""Configure an explicitly synthetic reader and an authorized test principal."""
app = Flask(__name__)
app.register_blueprint(analysis, url_prefix='/cama')
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama')
def read(cutoff):
with Session(cohort_db) as session:
return CamaCohort(session).rows(cutoff)
app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=lambda req: True)
return app.test_client()
QUERY = '?cohorte=cama_birads_v1&escenario=diagnostico&corte=2026-10-20&meses=0&birads=BIRADS_5'
def query(client, cutoff='2026-10-20'):
revision = client.get('/cama/analisis/indicadores?corte=' + cutoff).get_json()['revision']
return QUERY.replace('2026-10-20', cutoff) + '&revision=' + revision
def test_aggregate_list_detail_and_export_have_one_selection(client):
"""The published aggregate reconciles with pages, patient details and export."""
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 6
selection = query(client)
first = client.get('/cama/seguimiento' + selection + '&page_size=2').get_json()
assert first['ventana'] == {'meses': 0, 'desde': '2025-02-01', 'hasta': '2026-10-20'}
items = []
for page in (1, 2, 3):
data = client.get('/cama/seguimiento' + selection + f'&page_size=2&page={page}').get_json()
items.extend(data['items'])
exported = client.get('/cama/seguimiento/exportacion' + selection).get_json()
assert exported['items'] == items and exported['total_items'] == 6
for item in items:
detail = client.get('/cama/pacientes/' + item['pac_id'] + selection).get_json()
assert detail['item'] == item and detail['corte'] == aggregate['corte']
assert sum(item['biopsia'] == 'BENIGNO' for item in items) == 1
assert client.get('/cama/seguimiento' + selection).get_json()['items'] == items
def test_rejects_unknown_and_suppressed_selections_and_denies_access(client):
"""Unknown filters and small groups cannot silently broaden patient access."""
selection = query(client)
assert client.get('/cama/seguimiento' + selection + '&estadio=IV').status_code == 400
assert client.get('/cama/seguimiento' + selection.replace('BIRADS_5', 'BIRADS_4A')).status_code == 403
assert client.get('/cama/seguimiento' + selection.replace('cama_birads_v1', 'otra')).status_code == 400
assert client.get('/cama/seguimiento' + selection.replace(selection[-64:], '0' * 64)).status_code == 409
client.application.config['CAMA_COHORT_ACCESS'] = lambda req: False
assert client.get('/cama/seguimiento' + selection).status_code == 403
assert client.get('/cama/seguimiento/exportacion' + selection).status_code == 403
assert client.get('/cama/pacientes/some-id' + selection).status_code == 403
def test_cutoff_excludes_later_clinical_and_load_dates(client):
"""A report or observation not yet known at the cutoff cannot appear."""
early = query(client, '2025-02-09')
rows = client.get('/cama/seguimiento' + early).get_json()['items']
assert len(rows) == 6 and all(row['biopsia'] is None for row in rows)
empty = query(client, '2025-02-01').replace('&birads=BIRADS_5', '')
response = client.get('/cama/seguimiento' + empty).get_json()
assert response['items'] == [] and response['ventana']['desde'] == '2025-02-01'
def test_links_and_load_dates_are_distinct(client, cohort_db):
"""A missing link and a late load cannot supply a diagnosis before cutoff."""
ids = {i: str(i) for i in range(1, 5)}
data = client.get('/cama/seguimiento' + query(client)).get_json()
rows = {item['pac_id']: item for item in data['items']}
assert rows[ids[1]]['biopsia'] == 'BENIGNO'
assert rows[ids[2]]['biopsia'] is None and rows[ids[2]]['biopsia_fecha'] is None
assert rows[ids[3]]['biopsia'] is None and rows[ids[3]]['biopsia_fecha'] == '2025-02-15'
assert rows[ids[4]]['biopsia'] is None and rows[ids[4]]['biopsia_fecha'] is None
later = client.get('/cama/seguimiento' + query(client, '2027-12-01')).get_json()
rows_later = {item['pac_id']: item for item in later['items']}
assert rows_later[ids[3]]['biopsia'] == 'BENIGNO'
assert rows_later[ids[4]]['biopsia_fecha'] == '2027-02-15'
assert set(rows) == set(rows_later)
def test_full_application_registers_cohort_and_regular_followup(client):
"""The regular follow-up uses the configured reader instead of unrelated fixture rows."""
from webapi import create_app
app = create_app()
app.config.update(client.application.config)
full = app.test_client()
assert full.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 200
assert full.get('/cama/seguimiento?corte=2026-10-20&meses=0').get_json()['paginacion']['total_items'] == 6
assert full.get('/cama/seguimiento?meses=12&resultado=INVASOR').status_code == 400
def test_windows_and_disabled_provider(client):
"""Regular windows remain available and a missing reader returns unavailable."""
selection = query(client).replace('&meses=0', '&meses=1').replace('&birads=BIRADS_5', '')
body = client.get('/cama/seguimiento' + selection).get_json()
assert body['items'] == [] and body['ventana']['desde'] == '2026-09-21'
client.application.config['CAMA_COHORT_READER'] = None
assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503
def test_newer_noneligible_result_changes_revision_and_excludes_patient(client, cohort_db):
"""The latest reported result is selected before checking BI-RADS eligibility."""
previous = query(client)
with Session(cohort_db) as session:
session.add(TABLAS.Procedimiento(procedimiento_id=200, fuente_tabla='mastografia', fuente_id='new',
carga_id=1, pac_id=6, estudio_id='mastografia', clase='toma', fecha=date(2025, 4, 1)))
session.add(TABLAS.Procedimiento(procedimiento_id=201, padre_id=200, fuente_tabla='mastografia', fuente_id='new',
carga_id=1, pac_id=6, estudio_id='mastografia', clase='reporte', fecha=date(2025, 4, 2)))
session.add(TABLAS.Observacion(observacion_id=200, procedimiento_id=201, carga_id=1, pac_id=6,
resultado_id='mastografia.birads', valor_fuente='B1'))
session.commit()
assert client.get('/cama/seguimiento' + previous).status_code == 409
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 5
assert len(client.get('/cama/seguimiento' + query(client)).get_json()['items']) == 5
def test_cross_patient_links_and_observations_are_not_used(cohort_db):
"""A mismatched patient or an order before the mammogram cannot supply a result."""
with Session(cohort_db) as session:
# The biopsy order is linked to patient 1's mammogram but belongs to patient 2.
session.get(TABLAS.Procedimiento, 102).pac_id = 2
# Patient 3's otherwise linked biopsy order predates the mammogram.
session.get(TABLAS.Procedimiento, 106).fecha = date(2025, 1, 1)
# The BI-RADS observation belongs to a different patient.
session.get(TABLAS.Observacion, 6).pac_id = 5
session.commit()
reader = CamaCohort(session)
rows = {row['pac_id']: row for row in reader.rows(date(2027, 12, 1))}
assert '6' not in rows
assert rows['1']['biopsia'] is None
assert rows['3']['biopsia'] is None
+25
View File
@@ -0,0 +1,25 @@
"""Verify default persistent cohort setup with retained legacy configuration."""
from flask import Flask
from webapi.cama_runtime import configure_cama_cohort
def test_default_reader_uses_shared_persistence(monkeypatch):
"""The reader is registered without special cohort environment variables."""
for key in ('CAMA_COHORT_SYNTHETIC', 'CAMA_COHORT_SECRET', 'CAMA_COHORT_ACCESS_TOKEN'):
monkeypatch.delenv(key, raising=False)
app = Flask(__name__)
configure_cama_cohort(app)
assert callable(app.config['CAMA_COHORT_READER'])
assert 'CAMA_COHORT_ACCESS' not in app.config
def test_application_starts_with_retained_obsolete_configuration(monkeypatch):
"""Retained synthetic settings cannot prevent the health endpoint starting."""
monkeypatch.setenv('CAMA_COHORT_SYNTHETIC', '1')
monkeypatch.delenv('CAMA_COHORT_SECRET', raising=False)
monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 'invalid')
from webapi import create_app
assert create_app().test_client().get('/health').get_json() == {'status': 'ok'}
+66
View File
@@ -0,0 +1,66 @@
"""Publicación HTTP de CAM-01 y CAM-02 sobre la base sintética del kit."""
import pytest
from conftest import cliente_de
IDS = {"cama_tasa_deteccion_histopatologica": "C1", "cama_dias_resultado_diagnostico": "C3r"}
@pytest.fixture(scope="module")
def client(tmp_path_factory):
yield from cliente_de("cama", tmp_path_factory)
def test_catalogo_publica_las_dos_medidas(client):
"""Keep C1/C3r publication while titles remain suitable for the interface."""
catalogo = {item["id"]: item for item in client.get("/cama/indicadores").get_json()}
for identificador, contrato in IDS.items():
assert catalogo[identificador]["contrato"] == contrato
assert "demostración" not in catalogo[identificador]["titulo"]
assert "sintética" not in catalogo[identificador]["titulo"]
assert set(catalogo[identificador]["tipos_periodo"]) == {"mes", "semestre"}
@pytest.mark.parametrize("indicador,contrato", IDS.items())
def test_periodos_metadatos_y_datos(client, indicador, contrato):
raiz = f"/cama/indicadores/{indicador}"
assert client.get(raiz + "/metadatos").status_code == 200
assert client.get(raiz + "/periodos").status_code == 200
response = client.get(raiz + "/datos?periodos=2025-S1")
assert response.status_code == 200 and response.is_json
data = response.get_json()
assert data["contrato"] == contrato and data["periodos"] == ["2025-S1"]
assert isinstance(data["filas"], list) and data["filas"]
assert client.get(raiz + "/datos?periodos=2025-13").status_code == 404
@pytest.fixture(scope="module")
def client_sin_supresion(tmp_path_factory):
from indicadores_kit.demostracion import base_de_prueba
from indicadores_kit.registry.parametros import RUTA_PARAMETROS
from persistance import db
from persistance.settings import settings
from webapi import create_app
carpeta = tmp_path_factory.mktemp("cama_f4b2")
parametros = carpeta / "parametros.toml"
parametros.write_text(RUTA_PARAMETROS.read_text(encoding="utf-8").replace("valor = 5", "valor = 1"), encoding="utf-8")
with pytest.MonkeyPatch.context() as mp:
mp.setattr(settings, "cama_database_url", f"sqlite:///{carpeta / 'demo.db'}")
db.get_cama_engine.cache_clear()
try:
base_de_prueba(db.get_cama_engine(), "cama", ruta_parametros=parametros)
yield create_app().test_client()
finally:
db.get_cama_engine().dispose()
db.get_cama_engine.cache_clear()
def test_valores_sinteticos_visibles_con_umbral_de_prueba(client_sin_supresion):
raiz = "/cama/indicadores/"
c1 = client_sin_supresion.get(raiz + "cama_tasa_deteccion_histopatologica/datos?periodos=2025-S1").get_json()
c3 = client_sin_supresion.get(raiz + "cama_dias_resultado_diagnostico/datos?periodos=2025-S1").get_json()
assert c1["filas"][0]["numerador"] == 0 and c1["filas"][0]["denominador"] == 1
assert c1["filas"][0]["valor"] == 0 and c1["filas"][0]["ic_alto"] > 0
fila = c3["filas"][0]
assert (fila["n"], fila["q1"], fila["mediana"], fila["q3"]) == (5, 3, 7, 10)
assert fila["n_excluido"] == 1 and fila["unidad"] == "dias"
+107
View File
@@ -0,0 +1,107 @@
"""Publicación C2 de CAM-03 con dos matrices sintéticas y base aislada."""
from datetime import date
import json
import os
from pathlib import Path
import pytest
from sqlmodel import Session
from conftest import cliente_de
from indicadores_kit.cama.familias.histopatologia_birads.fixture_demo import agregar_en
from indicadores_kit.cama.tablas import TABLAS
from indicadores_kit.demostracion import base_de_prueba
from indicadores_kit.pruebas import calcular_measure
from indicadores_kit.registry.measures import measures_de
from persistance import db
from persistance.settings import settings
from webapi import create_app
ID = "cama_histopatologia_birads"
RAIZ = f"/cama/indicadores/{ID}"
@pytest.fixture(scope="module")
def publicaciones(tmp_path_factory):
resultados = []
for variante in (1, 2):
ruta = tmp_path_factory.mktemp(f"matriz{variante}") / "cama.db"
with pytest.MonkeyPatch.context() as mp:
mp.setattr(settings, "cama_database_url", f"sqlite:///{ruta}")
db.get_cama_engine.cache_clear()
motor = db.get_cama_engine()
try:
base_de_prueba(motor, "cama")
with Session(motor) as sesion:
agregar_en(sesion, variante=variante)
medida = measures_de("cama")[ID]
for periodo in ("2025-S1", "2025-02"):
calcular_measure(sesion, medida, periodo, tablas=TABLAS, corte=date(2025, 12, 31))
cliente = create_app().test_client()
general = cliente.get(RAIZ + "/datos?periodos=2025-S1")
matriz = cliente.get(RAIZ + "/datos?periodos=2025-S1&estrato=birads")
assert general.status_code == matriz.status_code == 200
resultados.append((general.get_json(), matriz.get_json()))
if variante == 1:
destinos = os.environ.get("CAM03_EJEMPLOS_DIR")
if destinos:
carpeta = Path(destinos)
carpeta.mkdir(parents=True, exist_ok=True)
for nombre, respuesta in (("cam03-general.json", general), ("cam03-birads.json", matriz)):
(carpeta / nombre).write_text(json.dumps(respuesta.get_json(), ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
catalogo = cliente.get("/cama/indicadores").get_json()
assert {"cama_tasa_deteccion_histopatologica", "cama_dias_resultado_diagnostico", ID} <= {i["id"] for i in catalogo}
historicos = ("cama_birads_456_paciente", "cama_birads_456_mastografia",
"cama_confirmacion_birads45", "cama_dias_toma_diagnostico", "cama_eu38a")
assert set(historicos) <= {i["id"] for i in catalogo}
for historico in historicos:
assert cliente.get(f"/cama/indicadores/{historico}/datos?periodos=2025-S1").status_code == 200
assert cliente.get(RAIZ + "/metadatos").status_code == 200
assert next(i for i in catalogo if i['id'] == ID)['titulo'] == 'Histopatología por BI-RADS'
assert matriz.get_json()['titulo'] == 'Histopatología por BI-RADS'
assert 'datos sintéticos' not in matriz.get_json()['notas'][0]
assert cliente.get(RAIZ + "/periodos").status_code == 200
assert cliente.get(RAIZ + "/datos?periodos=2025-02&estrato=birads").status_code == 200
figura = cliente.get(RAIZ + "/figuras/fig_c2_donas?periodos=2025-S1")
assert figura.status_code == 200
finally:
motor.dispose()
db.get_cama_engine.cache_clear()
return resultados
def test_cruce_completo_y_catalogos(publicaciones):
general, datos = publicaciones[0]
assert datos["contrato"] == general["contrato"] == "C2"
assert datos["estrato"] == "birads" and general["estrato"] is None
estratos = {"BIRADS_4", "BIRADS_4A", "BIRADS_4B", "BIRADS_4C", "BIRADS_5", "BIRADS_6"}
categorias = {"BENIGNO", "RIESGO_B3", "IN_SITU", "INVASOR", "SIN_DATO", "SIN_BIOPSIA"}
assert set(datos["valores_estrato"]) == estratos
assert {(f["estrato"], f["categoria"]) for f in datos["filas"]} == {(e, c) for e in estratos for c in categorias}
assert datos["categorias"]["BENIGNO"]["grupo"] == "NO_MALIGNO"
assert datos["categorias"]["RIESGO_B3"]["grupo"] == "NO_MALIGNO"
assert datos["categorias"]["IN_SITU"]["grupo"] == datos["categorias"]["INVASOR"]["grupo"] == "MALIGNO"
assert datos["categorias"]["SIN_DATO"]["grupo"] == "SIN_DATO"
assert datos["categorias"]["SIN_BIOPSIA"]["grupo"] is None
assert datos["grupos_de_categoria"]["MALIGNO"] == "Maligno"
celdas = {(f["estrato"], f["categoria"]): f for f in datos["filas"]}
assert celdas["BIRADS_4", "RIESGO_B3"]["n"] == 0 and celdas["BIRADS_4", "RIESGO_B3"]["suprimido"] == 0
assert celdas["BIRADS_4", "SIN_DATO"]["n"] == 1
for total in datos["totales_estrato"]:
assert total["n"] == sum(f["n"] for f in datos["filas"] if f["estrato"] == total["estrato"])
assert sum(f["n"] for f in general["filas"]) == sum(f["n"] for f in datos["filas"])
def test_mismas_marginales_no_ocultan_celdas_distintas(publicaciones):
(g1, m1), (g2, m2) = publicaciones
assert {f["categoria"]: f["n"] for f in g1["filas"]} == {f["categoria"]: f["n"] for f in g2["filas"]}
assert {f["estrato"]: f["n"] for f in m1["totales_estrato"]} == {f["estrato"]: f["n"] for f in m2["totales_estrato"]}
assert {(f["estrato"], f["categoria"]): f["n"] for f in m1["filas"]} != {(f["estrato"], f["categoria"]): f["n"] for f in m2["filas"]}
def test_supresion_en_fixture_pequeno(tmp_path_factory):
for cliente in cliente_de("cama", tmp_path_factory):
datos = cliente.get(RAIZ + "/datos?periodos=2025-S1&estrato=birads").get_json()
assert datos["filas"] and all(f["suprimido"] == 1 and f["n"] is None for f in datos["filas"])
assert all(t["suprimido"] == 1 and t["n"] is None for t in datos["totales_estrato"])
assert "BIRADS_4" not in datos["valores_estrato"]
assert not any(f["estrato"] == "BIRADS_4" for f in datos["filas"])
+11
View File
@@ -72,6 +72,17 @@ def test_a_scored_member_has_the_contracts_shape(client, seeded):
assert [(h["horizonte_anios"], h["probabilidad"], h["estado"]) for h in horizons] == [(1.0, 0.1, "final"), (3.0, 0.3, "final")] assert [(h["horizonte_anios"], h["probabilidad"], h["estado"]) for h in horizons] == [(1.0, 0.1, "final"), (3.0, 0.3, "final")]
def test_follow_up_identity_resolves_scored_patient(client, seeded):
"""The patient selected from follow-up resolves to that patient's seeded risk."""
listing = client.get('/cacu/seguimiento?corte=2025-12-31&meses=12&page_size=200').get_json()
row = next(item for item in listing['items'] if item['pac_id'] == str(seeded[0]))
assert row['id_seudonimo'] == row['pac_id']
response = client.get(f"/cacu/pacientes/{row['pac_id']}/riesgo")
assert response.status_code == 200
assert response.get_json()['cohorte']['pap_0'] == 'ASC-US'
assert response.get_json()['riesgo']['horizontes'][0]['probabilidad'] == 0.1
def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded): def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded):
"""Pins down: a member nobody scored has `cohorte` and `riesgo: null`; a patient outside the latest build has both """Pins down: a member nobody scored has `cohorte` and `riesgo: null`; a patient outside the latest build has both
null. Fails if either case errors or invents a risk.""" null. Fails if either case errors or invents a risk."""
+3 -2
View File
@@ -9,7 +9,7 @@ import pytest
from conftest import cliente_de from conftest import cliente_de
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"} LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
LLAVES_DEL_ITEM = {"id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph", LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
"dias_toma_diagnostico", "prioridad"} # fmt: skip "dias_toma_diagnostico", "prioridad"} # fmt: skip
@@ -31,7 +31,8 @@ def test_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
assert set(cuerpo) == LLAVES and cuerpo["simulado"] is True assert set(cuerpo) == LLAVES and cuerpo["simulado"] is True
assert cuerpo["items"] and all(set(i) == LLAVES_DEL_ITEM for i in cuerpo["items"]) assert cuerpo["items"] and all(set(i) == LLAVES_DEL_ITEM for i in cuerpo["items"])
assert all(i["prioridad"] is None for i in cuerpo["items"]) assert all(i["prioridad"] is None for i in cuerpo["items"])
assert "pac_id" not in response.get_data(as_text=True) assert all(i["pac_id"] == i["id_seudonimo"] and i["pac_id"].isdigit() for i in cuerpo["items"])
assert "pac_id_hospital" not in response.get_data(as_text=True)
def test_el_pedido_se_respeta(client): def test_el_pedido_se_respeta(client):
+72
View File
@@ -0,0 +1,72 @@
"""Exercise regular and cohort follow-up with an authorized synthetic reader."""
from datetime import date
import pytest
from flask import Flask
from webapi.cama_analysis import analysis, revision_of
from webapi.seguimiento_cama import blueprint_seguimiento_cama
@pytest.fixture
def client():
"""A fixed six-person cohort and a server-controlled access callback."""
rows = [dict(pac_id=str(n + 1), mastografia_fecha='2026-10-15',
birads='BIRADS_5', grupo_edad='50-59', biopsia=None,
biopsia_fecha=None) for n in range(6)]
app = Flask(__name__)
app.register_blueprint(analysis, url_prefix='/cama')
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama')
app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=lambda cutoff: rows,
CAMA_COHORT_ACCESS=lambda request: request.headers.get('X-Test') == 'yes')
return app.test_client()
def test_regular_list_detail_and_export_use_the_same_selection(client):
"""Pagination, detail and export resolve the same filtered persistent cohort."""
headers = {'X-Test': 'yes'}
query = '?corte=2026-10-20&meses=3&birads=BIRADS_5'
page = client.get('/cama/seguimiento' + query + '&page_size=2', headers=headers).get_json()
assert page['paginacion']['total_items'] == 6
assert page['cohorte'] == 'cama_birads_v1'
context = '&cohorte=' + page['cohorte'] + '&escenario=' + page['escenario'] + '&revision=' + page['revision']
rows = []
for number in (1, 2, 3):
rows.extend(client.get('/cama/seguimiento' + query + context + f'&page_size=2&page={number}', headers=headers).get_json()['items'])
exported = client.get('/cama/seguimiento/exportacion' + query + context, headers=headers).get_json()
assert exported['items'] == rows
assert client.get('/cama/pacientes/' + rows[0]['pac_id'] + query + context, headers=headers).get_json()['item'] == rows[0]
assert client.get('/cama/seguimiento' + query, headers=headers).headers['Cache-Control'] == 'no-store'
def test_regular_followup_checks_access_and_suppression(client):
"""The ordinary route cannot bypass authorization or suppression."""
assert client.get('/cama/seguimiento').status_code == 403
headers = {'X-Test': 'yes'}
assert client.get('/cama/seguimiento?corte=2026-10-20&birads=BIRADS_4', headers=headers).status_code == 403
assert client.get('/cama/seguimiento?corte=2026-10-20&estatus=BENIGNO', headers=headers).status_code == 400
assert client.get('/cama/seguimiento?revision=' + '0' * 64, headers=headers).status_code == 400
client.application.config['CAMA_COHORT_ACCESS'] = 'invalid'
assert client.get('/cama/seguimiento', headers=headers).status_code == 403
def test_disabled_provider_and_empty_window(client):
"""Unavailable sources fail closed and an empty unfiltered window stays empty."""
headers = {'X-Test': 'yes'}
body = client.get('/cama/seguimiento?corte=2025-01-01&meses=3', headers=headers).get_json()
assert body['items'] == [] and body['paginacion']['total_items'] == 0
client.application.config['CAMA_COHORT_READER'] = None
assert client.get('/cama/seguimiento', headers=headers).status_code == 503
def test_provider_failure_does_not_break_other_routes(client):
"""A failing cohort source returns unavailable while the app can serve other requests."""
def fail(_cutoff):
raise RuntimeError('provider unavailable')
client.application.add_url_rule('/health', 'health', lambda: {'status': 'ok'})
client.application.config['CAMA_COHORT_READER'] = fail
assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503
assert client.get('/cama/seguimiento?corte=2026-10-20', headers={'X-Test': 'yes'}).status_code == 503
assert client.get('/health').get_json() == {'status': 'ok'}
+7
View File
@@ -13,6 +13,8 @@ from webapi.blueprints.imports import imports_bp
from webapi.blueprints.reportes import reportes_bp from webapi.blueprints.reportes import reportes_bp
from webapi.blueprints.tea import tea_bp from webapi.blueprints.tea import tea_bp
from webapi.seguimiento import blueprint_de_seguimiento from webapi.seguimiento import blueprint_de_seguimiento
from webapi.seguimiento_cama import blueprint_seguimiento_cama
from webapi.cama_analysis import analysis as cama_analysis
class IsoJSONProvider(DefaultJSONProvider): class IsoJSONProvider(DefaultJSONProvider):
@@ -33,6 +35,9 @@ class IsoJSONProvider(DefaultJSONProvider):
def create_app() -> Flask: def create_app() -> Flask:
app = Flask(__name__) app = Flask(__name__)
app.json = IsoJSONProvider(app) app.json = IsoJSONProvider(app)
from webapi.cama_runtime import configure_cama_cohort
configure_cama_cohort(app)
# File sources travel inside the request; cap them per request. # File sources travel inside the request; cap them per request.
app.config["MAX_CONTENT_LENGTH"] = int(os.environ.get("WEBAPI_MAX_UPLOAD_MB", "200")) * 1024 * 1024 app.config["MAX_CONTENT_LENGTH"] = int(os.environ.get("WEBAPI_MAX_UPLOAD_MB", "200")) * 1024 * 1024
@@ -72,6 +77,8 @@ def create_app() -> Flask:
app.register_blueprint(cacu_bp, url_prefix="/cacu") app.register_blueprint(cacu_bp, url_prefix="/cacu")
app.register_blueprint(cama_bp, url_prefix="/cama") app.register_blueprint(cama_bp, url_prefix="/cama")
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix="/cama")
app.register_blueprint(cama_analysis, url_prefix="/cama")
app.register_blueprint(tea_bp, url_prefix="/tea") app.register_blueprint(tea_bp, url_prefix="/tea")
app.register_blueprint(imports_bp, url_prefix="/imports") app.register_blueprint(imports_bp, url_prefix="/imports")
app.register_blueprint(data_bp, url_prefix="/data") app.register_blueprint(data_bp, url_prefix="/data")
+168
View File
@@ -0,0 +1,168 @@
"""Aggregate and select the breast cohort through the same configured reader."""
from datetime import date
import hashlib
import hmac
import json
from flask import Blueprint, current_app, jsonify, request
from webapi.cama_cohort import COHORT, SCENARIO, THRESHOLD
analysis = Blueprint('cama_analysis', __name__)
BIRADS = ('BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6')
AGES = ('MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO')
class SelectionError(Exception):
def __init__(self, message, status=400):
self.message, self.status = message, status
def read_cohort(cutoff):
reader = current_app.config.get('CAMA_COHORT_READER')
if not callable(reader):
raise SelectionError('Cohorte no disponible', 503)
try:
return reader(cutoff)
except Exception:
current_app.logger.exception('Breast cohort provider failed')
raise SelectionError('Cohorte no disponible', 503) from None
def cutoff_arg(args):
text = args.get('corte')
if not text:
raise SelectionError('Se requiere corte')
try:
value = date.fromisoformat(text)
if value.isoformat() != text or value.year == 9999:
raise ValueError()
return value
except ValueError:
raise SelectionError('Corte inválido') from None
def patient_access():
check = current_app.config.get('CAMA_COHORT_ACCESS')
if check is not None and (not callable(check) or not check(request)):
raise SelectionError('Acceso no autorizado', 403)
def revision_of(rows):
"""Identify the materialized cohort without exposing its patient identifiers."""
encoded = json.dumps(rows, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()
return hashlib.sha256(encoded).hexdigest()
def cohort_request(args):
allowed = {'cohorte', 'revision', 'escenario', 'corte', 'meses', 'page', 'page_size', 'birads', 'grupo_edad'}
if set(args) - allowed or any(len(args.getlist(k)) != 1 for k in args):
raise SelectionError('Parámetros desconocidos o repetidos')
if args.get('cohorte') != COHORT or args.get('escenario') != SCENARIO:
raise SelectionError('Cohorte o escenario desconocido')
revision = args.get('revision', '')
if len(revision) != 64 or any(c not in '0123456789abcdef' for c in revision):
raise SelectionError('Revisión de cohorte inválida')
cutoff = cutoff_arg(args)
try:
months = int(args.get('meses', '3'))
page = int(args.get('page', '1'))
size = int(args.get('page_size', '50'))
if months not in (0, 1, 3, 6, 12) or page < 1 or not 1 <= size <= 200:
raise ValueError()
except ValueError:
raise SelectionError('Ventana o paginación inválida') from None
filters = {key: args.get(key) for key in ('birads', 'grupo_edad')}
if filters['birads'] not in (None, *BIRADS) or filters['grupo_edad'] not in (None, *AGES):
raise SelectionError('Filtro inválido')
return cutoff, months, page, size, filters, revision
def selected(args):
patient_access()
from werkzeug.datastructures import MultiDict
args = MultiDict(args)
if 'cohorte' not in args:
if any(key in args for key in ('revision', 'escenario')):
raise SelectionError('Contexto de cohorte incompleto')
if 'corte' not in args:
args['corte'] = date.today().isoformat()
cutoff = cutoff_arg(args)
rows = read_cohort(cutoff)
args.update({'cohorte': COHORT, 'escenario': SCENARIO, 'revision': revision_of(rows)})
else:
rows = None
cutoff, months, page, size, filters, revision = cohort_request(args)
if rows is None:
rows = read_cohort(cutoff)
if not hmac.compare_digest(revision, revision_of(rows)):
raise SelectionError('La cohorte cambió; actualiza el análisis', 409)
selected_rows = [row for row in rows if all(v is None or row[k] == v for k, v in filters.items())]
if months:
from webapi.seguimiento_cama import _desde
try:
since = _desde(cutoff, months)
except (ValueError, OverflowError):
raise SelectionError('Ventana inválida') from None
else:
since = min((date.fromisoformat(r['mastografia_fecha']) for r in rows), default=cutoff)
selected_rows = [r for r in selected_rows if since <= date.fromisoformat(r['mastografia_fecha']) <= cutoff]
# Every filtered selection is checked on the server after applying the window.
if len(selected_rows) < THRESHOLD and (selected_rows or any(filters.values())):
raise SelectionError('Selección no disponible', 403)
return cutoff, months, page, size, filters, since, selected_rows, revision
def selection_response(args, mode, patient=None):
cutoff, months, page, size, filters, since, rows, revision = selected(args)
options = [('birads', 'Categoría BI-RADS', BIRADS), ('grupo_edad', 'Grupo de edad', AGES)]
columns = [
{'clave': 'pac_id', 'etiqueta': 'Identificador de paciente'},
{'clave': 'grupo_edad', 'etiqueta': 'Grupo de edad'},
{'clave': 'birads', 'etiqueta': 'Última mastografía', 'detalles': [{'clave': 'mastografia_fecha', 'etiqueta': 'Fecha'}]},
{'clave': 'biopsia', 'etiqueta': 'Resultado histopatológico', 'detalles': [{'clave': 'biopsia_fecha', 'etiqueta': 'Fecha de reporte'}]},
]
meta = {'simulado': True, 'cohorte': COHORT, 'revision': revision, 'escenario': SCENARIO, 'corte': cutoff.isoformat(),
'ventana': {'meses': months, 'desde': since.isoformat(), 'hasta': cutoff.isoformat()},
'campo_ventana': 'mastografia_fecha', 'filtros': filters,
'filtros_disponibles': [{'clave': k, 'etiqueta': label, 'opciones': [{'codigo': v, 'etiqueta': v} for v in values]}
for k, label, values in options], 'columnas': columns}
if mode == 'patient':
found = next((row for row in rows if row['pac_id'] == patient), None)
if found is None:
raise SelectionError('Paciente no encontrado', 404)
return jsonify(**meta, item=found)
if mode == 'export':
if len(rows) > 5000:
raise SelectionError('La exportación supera el límite de 5000 registros', 413)
return jsonify(**meta, total_items=len(rows), items=rows)
return jsonify(**meta, paginacion={'page': page, 'page_size': size, 'total_items': len(rows),
'total_pages': (len(rows) + size - 1) // size},
items=rows[(page - 1) * size:page * size])
@analysis.get('/analisis/indicadores')
def indicators():
try:
if set(request.args) != {'corte'} or len(request.args.getlist('corte')) != 1:
raise SelectionError('Se requiere únicamente corte')
cutoff = cutoff_arg(request.args)
rows = read_cohort(cutoff)
groups = []
for code in BIRADS:
count = sum(r['birads'] == code for r in rows)
groups.append({'codigo': code, 'n': count if count >= THRESHOLD else None, 'suprimido': count < THRESHOLD})
return jsonify(simulado=True, cohorte=COHORT, revision=revision_of(rows), escenario=SCENARIO, corte=cutoff.isoformat(),
horizonte_dias=0, umbral_supresion=THRESHOLD, unidad='paciente',
denominador='pacientes elegibles con última mastografía reportada BI-RADS 4 a 6',
indicadores=[], grupos=groups)
except SelectionError as e:
return jsonify(error=e.message), e.status
@analysis.after_request
def no_cache(response):
response.headers['Cache-Control'] = 'no-store'
return response
+136
View File
@@ -0,0 +1,136 @@
"""Read the breast screening cohort from the existing silver tables.
The current silver tables keep only the last version of each fact. Filtering by
load date prevents future facts from appearing at an earlier cutoff, but cannot
restore a previous value after an update.
"""
from datetime import date, datetime, time, timedelta, timezone
from sqlalchemy import select
from indicadores_kit.cama.consultas.plata import biopsias, mastografias
from indicadores_kit.cama.familias.histopatologia_birads.consulta import BIRADS
from indicadores_kit.cama.tablas import TABLAS
COHORT = "cama_birads_v1"
SCENARIO = "diagnostico"
THRESHOLD = 5
def _date(value):
return date.fromisoformat(value) if isinstance(value, str) else value
def _known(value, cutoff):
if value is None:
return False
if isinstance(value, str):
value = datetime.fromisoformat(value)
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value < datetime.combine(cutoff + timedelta(days=1), time.min, timezone.utc)
def _age_group(birth, cutoff):
if birth is None or birth > cutoff:
return "SIN_DATO"
age = cutoff.year - birth.year - ((cutoff.month, cutoff.day) < (birth.month, birth.day))
if age < 40:
return "MENOR_40"
if age >= 70:
return "70+"
return f"{age // 10 * 10}-{age // 10 * 10 + 9}"
class CamaCohort:
"""Materialize one row per eligible patient, using a caller-owned session."""
def __init__(self, session):
self.session = session
def rows(self, cutoff: date):
t = TABLAS
loads = {x.carga_id: x.inicio for x in self.session.execute(select(t.Carga)).scalars()}
procedures = {x.procedimiento_id: x for x in self.session.execute(select(t.Procedimiento)).scalars()}
observations = {(x.procedimiento_id, x.resultado_id): x for x in self.session.execute(select(t.Observacion)).scalars()}
people = {x.pac_id: x for x in self.session.execute(select(t.Persona)).scalars()}
def procedure_known(identifier):
p = procedures.get(identifier)
return bool(p and _known(loads.get(p.carga_id), cutoff))
def observation_known(identifier, result, patient):
o = observations.get((identifier, result))
return bool(o and o.pac_id == patient and _known(loads.get(o.carga_id), cutoff))
def load_time(record):
value = loads.get(record.carga_id) if record else None
return value.isoformat() if value else None
candidates = {}
for row in self.session.execute(select(mastografias(t))).mappings():
taken, reported = _date(row['fecha_toma']), _date(row['fecha_reporte'])
if not (taken and reported and taken <= reported <= cutoff and row['birads']
and procedure_known(row['procedimiento_id']) and procedure_known(row['reporte_id'])
and procedures[row['reporte_id']].pac_id == row['pac_id']
and observation_known(row['reporte_id'], 'mastografia.birads', row['pac_id'])):
continue
key = (taken, str(row['fuente_id']), reported, row['reporte_id'])
prior = candidates.get(row['pac_id'])
if prior is None or key > prior[0]:
candidates[row['pac_id']] = (key, row)
reports = {}
orders = {}
for p in procedures.values():
when = _date(p.fecha)
if (p.estudio_id != 'biopsia' or p.clase != 'orden' or not p.padre_id or not when
or when > cutoff or not procedure_known(p.procedimiento_id)):
continue
key = (p.pac_id, p.padre_id)
rank = (when, str(p.fuente_id), p.procedimiento_id)
if key not in orders or rank > orders[key][0]:
orders[key] = (rank, p)
for row in self.session.execute(select(biopsias(t))).mappings():
reported, ordered, taken = (_date(row['fecha_reporte']), _date(row['fecha_solicitud']),
_date(row['fecha_toma']))
procedure = procedures.get(row['procedimiento_id'])
order = procedures.get(procedure.padre_id) if procedure else None
if not (taken and reported and ordered and taken <= ordered <= reported <= cutoff and row['toma_id']
and row['pac_id'] == row['toma_pac_id'] and procedure_known(row['procedimiento_id'])
and order and order.pac_id == row['pac_id'] and procedure_known(order.procedimiento_id)):
continue
key = (row['pac_id'], row['toma_id'])
rank = (reported, str(row['fuente_id']), row['procedimiento_id'])
if key not in reports or rank > reports[key][0]:
reports[key] = (rank, row)
rows = []
for patient, (_, m) in candidates.items():
code = BIRADS.get(m['birads'])
if not code or patient not in people:
continue
b = reports.get((patient, m['procedimiento_id']))
b = b[1] if b and _date(b[1]['fecha_reporte']) >= _date(m['fecha_toma']) else None
order = procedures[procedures[b['procedimiento_id']].padre_id] if b else None
if not order:
found_order = orders.get((patient, m['procedimiento_id']))
order = found_order[1] if found_order and _date(found_order[1].fecha) >= _date(m['fecha_toma']) else None
grade = b['grado'] if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None
rows.append({
'pac_id': str(patient), 'mastografia_fecha': _date(m['fecha_toma']).isoformat(),
'mastografia_reporte_fecha': _date(m['fecha_reporte']).isoformat(),
'birads': code, 'grupo_edad': _age_group(people[patient].fecha_nacimiento, cutoff),
'biopsia': grade, 'biopsia_fecha': _date(b['fecha_reporte']).isoformat() if b else None,
'biopsia_solicitud_fecha': _date(order.fecha).isoformat() if order else None,
'toma_carga_inicio': load_time(procedures[m['procedimiento_id']]),
'mastografia_reporte_carga_inicio': load_time(procedures[m['reporte_id']]),
'birads_carga_inicio': load_time(observations.get((m['reporte_id'], 'mastografia.birads'))),
'biopsia_solicitud_carga_inicio': load_time(order),
'biopsia_reporte_carga_inicio': load_time(procedures[b['procedimiento_id']]) if b else None,
'biopsia_resultado_carga_inicio': load_time(observations.get((b['procedimiento_id'], 'biopsia.grado')))
if b and observation_known(b['procedimiento_id'], 'biopsia.grado', patient) else None,
})
return sorted(rows, key=lambda row: (-date.fromisoformat(row['mastografia_fecha']).toordinal(), int(row['pac_id'])))
+12
View File
@@ -0,0 +1,12 @@
"""Configure the breast cohort using the shared persistence settings."""
from persistance.db import get_cama_session
from webapi.cama_cohort import CamaCohort
def configure_cama_cohort(app):
def read(cutoff):
with get_cama_session() as session:
return CamaCohort(session).rows(cutoff)
app.config['CAMA_COHORT_READER'] = read
+1 -2
View File
@@ -19,7 +19,6 @@ from indicadores_kit.serving.seguimiento import PaginaFuera, PedidoInvalido, seg
from sqlmodel import Session from sqlmodel import Session
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}") FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
SAL_POR_OMISION = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno
def en_dev() -> bool: def en_dev() -> bool:
@@ -40,7 +39,7 @@ def blueprint_de_seguimiento(get_session: Callable[[], Session]) -> Blueprint:
return jsonify({"error": str(error)}), 400 return jsonify({"error": str(error)}), 400
sesion = get_session() sesion = get_session()
try: try:
cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", SAL_POR_OMISION), **pedido) cuerpo = seguimiento_de(sesion, **pedido)
except PedidoInvalido as error: except PedidoInvalido as error:
return jsonify({"error": str(error)}), 400 return jsonify({"error": str(error)}), 400
except PaginaFuera as error: except PaginaFuera as error:
+46
View File
@@ -0,0 +1,46 @@
"""Patient follow-up for the configured breast cohort."""
import calendar
from datetime import date, timedelta
from flask import Blueprint, jsonify, request
from webapi.cama_analysis import SelectionError, selection_response
def _desde(corte, meses):
indice = corte.year * 12 + corte.month - 1 - meses
anio, mes = divmod(indice, 12)
if anio < 1:
raise ValueError("la ventana excede el rango de fechas admitido")
anterior = date(anio, mes + 1, min(corte.day, calendar.monthrange(anio, mes + 1)[1]))
return anterior + timedelta(days=1)
def blueprint_seguimiento_cama():
blueprint = Blueprint("cama_seguimiento", __name__)
@blueprint.after_request
def no_cache(response):
response.headers["Cache-Control"] = "no-store"
return response
def respond(mode, patient=None):
try:
return selection_response(request.args, mode, patient)
except SelectionError as error:
return jsonify(error=error.message), error.status
@blueprint.get("/seguimiento")
def seguimiento():
return respond('list')
@blueprint.get("/seguimiento/exportacion")
def exportacion():
return respond('export')
@blueprint.get("/pacientes/<pac_id>")
def paciente(pac_id):
return respond('patient', pac_id)
return blueprint