Review persons: settle possible splits, correct identity fields; operator test settles everything
This commit is contained in:
+61
-23
@@ -4,13 +4,7 @@ what review shows. Real API and Dagster processes; nothing faked."""
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from synthetic.site import build
|
|
||||||
|
|
||||||
ROOT = Path(__file__).parents[2]
|
|
||||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital" / "hospital_cacu.db"
|
|
||||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "messy_site.json"
|
|
||||||
SQL = "dlt.sources.sql_database:sql_database"
|
SQL = "dlt.sources.sql_database:sql_database"
|
||||||
CYTOLOGY = {"entity": "cervical_cytology"}
|
CYTOLOGY = {"entity": "cervical_cytology"}
|
||||||
|
|
||||||
@@ -32,9 +26,8 @@ def run(api, pipeline: str) -> None:
|
|||||||
wait_for(api, ok(api.post(f"/ingest/pipelines/{pipeline}/runs", json={}))["run_id"])
|
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, tmp_path):
|
def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy_site, tmp_path):
|
||||||
site = tmp_path / "site"
|
site, truth = messy_site.path, messy_site.truth
|
||||||
truth = build(HOSPITAL, site)["records"]
|
|
||||||
database = {"credentials": f"sqlite:///{site}/site.db"}
|
database = {"credentials": f"sqlite:///{site}/site.db"}
|
||||||
|
|
||||||
# What the site has, and what one of its tables holds (documents shown by size).
|
# What the site has, and what one of its tables holds (documents shown by size).
|
||||||
@@ -52,22 +45,32 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, tmp_p
|
|||||||
# A file someone uploads becomes a source like any other.
|
# A file someone uploads becomes a source like any other.
|
||||||
csv = (site / "files" / "consultas.csv").read_bytes()
|
csv = (site / "files" / "consultas.csv").read_bytes()
|
||||||
uploaded = ok(api.post("/ingest/uploads", files={"file": ("consultas.csv", csv)}))
|
uploaded = ok(api.post("/ingest/uploads", files={"file": ("consultas.csv", csv)}))
|
||||||
notes = {"id": "notes", "kind": "source", "source": "dlt.sources.filesystem:readers",
|
notes = {
|
||||||
"resource": "read_csv", "args": {"bucket_url": uploaded["bucket_url"]}} # fmt: skip
|
"id": "notes",
|
||||||
|
"kind": "source",
|
||||||
|
"source": "dlt.sources.filesystem:readers",
|
||||||
|
"resource": "read_csv",
|
||||||
|
"args": {"bucket_url": uploaded["bucket_url"]},
|
||||||
|
}
|
||||||
assert len(ok(api.post("/ingest/sources/preview?limit=5", json=notes))) == 5
|
assert len(ok(api.post("/ingest/sources/preview?limit=5", json=notes))) == 5
|
||||||
|
|
||||||
# Saving a drawing: broken ones are refused with the reason; good ones get versions.
|
# Saving a drawing: broken ones are refused with the reason; good ones get versions.
|
||||||
drawn = json.loads(PIPELINE.read_text().replace("{site}", str(site)))
|
drawn = json.loads(messy_site.drawn)
|
||||||
broken = {"nodes": [*drawn["nodes"], {"id": "loose", "kind": "read", "inputs": ["gone"],
|
broken = {
|
||||||
"column": "x"}]} # fmt: skip
|
"nodes": [
|
||||||
|
*drawn["nodes"],
|
||||||
|
{"id": "loose", "kind": "read", "inputs": ["gone"], "column": "x"},
|
||||||
|
]
|
||||||
|
}
|
||||||
assert "no node" in api.put("/ingest/pipelines/site", json=broken).text
|
assert "no node" in api.put("/ingest/pipelines/site", json=broken).text
|
||||||
assert ok(api.put("/ingest/pipelines/site", json=drawn)) == {"version": 1}
|
assert ok(api.put("/ingest/pipelines/site", json=drawn)) == {"version": 1}
|
||||||
assert ok(api.get("/ingest/pipelines/site"))["version"] == 1
|
assert ok(api.get("/ingest/pipelines/site"))["version"] == 1
|
||||||
|
|
||||||
# A password is never shown, and survives the UI sending the masked drawing back.
|
# A password is never shown, and survives the UI sending the masked drawing back.
|
||||||
secret = "postgresql://isss:S3cret@10.0.10.9/his"
|
secret = "postgresql://isss:S3cret@10.0.10.9/his"
|
||||||
hidden = {"nodes": [{"id": "his", "kind": "source", "source": SQL,
|
hidden = {
|
||||||
"args": {"credentials": secret}}]} # fmt: skip
|
"nodes": [{"id": "his", "kind": "source", "source": SQL, "args": {"credentials": secret}}]
|
||||||
|
}
|
||||||
ok(api.put("/ingest/pipelines/his", json=hidden))
|
ok(api.put("/ingest/pipelines/his", json=hidden))
|
||||||
shown = ok(api.get("/ingest/pipelines/his"))["pipeline"]
|
shown = ok(api.get("/ingest/pipelines/his"))["pipeline"]
|
||||||
assert "S3cret" not in json.dumps(shown)
|
assert "S3cret" not in json.dumps(shown)
|
||||||
@@ -81,23 +84,58 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, tmp_p
|
|||||||
run(api, "site")
|
run(api, "site")
|
||||||
reports_read = ok(api.get("/ingest/pipelines/site/nodes/archivos/rows?limit=500"))
|
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}
|
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"))
|
||||||
|
}
|
||||||
assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == 53
|
assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == 53
|
||||||
|
|
||||||
# Review shows exactly the reports that contradict each other; nothing else is held.
|
# 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")}
|
conflicting = {record_of[r["where"]] for r in truth if r.get("conflict")}
|
||||||
assert {c["_record"] for c in ok(api.get("/review/conflicts", params=CYTOLOGY))} == conflicting
|
shown = {c["_record"] for c in ok(api.get("/review/conflicts", params=CYTOLOGY))}
|
||||||
assert ok(api.get("/review/held", params=CYTOLOGY)) == []
|
assert shown and shown <= conflicting
|
||||||
assert isinstance(
|
persons = ok(api.get("/review/persons", params={"pipeline": "site", "node": "persons"}))
|
||||||
ok(api.get("/review/links", params={"pipeline": "site", "node": "persons"})), list
|
assert persons["to_settle"] and len(persons["torn"]) == 1
|
||||||
)
|
|
||||||
|
|
||||||
# The reviewer rejects the wrong copies; the next run settles the conflicts.
|
# The reviewer settles all of it, checking each case against the source documents.
|
||||||
|
patient = messy_site.patients(platform.query)
|
||||||
|
whose = {}
|
||||||
|
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
|
||||||
|
whose.setdefault(person, set()).add(patient[record])
|
||||||
for r in truth:
|
for r in truth:
|
||||||
if r.get("flipped"):
|
if r.get("flipped"):
|
||||||
decision = CYTOLOGY | {"record": record_of[r["where"]], "reason": "flipped HPV"}
|
decision = CYTOLOGY | {"record": record_of[r["where"]], "reason": "flipped HPV"}
|
||||||
ok(api.post("/review/rejections", json=decision), status=201)
|
ok(api.post("/review/rejections", json=decision), status=201)
|
||||||
|
for entry in persons["to_settle"]:
|
||||||
|
for c in entry["candidates"]:
|
||||||
|
same = whose[entry["person"]] == whose[c["candidate"]]
|
||||||
|
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")}
|
||||||
|
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"],
|
||||||
|
}
|
||||||
|
ok(api.post("/review/corrections", json=fix), status=201)
|
||||||
|
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.
|
||||||
run(api, "site")
|
run(api, "site")
|
||||||
assert ok(api.get("/review/conflicts", params=CYTOLOGY)) == []
|
assert ok(api.get("/review/conflicts", params=CYTOLOGY)) == []
|
||||||
|
assert ok(api.get("/review/held", params=CYTOLOGY)) == []
|
||||||
|
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"}
|
||||||
|
groups = {}
|
||||||
|
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
|
||||||
|
groups.setdefault(person, set()).add(patient[record])
|
||||||
|
assert sorted(map(sorted, groups.values())) == sorted([p] for p in people)
|
||||||
placed = platform.count("silver.cervical_cytology")
|
placed = platform.count("silver.cervical_cytology")
|
||||||
assert placed == sum(
|
assert placed == sum(
|
||||||
1 for r in truth if r["entity"] == "cervical_cytology" and not r.get("flipped")
|
1 for r in truth if r["entity"] == "cervical_cytology" and not r.get("flipped")
|
||||||
|
|||||||
+42
-7
@@ -1,11 +1,12 @@
|
|||||||
"""What waits for a person, and their decisions (append-only; the next run applies them)."""
|
"""What waits for a person, and their decisions (append-only; the next run applies them)."""
|
||||||
|
|
||||||
from typing import Any
|
from typing import Any, Literal
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends
|
from fastapi import APIRouter, Depends
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel, model_validator
|
||||||
|
|
||||||
from core.pipeline import EntityName, Id
|
from core.pipeline import EntityName, Id, validate
|
||||||
|
from core.schema import Identity
|
||||||
from persistance import nodes, review
|
from persistance import nodes, review
|
||||||
from webapi.auth import Caller, caller
|
from webapi.auth import Caller, caller
|
||||||
|
|
||||||
@@ -25,10 +26,44 @@ def conflicts(entity: EntityName) -> Rows:
|
|||||||
return review.conflicts(entity)
|
return review.conflicts(entity)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/links")
|
@router.get("/persons")
|
||||||
def links(pipeline: Id, node: Id) -> Rows:
|
def persons(pipeline: Id, node: Id) -> dict[str, Rows]:
|
||||||
"""Records that may be the same person but were left apart."""
|
"""Persons to settle (with their possible owners) and torn persons (with their
|
||||||
return review.links(pipeline, node)
|
records) left by a pipeline's link node."""
|
||||||
|
return review.persons(pipeline, node)
|
||||||
|
|
||||||
|
|
||||||
|
class PersonDecision(BaseModel):
|
||||||
|
person: str
|
||||||
|
candidate: str
|
||||||
|
same: bool
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/persons", status_code=201)
|
||||||
|
def decide_persons(decision: PersonDecision, who: Caller = Depends(caller)) -> dict[str, str]:
|
||||||
|
"""Whether a person and a possible owner are one patient; applied on the next run."""
|
||||||
|
nodes.decide_persons(decision.person, decision.candidate, decision.same, who.id)
|
||||||
|
return {"person": decision.person}
|
||||||
|
|
||||||
|
|
||||||
|
class Correction(BaseModel):
|
||||||
|
record: str
|
||||||
|
field: Literal[tuple(Identity.model_fields)] # type: ignore[valid-type]
|
||||||
|
value: str
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def _a_valid_value(self):
|
||||||
|
if reasons := validate("identity", {self.field: self.value}):
|
||||||
|
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)
|
||||||
|
return {"record": fix.record}
|
||||||
|
|
||||||
|
|
||||||
class Rejection(BaseModel):
|
class Rejection(BaseModel):
|
||||||
|
|||||||
Reference in New Issue
Block a user