From 9c89c9e10ddd31cffc8b7235d87af88de4e4663a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?= Date: Fri, 27 Nov 2026 01:45:16 -0600 Subject: [PATCH] Corrections of study fields; operator flow on ISSSTELEON's test source (SQL Server, two tables of PDFs) --- tests/test_conectar.py | 158 ++++++++++++++++++++++++----------------- tests/test_webapp.py | 10 +-- webapi/review.py | 23 ++++-- 3 files changed, 113 insertions(+), 78 deletions(-) diff --git a/tests/test_conectar.py b/tests/test_conectar.py index 3fc5092..8696de9 100644 --- a/tests/test_conectar.py +++ b/tests/test_conectar.py @@ -1,12 +1,16 @@ -"""An operator connects a messy site through the API, the way the /conectar screens will: -look into its sources, save the drawn pipeline, run it, read what came out, and settle -what review shows. Real API and Dagster processes; nothing faked.""" +"""An operator connects ISSSTELEON's test source through the API, the way the /conectar +screens do: look into its tables, save the drawn pipeline, run it, read what came out, and +settle what review shows. Real API and Dagster processes; nothing faked.""" import json import time +from sqlalchemy import create_engine, make_url, text + SQL = "dlt.sources.sql_database:sql_database" CYTOLOGY = {"entity": "cervical_cytology"} +STUDIES = ("cervical_cytology", "cervical_biopsy", "mammography", "breast_biopsy", + "breast_treatment", "clinical_note") # fmt: skip def ok(response, status=200): @@ -26,44 +30,47 @@ def run(api, pipeline: str) -> None: wait_for(api, ok(api.post(f"/ingest/pipelines/{pipeline}/runs", json={}))["run_id"]) -def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy_site, tmp_path): - site, truth = messy_site.path, messy_site.truth - database = {"credentials": f"sqlite:///{site}/site.db"} +def test_an_operator_connects_a_site_and_settles_its_review(api, platform, site, tmp_path): + truth = site.truth + database = {"credentials": site.url, "schema": "dbo"} # What the site has, and what one of its tables holds (documents shown by size). found = ok(api.post("/ingest/sources/resources", json={"source": SQL, "args": database})) - assert found == ["ArchivosUni", "pacientes_his"] - missing = {"credentials": f"sqlite:///{tmp_path}/nowhere/site.db"} + assert found == ["ArchivosUni", "ResultadosSubrogados"] + missing = {"credentials": "mssql+pymssql://sa:x@nowhere.invalid:1433/Pruebas"} unreachable = api.post("/ingest/sources/resources", json={"source": SQL, "args": missing}) - assert unreachable.status_code == 422 and "unable to open" in unreachable.text + assert unreachable.status_code == 422, unreachable.text reports = {"id": "reports", "kind": "source", "source": SQL, "args": database} sample = ok( api.post("/ingest/sources/preview?limit=3", json=reports | {"resource": "ArchivosUni"}) ) assert len(sample) == 3 and all(r["Archivo"].endswith(" bytes>") for r in sample) - # A file someone uploads becomes a source like any other. - csv = (site / "files" / "consultas.csv").read_bytes() - uploaded = ok(api.post("/ingest/uploads", files={"file": ("consultas.csv", csv)})) - notes = { - "id": "notes", + # A file someone uploads (a report sent by mail) becomes a source like any other. + engine = create_engine(site.url) + with engine.connect() as con: + pdf = con.execute(text("select Archivo from dbo.ArchivosUni where Id = 1")).scalar() + engine.dispose() + uploaded = ok(api.post("/ingest/uploads", files={"file": ("informe.pdf", pdf)})) + mailed = { + "id": "mailed", "kind": "source", - "source": "dlt.sources.filesystem:readers", - "resource": "read_csv", + "source": "dlt.sources.filesystem:filesystem", "args": {"bucket_url": uploaded["bucket_url"]}, + "then": "persistance.readers:read_bytes", } - assert len(ok(api.post("/ingest/sources/preview?limit=5", json=notes))) == 5 + assert len(ok(api.post("/ingest/sources/preview?limit=5", json=mailed))) == 1 # The site's codes in platform terms: a ConceptMap, saved before the drawing that names # it. One that maps onto a code no field allows is refused, saying which. - drawn = json.loads(messy_site.drawn) + drawn = json.loads(site.drawn) missing = api.put("/ingest/pipelines/site", json=drawn) - assert missing.status_code == 422 and "messy_site" in missing.text - codes = json.loads(messy_site.concept_map.read_text()) + assert missing.status_code == 422 and "erick_site" in missing.text + codes = json.loads(site.concept_map.read_text()) wrong = json.loads(json.dumps(codes).replace('"code": "HSIL"', '"code": "BIRADS-7"')) - refused = api.put("/ingest/concept-maps/messy_site", json=wrong) + refused = api.put("/ingest/concept-maps/erick_site", json=wrong) assert refused.status_code == 422 and "BIRADS-7 is not an allowed code" in refused.text - assert ok(api.put("/ingest/concept-maps/messy_site", json=codes)) == {"version": 1} + assert ok(api.put("/ingest/concept-maps/erick_site", json=codes)) == {"version": 1} # Saving a drawing: broken ones are refused with the reason; good ones get versions. broken = { @@ -77,40 +84,39 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy assert ok(api.get("/ingest/pipelines/site"))["version"] == 1 # A password is never shown, and survives the UI sending the masked drawing back. - secret = "postgresql://isss:S3cret@10.0.10.9/his" - hidden = { - "nodes": [{"id": "his", "kind": "source", "source": SQL, "args": {"credentials": secret}}] - } - ok(api.put("/ingest/pipelines/his", json=hidden)) - shown = ok(api.get("/ingest/pipelines/his"))["pipeline"] - assert "S3cret" not in json.dumps(shown) - assert ok(api.put("/ingest/pipelines/his", json=shown)) == {"version": 2} + shown = ok(api.get("/ingest/pipelines/site"))["pipeline"] + password = make_url(site.url).password + assert password not in json.dumps(shown) + assert ok(api.put("/ingest/pipelines/site", json=shown)) == {"version": 2} stored = platform.query( - "select doc from config.pipelines where pipeline_id = 'his' and version = 2" + "select doc from config.pipelines where pipeline_id = 'site' and version = 2" ) - assert secret in stored[0][0] + assert site.url in stored[0][0] # Run it, and look at what any node produced. run(api, "site") - reports_read = ok(api.get("/ingest/pipelines/site/nodes/archivos/rows?limit=500")) - record_of = {f"ArchivosUni:{r['id']}": r["_record"] for r in reports_read} - his = { - r["_record"]: f"pacientes_his:{r['num']}" - for r in ok(api.get("/ingest/pipelines/site/nodes/his_patients/rows?limit=500")) - } - reports = sum(1 for r in truth if r["where"].startswith("ArchivosUni:")) - assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == reports + record_of = {} + for table, node in (("ArchivosUni", "archivos"), ("ResultadosSubrogados", "subrogados")): + rows = ok(api.get(f"/ingest/pipelines/site/nodes/{node}/rows?limit=500")) + record_of |= {f"{table}:{r['id']}": r["_record"] for r in rows} + assert len(record_of) == len(truth) + forms = sum(1 for r in truth if r["where"].startswith("ArchivosUni:") + and r["entity"] == "cervical_cytology") # fmt: skip + assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == forms # Review: reports that contradict each other, rows held because their person is torn - # (a record number shared by two patients), and persons that may be one patient. - conflicting = {record_of[r["where"]] for r in truth if r.get("conflict")} + # (a pathology report that fits two women of one name), and persons that may be one. + # (a disputed cytology shows all its records: both HPV copies and the form they share) + disputed = {(r["person"], r["values"]["sample_date"]) for r in truth if r.get("conflict")} + conflicting = {record_of[r["where"]] for r in truth if r["entity"] == "cervical_cytology" + and (r["person"], r["values"]["sample_date"]) in disputed} # fmt: skip shown = {c["_record"] for c in ok(api.get("/review/conflicts", params=CYTOLOGY))} assert shown and shown <= conflicting persons = ok(api.get("/review/persons", params={"pipeline": "site", "node": "persons"})) assert persons["to_settle"] and len(persons["torn"]) == 1 # The reviewer settles all of it, checking each case against the source documents. - patient = messy_site.patients(platform.query) + patient = site.patients(platform.query) whose, before = {}, {} for record, person in platform.query("select _record, person_id from bronze.n__site__persons"): whose.setdefault(person, set()).add(patient[record]) @@ -128,35 +134,47 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy merges += same decision = {"person": entry["person"], "candidate": c["candidate"], "same": same} ok(api.post("/review/persons", json=decision), status=201) - collision = {r["where"]: r for r in truth if r.get("collision")} + # The torn person: the pathology reports without a birth date get the one their woman's + # other documents show. + at = {record_of[r["where"]]: r for r in truth} for record in persons["torn"][0]["records"]: - if (where := his.get(record["_record"])) in collision: - fix = { - "record": record["_record"], - "field": "record_number", - "value": collision[where]["true_record_number"], - } + r = at[record["_record"]] + if "birth_date" not in r["identity"]: + fix = {"record": record["_record"], "field": "birth_date", + "value": site.meta["birth_dates"][r["person"]]} # fmt: skip ok(api.post("/review/corrections", json=fix), status=201) - # A row a rule held because its value is wrong (a scan misread) is rejected after a look - # at the document; rows of the torn person wait for the correction above. - misread = [ - h for h in ok(api.get("/review/held", params=CYTOLOGY)) - if not any("disagree on birth date" in why for why in h["_held"]) - ] # fmt: skip - for h in misread: - decision = CYTOLOGY | {"record": h["_record"], "reason": "misread in the scan"} - ok(api.post("/review/rejections", json=decision), status=201) + # A row a rule held because a value came out wrong (a scan misread: "lA" for a stage) + # gets the value the reviewer reads in the document; one with nothing to fix is + # rejected, but for the torn person's rows, which wait for the correction above. + misread = [] + for study in STUDIES: + for h in ok(api.get("/review/held", params={"entity": study})): + torn = any("disagree on birth date" in why for why in h["_held"]) + r = at[h["_record"]] + truly = r.get("clinical_note") if study == "clinical_note" else r["values"] + wrong = {f: v for f, v in truly.items() + if v is not None and str(h["_raw"].get(f)) != str(v)} # fmt: skip + for field, v in wrong.items(): + fix = {"entity": study, "record": h["_record"], "field": field, "value": str(v)} + ok(api.post("/review/corrections", json=fix), status=201) + if not wrong and not torn: + decision = {"entity": study, "record": h["_record"], "reason": "misread"} + ok(api.post("/review/rejections", json=decision), status=201) + misread.append((h["_record"], study)) + stage = {"entity": "breast_biopsy", "record": "x", "field": "stage", "value": "VII"} + assert api.post("/review/corrections", json=stage).status_code == 422 bad = {"record": "x", "field": "birth_date", "value": "not a date"} assert api.post("/review/corrections", json=bad).status_code == 422 # The next run applies every decision: one person per patient, nothing left to review, - # and silver holds every report except the wrong copies. + # and silver holds every cytology but the wrong copies and the misreads. run(api, "site") assert ok(api.get("/review/conflicts", params=CYTOLOGY)) == [] - assert ok(api.get("/review/held", params=CYTOLOGY)) == [] + for study in STUDIES: + assert ok(api.get("/review/held", params={"entity": study})) == [], study left = ok(api.get("/review/persons", params={"pipeline": "site", "node": "persons"})) assert left == {"to_settle": [], "torn": []} - people = {r["person"] for r in truth if r["entity"] == "identity"} + people = {r["person"] for r in truth} groups = {} for record, person in platform.query("select _record, person_id from bronze.n__site__persons"): groups.setdefault(person, set()).add(patient[record]) @@ -171,7 +189,15 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy for old, new in replaced.items(): assert new in set(after.values()) assert any(before[r] == old and after[r] == new for r in before) - assert set(after.values()) <= set(before.values()) # no person got a new id - placed = platform.count("silver.cervical_cytology") - reports = sum(1 for r in truth if r["entity"] == "cervical_cytology" and not r.get("flipped")) - assert placed == reports - len(misread) + # No person got a new id, but for the woman parted from the torn person (two namesakes + # one pathology report had joined): her records all come from that person. + new = set(after.values()) - set(before.values()) + torn_id = persons["torn"][0]["person"] + assert len(new) <= 1 + assert all(before[r] == torn_id for r, p in after.items() if p in new) + rejected = {r for r, study in misread if study == "cervical_cytology"} + rejected |= {record_of[r["where"]] for r in truth if r.get("flipped")} + cytologies = {(r["person"], r["values"]["sample_date"]) for r in truth + if r["entity"] == "cervical_cytology" + and record_of[r["where"]] not in rejected} # fmt: skip + assert platform.count("silver.cervical_cytology") == len(cytologies) diff --git a/tests/test_webapp.py b/tests/test_webapp.py index 82e5ba4..e07474b 100644 --- a/tests/test_webapp.py +++ b/tests/test_webapp.py @@ -1,7 +1,7 @@ """Phase 3 and 4 gate, the WebApp: every page loads from the new API. The platform runs as in production (API, Dagster), loaded with the synthetic CaCu and CaMa hospitals (CaMa's -models trained, none promoted) and the messy site; Playwright drives the real pages against -it (WebApp/e2e).""" +models trained, none promoted) and ISSSTELEON's test source; Playwright drives the real +pages against it (WebApp/e2e).""" import json import os @@ -20,7 +20,7 @@ PIPELINES = ROOT / "tests" / "fixtures" / "pipelines" @pytest.mark.webapp @pytest.mark.parametrize("platform", ["sqlite"], indirect=True) # pages read one API either way -def test_every_page_loads_from_the_api(api, platform, messy_site): +def test_every_page_loads_from_the_api(api, platform, site): for domain in ("cacu", "cama"): drawn = (PIPELINES / f"hospital_{domain}.json").read_text() put_concept_map(api, f"hospital_{domain}") @@ -29,8 +29,8 @@ def test_every_page_loads_from_the_api(api, platform, messy_site): run(api, domain) # A trained CaMa version, unpromoted: what the governance page shows and refuses. wait_for(api, ok(api.post("/models/cama/train", json={"as_of": "2026-11-24"}))["run_id"]) - put_concept_map(api, "messy_site") - ok(api.put("/ingest/pipelines/site", json=json.loads(messy_site.drawn))) + put_concept_map(api, "erick_site") + ok(api.put("/ingest/pipelines/site", json=json.loads(site.drawn))) run(api, "site") subprocess.run(["npx", "playwright", "test"], cwd=ROOT / "WebApp", check=True, env={**os.environ, "API_URL": str(api.base_url).rstrip("/")}) # fmt: skip diff --git a/webapi/review.py b/webapi/review.py index e434917..da8e206 100644 --- a/webapi/review.py +++ b/webapi/review.py @@ -1,12 +1,12 @@ """What waits for a person, and their decisions (append-only; the next run applies them).""" -from typing import Any, Literal +from typing import Any from fastapi import APIRouter, Depends from pydantic import BaseModel, model_validator from core.pipeline import EntityName, Id, validate -from core.schema import Identity +from core.schema import ENTITIES from persistance import nodes, review from webapi.auth import Caller, caller @@ -47,22 +47,31 @@ def decide_persons(decision: PersonDecision, who: Caller = Depends(caller)) -> d class Correction(BaseModel): + """One field of one record as a reviewer read it in the source document: an identity + field (a mistyped record number) or a study's (a stage the scan made unreadable).""" + + entity: EntityName = "identity" record: str - field: Literal[tuple(Identity.model_fields)] # type: ignore[valid-type] + field: str value: str @model_validator(mode="after") def _a_valid_value(self): - if reasons := validate("identity", {self.field: self.value}): + if self.field not in ENTITIES[self.entity].model_fields: + raise ValueError(f"{self.entity} has no field {self.field}") + # only this field's own problems (a study's other required fields aren't given here) + reasons = [r for r in validate(self.entity, {self.field: self.value}) + if r.split(":")[0] == self.field] # fmt: skip + if reasons: raise ValueError("; ".join(reasons)) return self @router.post("/corrections", status_code=201) def correct(fix: Correction, who: Caller = Depends(caller)) -> dict[str, str]: - """A corrected identity field of one record (e.g. a mistyped record number); linking - uses it on the next run. Fixing the source too is still worth it.""" - nodes.correct(fix.record, fix.field, fix.value, who.id) + """A corrected field of one record; the next run uses it (linking for identity fields, + the study's target for the others). Fixing the source too is still worth it.""" + nodes.correct(fix.record, fix.field, fix.value, who.id, fix.entity) return {"record": fix.record}