Document CaCu scenario instances and model contracts

This commit is contained in:
2026-11-24 18:57:14 -06:00
parent c12ea569cf
commit 5624e1f361
+169
View File
@@ -0,0 +1,169 @@
# CaCu scenario instances, follow-up, and model interfaces
This proposal gives `seguimiento` and all six CaCu model scenarios a shared unit of work. A **scenario instance** represents one patient, one model scenario, and one candidate procedure. The follow-up list reads the instance and its eligibility. A separate episode endpoint returns the clinical studies. Hamilton uses the same procedure references to assemble the features and outcomes required by each model.
The existing `GET /cacu/seguimiento` delegates to `indicadores_kit.serving.seguimiento_de`, which builds one item per patient and slices the list for pagination. The new list changes the unit of pagination to the scenario instance. The proposed endpoints and schema below are for review. The names and IDs in the examples are illustrative.
## Scenario instance schema
Proposed table name `cacu_instancia_escenario`. Reuse `persona`, `procedimiento`, and `observacion_clinica` in Persistance. The existing `procedimiento` table distinguishes `orden`, `encuentro`, `toma`, `reporte`, and `parte`, and can link a child procedure through `padre_id`. `observacion_clinica.procedimiento_id` identifies the procedure or report that owns each result.
| Column | Type | Meaning |
|---|---|---|
| `instancia_id` | Stable ID, primary key | Identifies the instance across refreshes. The API can expose an opaque ID. |
| `pac_id` | Integer, FK to `persona.pac_id` | Patient the instance belongs to. |
| `escenario` | Scenario code | For example, `cin2_pim`, `cin2_pim_post_colposcopy`, or `cin2_pim_post_treatment`. |
| `candidato_procedimiento_id` | Integer, FK to `procedimiento.procedimiento_id` | The procedure under consideration. This can be a cytology `toma` or the qualifying biopsy `reporte` for survival. |
| `ancla_procedimiento_id` | Nullable integer, FK to `procedimiento.procedimiento_id` | The earlier colposcopy or treatment that starts the visit sequence. Surveillance can leave it empty. |
| `episodio_id` | Nullable episode reference | Groups related studies. Resolve through `episodioclinico.episodio_id` where the source episode actually matches the care period being shown. |
| `fecha_indice` | Date | Time zero for the scenario. For a sample-indexed model, this is the collection date. |
| `resultados_disponibles_en` | Nullable timestamp | Earliest cutoff at which all results required by this scenario were available. |
| `elegibilidad` | `elegible`, `pendiente`, or `excluida` | Decision for this candidate at the published cutoff. |
| `version_reglas` | Immutable version or hash | Identifies the visit, inclusion, and exclusion rules used to derive the row. |
The business key is `(pac_id, escenario, candidato_procedimiento_id)`. Both procedure references must belong to `pac_id`. Each scenario in this proposal resolves at most one anchor for a candidate. If a future scenario permits multiple valid anchors for the same candidate, extend its identity before publishing those rows. A second observation or an earlier visit used as a covariate remains a reference in the timeline, while the instance still has one candidate.
The CaCu baseline migration already defines `episodioclinico`. Confirm that an existing episode represents the grouping needed by this endpoint before publishing it as a care episode. Where an episode is unresolved, return an empty episode reference and omit the studies link. The episode period, the index date, and the cutoff are separate values.
## Eligibility and shared inputs
dbt enumerates candidates and emits **one result per applicable rule and instance**. Store or publish the rule code, its result (`cumple`, `incumple`, `pendiente`), and an evidence procedure or observation ID when one exists. The instance carries the overall decision. The list can expose the relevant reason codes without returning the underlying clinical values.
| Scenario | Candidate and anchor | Example inclusion and exclusion checks |
|---|---|---|
| Surveillance | Cytology sample with an empty anchor | Required results belong to the same sample. A prior-event rule checks for qualifying history relative to the sample date. |
| Post-colposcopy | Follow-up cytology and its colposcopy | Check the anchor workup and whether the follow-up cotest is complete. Apply the scenario's prior cancer, hysterectomy, and treatment rules as of the candidate date. |
| Post-treatment | Follow-up cytology and its treatment | Require the treatment relationship and the results specified for the follow-up visit. Evaluate any historical exclusion declared for this scenario. |
For example, a configured `histerectomia_previa` rule is an `EXISTS` check for qualifying evidence for the same patient with a clinical date before the candidate's index and a known date at or before the evaluation cutoff. `vph_disponible` checks the HPV result linked to the selected sample. Model and clinical owners approve the exact rules, date bounds, and visit policy for each scenario. The table above describes how to express them. [Current Python index rules](../models/steps/indexing.py)
## CaCu scenarios and their inputs
Use the same instance schema for all CaCu models. The scenario configuration determines the candidate, index policy, required features, outcome, and training target. This table records the current model definitions as the starting point for migration. Any change to cohort membership, index timing, or scoreability should be reviewed as a separate model change.
| Current scenario | Candidate procedure and index | Features and training target |
|---|---|---|
| `cin2_logistic` | Surveillance cytology sample. Current index policy uses the first cytology. The configured outcome horizon is one year. | Bethesda, HPV, and HPV 16/18. Binary CIN2+ outcome for the configured window, with ascertainment handled by the scenario. [Configuration](../models/cacu/cin2_logistic/model.toml) |
| `cin2_pim` | Surveillance cytology sample. Current training uses the first cytology. Current scoring selects the latest complete sample when the patient has neither a recorded colposcopy nor a biopsy in the scoring frame. | Cytology category and HPV status. CIN2+ coded intervals `(c, l, r)`. [Configuration](../models/cacu/cin2_pim/model.toml) |
| `cancer_pim` | Surveillance cytology sample with the same current first-versus-latest index policy as `cin2_pim`. It has its own instance even when both models use the same sample. | Cytology category and HPV status. Coded intervals for carcinoma as the endpoint. [Configuration](../models/cacu/cancer_pim/model.toml) |
| `cin2_pim_post_colposcopy` | Follow-up cytology sample after the colposcopy workup, with that colposcopy as the anchor. The configured visit is `1`. | Index cytology and HPV, plus referral grade from the pre-colposcopy lookback. CIN2+ coded intervals. [Configuration](../models/cacu/cin2_pim_post_colposcopy/model.toml) |
| `cin2_pim_post_treatment` | First cytology after treatment, with the treatment as the anchor. The current build supplies the index. | Index cytology and HPV. CIN2+ coded intervals. [Configuration](../models/cacu/cin2_pim_post_treatment/model.toml) |
| `survival` | First biopsy report with a qualifying carcinoma grade (`CIS` or `CARCINOMA`). The report supplies the index date. | Age group and the latest cytology and HPV through diagnosis. Time to all-cause death or censoring. The estimator returns mortality and the current presentation can show its survival complement. [Configuration](../models/cacu/survival/model.toml) |
## Model interface
Hamilton gets a batch of instance rows keyed by `instancia_id`, plus a reference to the source publication. It loads candidate and anchor procedures by ID and retrieves the linked observations and permitted history in batches. For sample-indexed scoring, it reads cytology and HPV from the exact sample in the instance. A nearby result from another sample does not replace a result for that candidate. When a rule uses a historical covariate, such as referral grade, the scenario declares the anchor and lookback for that feature.
### Input and output contracts
| Dataset | Key | Contents |
|---|---|---|
| `instances` | `instancia_id` | Patient, scenario, candidate and anchor procedure IDs, date of index, episode reference, result availability, eligibility, and rule version. The batch carries `publicacion_id` and its clinical and data-availability cutoffs. |
| `features` | `instancia_id` | One row of prepared covariates per scorable instance and a versioned feature schema. The model signature declares the predictor columns and their types. |
| `targets` | `instancia_id` | Training only. PIM uses `(c, l, r)`, logistic uses its ascertainable binary target, and survival uses its time-to-event and censoring input. |
| `risks` | `(scoring_run_id, instancia_id, horizonte_anios)` | Scenario and index date, outcome, probability, and interval bounds when the model gives them. The scoring run pins the concrete model version and source publication. |
| `scoring_decisions` | `(scoring_run_id, instancia_id)` | Scored, pending, excluded, or unable to score, with a reason such as missing required results or an unsupported feature level. |
The estimator receives its predictor columns. Hamilton retains `instancia_id` as the join key for results and reads the model's registered horizons and outcome. A score for November and a score for August can therefore coexist for one patient in the same scenario. If a registry alias selects a production model, resolve it once at the start of the run and record the concrete version.
For example, post-treatment instance `ins-82fc` in the follow-up response below produces a `pendiente` scoring decision while HPV is missing. Once a later publication includes that result, Hamilton can prepare the cytology and HPV predictors from `pr-526`. If the selected model version supports that visit, it gives one risk row per configured horizon, all keyed by `ins-82fc` and the new scoring run. The model receives the feature values through its signature. The procedure references stay with the instance and its evidence.
### Training and scoring paths
```text
Training: publication + training visit policy
→ selected instances → linked evidence → features + targets
→ split → fit → held-out metrics → registered model version
Scoring: publication + requested visit or validated scoring visit policy
→ selected instances → linked evidence → features
→ registered model → risks and scoring decisions
```
Select the training index before coding outcomes. Join features and targets by `instancia_id`. Keep the existing temporal split for the first migration and ensure that repeated instances of a patient cannot cross from training to holdout if a model later includes multiple visits. Score a single patient by passing a batch of one instance through the same preparation and prediction steps. A visit number or new index policy requires a model validated for that use.
Enforce time bounds in feature preparation. Historical features use events from their specified window and evidence available by the feature cutoff. Results linked to the candidate sample can arrive after collection when the scenario allows it. Follow-up used to construct or evaluate the outcome is read separately from feature evidence. For retrospective scoring, use the source version available at the requested scoring cutoff.
The current `CohortSource` and registered MLflow pipelines accept the long cohort frame. The current estimate contract identifies output by patient and horizon within each estimate. Add an instance-based source and versioned scoring contract alongside that interface. Keep existing registered versions callable with the input shape they were registered with. A compatibility adapter can use an old model only where it can verify that the model uses the intended candidate. Existing risk batches that store patient and horizon need a new instance-aware representation before multiple visits can be published in one batch. [Current cohort source](../models/io/storage.py) · [Current training graph](../models/dags/training.py) · [Current scoring path](../models/dags/estimation.py)
### Rollout and verification
1. Publish the dbt instance and rule projections from `procedimiento` and `observacion_clinica`. Compare selected patients, index dates, and attrition with the existing paths for all six scenarios. Record differences that come from changing the index policy.
2. Add Hamilton batch loaders and a shared sample lookup keyed by procedure ID. Verify the same features and scores in a single-instance run and a batch. Use a fixture with two samples in the same time window and keep each sample's results together.
3. Enable the instance-based follow-up list and episode detail on a retained publication. Check pagination and measure both derivation and publication times. Verify repeat publication is idempotent and a late result only updates affected instances.
4. Register the first model versions with explicit feature and visit policies. Compare old and new estimates for matching instances and capture score coverage by scenario before exposing instance-level risks.
## Endpoint 1 · Follow-up list
```http
GET /cacu/seguimiento/instancias?corte=2026-10-20&escenario=cin2_pim_post_treatment&page=1&page_size=50
```
Expose the new granularity through a separate route so current one-item-per-patient consumers can migrate deliberately. An item can include an index date and a compact status for a visit still awaiting results. Filters can include scenario, eligibility, and patient reference where authorized. The response carries a stable `publicacion_id`. Pass it on later pages to retain the same cutoff and data version, with rows ordered by index date and instance ID. `total_items` counts instances.
```json
{
"corte": "2026-10-20",
"publicacion_id": "seg-20261020-01",
"paginacion": {"page": 1, "page_size": 50, "total_items": 1},
"items": [
{
"instancia_id": "ins-82fc",
"paciente_ref": "P-EXAMPLE",
"escenario": "cin2_pim_post_treatment",
"candidato_procedimiento_ref": "pr-526",
"ancla_procedimiento_ref": "pr-301",
"episodio_ref": "eoc-07",
"fecha_indice": "2026-10-15",
"resultados_disponibles_en": null,
"elegibilidad": "pendiente",
"motivos": ["vph_pendiente"],
"version_reglas": "cacu-pim-v1",
"estudios_url": "/cacu/episodios/eoc-07/estudios?publicacion_id=seg-20261020-01"
}
]
}
```
Publish a slim projection for this route and apply filters and pagination in the database. Batch changes for patients affected by new procedures, results, corrections, or rule changes. Upsert changed instance rows by the business key. Readers should see a consistent publication across a refresh. Historical reads require retained revisions or a reproducible source snapshot. Measure derivation time and publication time separately to see which part of the current upload benefits.
## Endpoint 2 · Clinical studies and results for the episode
```http
GET /cacu/episodios/{episodio_ref}/estudios?publicacion_id=seg-20261020-01
```
Resolve the episode and patient, then return the study records linked to that episode and available at the publication cutoff. A patient may have more than one episode. When the source lacks explicit episode membership, publish the links derived from the episode rules as `(episodio_id, procedimiento_id)` pairs in dbt. Use the existing silver join rules for study details. `cacu_citologias` connects the sample and separate reports through their source keys. `cacu_biopsias` follows `padre_id` from the report through the biopsy order to the source sample. For each study return its reference, status, dates, and actual coded or typed results. Preserve multiple findings and represent pending results explicitly. The client can fetch this detail when someone opens an episode.
```json
{
"episodio_ref": "eoc-07",
"paciente_ref": "P-EXAMPLE",
"publicacion_id": "seg-20261020-01",
"estudios": [
{"tipo": "referencia_colposcopia", "orden_ref": "ord-179", "fecha": "2025-05-02", "estado": "atendida", "motivo": "citologia_anormal"},
{"tipo": "colposcopia", "procedimiento_ref": "pr-204", "orden_ref": "ord-179", "fecha": "2025-05-10", "estado": "realizada"},
{"tipo": "biopsia", "procedimiento_ref": "pr-240", "fecha_reporte": "2025-09-25", "estado": "informada", "resultados": [{"codigo": "biopsia.grado", "valor": "LIEAG"}]},
{"tipo": "tratamiento", "procedimiento_ref": "pr-301", "fecha": "2025-10-01", "estado": "realizado", "codigo": "LEEP"},
{"tipo": "citologia", "toma_ref": "pr-526", "reporte_ref": "pr-527", "fecha_toma": "2026-10-15", "fecha_reporte": "2026-10-19", "estado": "informada", "resultados": [{"codigo": "citologia.bethesda", "valor": "NORMAL"}]},
{"tipo": "vph", "toma_ref": "pr-526", "estado": "pendiente", "resultados": []}
]
}
```
Only publish a referral when there is a source order or referral record. Record the performed colposcopy separately and link it to the referral when that relationship is known. Cytology and HPV can share a sample reference while retaining separate report dates and result values. Check access to the patient and episode on the detail request as well as the list request.
## How this fits a FHIR API
Use the CaCu routes as application JSON. A FHIR R5 facade can publish the linked clinical records as FHIR resources under `/fhir`. The scenario instance stays in the application schema because it expresses eligibility for a particular model. The list can include FHIR references for the patient, episode, and study records that have been mapped. [FHIR R5 EpisodeOfCare](https://hl7.org/fhir/R5/episodeofcare.html)
| CaCu record | FHIR R5 representation |
|---|---|
| Care episode | `EpisodeOfCare` for the period of responsibility. Link an actual `Encounter` to the episode through `Encounter.episodeOfCare`. [Episode reference](https://hl7.org/fhir/R5/encounter-definitions.html#Encounter.episodeOfCare) |
| Cytology or HPV | `Specimen` for the collected sample when represented in the source, `DiagnosticReport` for the report, and `Observation` for each coded or quantitative result. Share the specimen reference when it is the same sample. [Specimen](https://hl7.org/fhir/R5/specimen.html) · [DiagnosticReport](https://hl7.org/fhir/R5/diagnosticreport.html) · [Observation](https://hl7.org/fhir/R5/observation.html) |
| Colposcopy referral | `ServiceRequest`. A performed colposcopy can be a `Procedure` linked back through `Procedure.basedOn`. [ServiceRequest](https://hl7.org/fhir/R5/servicerequest.html) · [Procedure](https://hl7.org/fhir/R5/procedure.html) |
| Biopsy | `Procedure` for a documented biopsy collection and `DiagnosticReport` with result `Observation` records for the histology. An order can be a separate `ServiceRequest`. [Procedure](https://hl7.org/fhir/R5/procedure.html) · [DiagnosticReport](https://hl7.org/fhir/R5/diagnosticreport.html) |
| Treatment | `Procedure` for a documented intervention such as LEEP. [Procedure](https://hl7.org/fhir/R5/procedure.html) |
| Computed risk | `RiskAssessment` when a score exists. Use `basis` for the evidence and `prediction` for the outcome, probability, and time horizon. [RiskAssessment](https://hl7.org/fhir/R5/riskassessment.html) |
For a single FHIR response containing all studies, a server could declare an instance operation such as `GET /fhir/EpisodeOfCare/{id}/$estudios` in its `OperationDefinition` and `CapabilityStatement` and return a `Bundle` of type `collection`. This would be a CaCu operation. Its published definition should specify the cutoff parameter, included resource types, and authorization behavior. The application JSON endpoint above is sufficient for the initial follow-up UI. [FHIR operations](https://hl7.org/fhir/R5/operations.html) · [FHIR Bundle](https://hl7.org/fhir/R5/bundle.html)