Compare commits

..

1 Commits

Author SHA1 Message Date
Angel Capetillo Zavala fee6a6622d CaMa: account for provisional measure in integration test 2026-12-01 12:27:18 -06:00
3 changed files with 5 additions and 106 deletions
-67
View File
@@ -1,67 +0,0 @@
"""Automático through the API, as the Conectar button uses it: an operator connects
ISSSTELEON's test source and nothing else; the site's language model (LLM_URL: at
ISSSTELEON, its SGLang) drafts the whole pipeline, which is saved and run. What it places
must agree with the pipeline an operator drew, record by record. Real processes and the
real endpoint; nothing faked."""
import json
from test_conectar import ok, wait_for
SOURCE = "resultados"
# Studies whose every record the operator's drawing places, the draft must place too.
DRAWN = ("cervical_cytology", "mammography", "cervical_biopsy", "breast_biopsy")
HOURS = 3600 # with a model answering, it reads every document: an hour or more per run
def staged(platform, pipeline: str) -> dict[tuple, object]:
"""What a pipeline's targets staged, clean rows only: (study, record, field) -> value."""
rows = platform.query(
"select study, _record, field, value_text, value_num, value_bool, value_date "
f"from bronze.staged__observation where _pipeline = '{pipeline}'"
)
return {(s, r, f): next((v for v in vs if v is not None), None) for s, r, f, *vs in rows}
def test_automatico_drafts_a_sites_pipeline_and_runs_it(api, platform, site):
model = ok(api.get("/ingest/llm"))
assert model["available"], model["reason"]
drawn = json.loads(site.drawn)
source = next(n for n in drawn["nodes"] if n["id"] == SOURCE)
# Automático starts from the sources alone: a drawing with more is refused.
ok(api.put("/ingest/pipelines/half", json={"nodes": drawn["nodes"][:2]}))
assert api.post("/ingest/pipelines/half/draft").status_code == 422
assert api.post("/ingest/pipelines/nowhere/draft").status_code == 404
ok(api.put("/ingest/pipelines/auto", json={"nodes": [source]}))
wait_for(api, ok(api.post("/ingest/pipelines/auto/draft"))["run_id"], seconds=3 * HOURS)
saved = ok(api.get("/ingest/pipelines/auto"))
assert saved["version"] == 2
kinds = [n["kind"] for n in saved["pipeline"]["nodes"]]
assert {"read", "route", "extract", "link", "target"} <= set(kinds)
studies = {n["entity"] for n in saved["pipeline"]["nodes"] if n["kind"] == "target"}
# One layout may report several studies: pathology by organ, notes by what they record.
assert set(DRAWN) | {"breast_treatment", "death"} <= studies, studies
# Documents no route claims wait for a reviewer, as with a drawn pipeline.
assert any(n.get("otherwise") for n in saved["pipeline"]["nodes"])
# The operator's own drawing over the same source: where both placed a value, the same.
ok(api.put("/ingest/concept-maps/erick_site", json=json.loads(site.concept_map.read_text())))
ok(api.put("/ingest/pipelines/site", json=drawn))
wait_for(api, ok(api.post("/ingest/pipelines/site/runs", json={}))["run_id"], 2 * HOURS)
mine, theirs = staged(platform, "auto"), staged(platform, "site")
both = set(mine) & set(theirs)
differ = {k: (mine[k], theirs[k]) for k in both if str(mine[k]) != str(theirs[k])}
assert both and not differ, differ
for study in DRAWN:
drawn_records = {r for s, r, _ in theirs if s == study}
assert drawn_records <= {r for s, r, _ in mine if s == study}, study
# Each case review waits on carries the model's reading, and still waits for a person.
link = next(n["id"] for n in saved["pipeline"]["nodes"] if n["kind"] == "link")
persons = ok(api.get("/review/persons", params={"pipeline": "auto", "node": link}))
for entry in persons["to_settle"]:
assert all(c["suggestion"]["reason"] for c in entry["candidates"])
for entry in persons["torn"]:
assert entry["suggestion"]["reason"]
+4 -2
View File
@@ -30,6 +30,7 @@ PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cama.json"
CAPTURED_ON = "2026-11-26" # the day of the capture's load: durations counted to it CAPTURED_ON = "2026-11-26" # the day of the capture's load: durations counted to it
TRAINED_ON = "2026-11-24" # survival's follow-up ended the day the reference was trained TRAINED_ON = "2026-11-24" # survival's follow-up ended the day the reference was trained
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)] PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
NEW = {"CAMA_DIAS_RESULTADO_BIOPSIA"} # tests/test_cama_biopsy_time.py
CODES = { # platform code -> the current platform's CODES = { # platform code -> the current platform's
**{c: f"B{c}" for c in ("0", "1", "2", "3", "4", "5", "6")}, **{c: f"B{c}" for c in ("0", "1", "2", "3", "4", "5", "6")},
"4A": "B4", "4B": "B4", "4C": "B4", "4A": "B4", "4B": "B4", "4C": "B4",
@@ -128,8 +129,9 @@ def test_cama_from_the_hospital_to_indicators(api, platform, tmp_path):
# Indicators: every measure, every semester, as the current platform answers them. # Indicators: every measure, every semester, as the current platform answers them.
reference = json.loads((REFERENCE / "indicators.json").read_text()) reference = json.loads((REFERENCE / "indicators.json").read_text())
(measures,) = pages(api, "/cama/fhir/Measure") (measures,) = pages(api, "/cama/fhir/Measure")
assert {m["resource"]["name"] for m in measures["entry"]} == set(reference) # A measure the current platform never had (not in its capture) is checked by its own tests.
for measure in [e["resource"] for e in measures["entry"]]: assert {m["resource"]["name"] for m in measures["entry"]} == set(reference) | NEW
for measure in [e["resource"] for e in measures["entry"] if e["resource"]["name"] not in NEW]:
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS), params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON} # fmt: skip "event-cutoff": CAPTURED_ON} # fmt: skip
found = [e for b in pages(api, "/cama/fhir/MeasureReport", params) for e in b["entry"]] found = [e for b in pages(api, "/cama/fhir/MeasureReport", params) for e in b["entry"]]
+1 -37
View File
@@ -10,7 +10,7 @@ from pydantic import BaseModel
from core import concept_map from core import concept_map
from core.pipeline import ID_PATTERN, ImportPath, Pipeline, Source, redacted, restored from core.pipeline import ID_PATTERN, ImportPath, Pipeline, Source, redacted, restored
from core.schema import ENTITIES from core.schema import ENTITIES
from persistance import config_log, llm, nodes from persistance import config_log, nodes
from webapi.runs import dagster from webapi.runs import dagster
router = APIRouter(prefix="/ingest", tags=["ingest"]) router = APIRouter(prefix="/ingest", tags=["ingest"])
@@ -140,42 +140,6 @@ def submit(client: DagsterGraphQLClient, pipeline_id: str, version: int | None =
raise HTTPException(502, detail=str(e)) from e raise HTTPException(502, detail=str(e)) from e
class LanguageModel(BaseModel):
available: bool
model: str | None
vision: bool # reads page images (scans), not only their OCR text
reason: str | None # why it is not available
@router.get("/llm")
def language_model() -> LanguageModel:
"""The site's language model (LLM_URL): whether it answers, which, and whether it
reads images. Automático needs it; extract nodes use their patterns without it."""
return LanguageModel(**llm.status())
@router.post("/pipelines/{pipeline_id}/draft")
def start_draft(
pipeline_id: PipelineId, run: bool = True, client: DagsterGraphQLClient = Depends(dagster)
) -> dict[str, str]:
"""Automático: starts the `draft` job, which draws the whole pipeline from its saved
sources (the only nodes it may hold), saves it as a new version and runs it (`run`
false: drawn and saved only); follow it at /runs/{run_id}."""
if not config_log.latest_version(pipeline_id):
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
_, saved = config_log.get(pipeline_id)
if not saved.nodes or any(n.kind != "source" for n in saved.nodes):
raise HTTPException(422, detail="Automático arma la canalización a partir de sus "
"fuentes: guárdela solo con ellas.") # fmt: skip
if not (found := llm.status())["available"]:
raise HTTPException(503, detail=f"El modelo de lenguaje no responde: {found['reason']}")
config = {"ops": {"draft_pipeline": {"config": {"pipeline": pipeline_id, "run": run}}}}
try:
return {"run_id": client.submit_job_execution("draft", run_config=config)}
except DagsterGraphQLClientError as e:
raise HTTPException(502, detail=str(e)) from e
@router.get("/pipelines/{pipeline_id}/nodes/{node_id}/rows") @router.get("/pipelines/{pipeline_id}/nodes/{node_id}/rows")
def node_rows( def node_rows(
pipeline_id: PipelineId, pipeline_id: PipelineId,