"""Phase 1 gate: a messy site, drawn once as a pipeline, becomes silver an analyst can trust. The site hides its answers the way real ones do: demographics split between a database and an Excel file with mistyped record numbers, reports as BLOBs in three layouts (some scanned), loose PDFs, a CSV of consultations, and contradicting copies of some reports. """ from datetime import date 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" FIELDS = { "cervical_cytology": ("sample_date", "adequacy", "result", "hpv"), "cervical_biopsy": ("request_date", "histology"), } BOOLS = {"hpv"} def _value(field, v): if v is None: return None if field in BOOLS: return bool(v) return v.isoformat() if isinstance(v, date) else str(v) def test_a_messy_site_becomes_silver_with_no_wrong_value(platform, tmp_path): truth = build(HOSPITAL, tmp_path / "site")["records"] at = {r["where"]: r for r in truth} drawn = PIPELINE.read_text().replace("{site}", str(tmp_path / "site")) (tmp_path / "pipeline.json").write_text(drawn) platform.run("python", "-m", "persistance.config_log", "site", str(tmp_path / "pipeline.json")) platform.ingest() q = platform.query # Which place in the site each record came from (only for checking against the truth). where = { r: f"ArchivosUni:{i}" for i, r in q("select id, _record from bronze.n__site__archivos") } where |= {r: f"files/{n}" for n, r in q("select file_name, _record from bronze.n__site__pdfs")} where |= { r: f"pacientes_his:{n}" for n, r in q("select num, _record from bronze.n__site__his_patients") } # Nobody is merged with somebody else. patients_of: dict[str, set] = {} for record, person in q("select _record, person_id from bronze.n__site__persons"): if record in where: patients_of.setdefault(person, set()).add(at[where[record]]["person"]) assert all(len(p) == 1 for p in patients_of.values()), patients_of patient = {person: next(iter(p)) for person, p in patients_of.items()} # Every value accepted from a document is what the document says. for entity, fields in FIELDS.items(): cols = ", ".join(fields) for record, held, *values in q( f"select _record, _held, {cols} from bronze.staged__{entity}" ): t = at[where[record]] if held is None and not t.get("flipped"): got = {f: _value(f, v) for f, v in zip(fields, values, strict=True)} assert got == {f: t["values"][f] for f in fields}, (t["where"], got) def silver(entity): fields = FIELDS[entity] rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}") return { (patient[p], *(_value(f, v) for f, v in zip(fields, values, strict=True))) for p, *values in rows } def expected(entity, keep): return { (r["person"], *(r["values"][f] for f in FIELDS[entity])) for r in truth if r["entity"] == entity and keep(r) } # Contradicting reports stay out until a reviewer decides; everything else is in. assert silver("cervical_cytology") == expected( "cervical_cytology", lambda r: not r.get("conflict") ) assert silver("cervical_biopsy") == expected("cervical_biopsy", lambda r: True) notes = q("select note_date, specialty, icd10 from silver.clinical_note") assert sorted(tuple(map(str, n)) for n in notes) == sorted( (r["values"]["note_date"], r["values"]["specialty"], r["values"]["icd10"]) for r in truth if r["entity"] == "clinical_note" ) # The reviewer rejects each wrong copy; the next run places the right value. wrong = [rec for rec, w in where.items() if at[w].get("flipped")] assert wrong reject = "; ".join( f"nodes.reject('cervical_cytology', {rec!r}, 'contradicts the original report', 'qa')" for rec in wrong ) platform.run("python", "-c", f"from persistance import nodes; {reject}") platform.ingest() assert silver("cervical_cytology") == expected( "cervical_cytology", lambda r: not r.get("flipped") )