diff --git a/models/dbt_project.py b/models/dbt_project.py deleted file mode 100644 index 9676379..0000000 --- a/models/dbt_project.py +++ /dev/null @@ -1,8 +0,0 @@ -"""The dbt project, alone so `dagster-dbt project prepare-and-package` can build its manifest.""" - -from dagster_dbt import DbtProject - -from persistance.config import DBT_DIR - -dbt_project = DbtProject(project_dir=DBT_DIR, profiles_dir=DBT_DIR) -dbt_project.prepare_if_dev() diff --git a/models/graph.py b/models/graph.py index cfa420e..616fb1c 100644 --- a/models/graph.py +++ b/models/graph.py @@ -1,19 +1,45 @@ -"""Runs a pipeline graph: each node, after its inputs, writes its output table.""" +"""Runs a pipeline graph: each node, after its inputs, writes its output table; then dbt +places what the targets staged into silver.""" import hashlib import io +import json +import os from collections.abc import Callable from concurrent.futures import ProcessPoolExecutor from functools import cache -import dlt import ocrmypdf +import pandas as pd +import pdfplumber +import splink.comparison_library as cl from markitdown import MarkItDown -from sqlalchemy import inspect, text +from openai import OpenAI, OpenAIError +from splink import Linker, SettingsCreator +from splink.backends.duckdb import DuckDBAPI -from core.pipeline import Pipeline, Read -from persistance import nodes -from persistance.destination import engine, platform +from core.pipeline import ( + HELD, + QUOTES, + RECORD, + Extract, + Join, + Link, + Map, + Pipeline, + Read, + Route, + Target, + answer_schema, + apply_patterns, + ground, + join, + map_row, + matches, + validate, +) +from core.schema import ENTITIES +from persistance import nodes, silver MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error` @@ -28,75 +54,219 @@ def _reader() -> MarkItDown: return MarkItDown() +def _text(content: bytes) -> str: + """PDFs through pdfplumber's layout mode, which keeps a table's rows on one line each + (spacing within a line collapsed); every other format through MarkItDown.""" + if content.startswith(b"%PDF"): + with pdfplumber.open(io.BytesIO(content)) as pdf: + text = "\n".join(page.extract_text(layout=True) or "" for page in pdf.pages) + return "\n".join(" ".join(line.split()) for line in text.splitlines() if line.strip()) + return _reader().convert_stream(io.BytesIO(content)).text_content + + def read_file(content: bytes) -> dict: """Text of one file, and whether OCR was needed. An unreadable file keeps its error.""" try: - found = _reader().convert_stream(io.BytesIO(content)).text_content + found = _text(content) ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS if ocr: out = io.BytesIO() ocrmypdf.ocr( - io.BytesIO(content), - out, - language="spa", - skip_text=True, - output_type="pdf", - optimize=0, - progress_bar=False, - jobs=1, - ) - found = _reader().convert_stream(io.BytesIO(out.getvalue())).text_content + io.BytesIO(content), out, language="spa", skip_text=True, + output_type="pdf", optimize=0, progress_bar=False, jobs=1, deskew=True, + ) # fmt: skip + found = _text(out.getvalue()) return {"text": found, "ocr": ocr, "error": None} except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"} -def _cached(shas: set[str]) -> dict[str, dict]: - """Files already read, by content hash, in any node of any pipeline.""" - with engine().connect() as con: - if not inspect(con).has_table("read_cache", schema="bronze"): - return {} - rows = con.execute(text("select sha256, text, ocr, error from bronze.read_cache")) - return {r.sha256: dict(r._mapping) for r in rows if r.sha256 in shas} - - -def run_read(pipeline_id: str, node: Read): +def run_read(p: str, node: Read): """The input's rows with the file column replaced by its text; each file read once.""" - source = node.inputs[0] - rows = list(nodes.rows(pipeline_id, source)) + rows = list(nodes.rows(p, node.inputs[0])) + keys = {} for row in rows: content = row.pop(node.column) - row["sha256"] = hashlib.sha256(content).hexdigest() if content else None - row["_content"] = content - found = _cached({r["sha256"] for r in rows if r["sha256"]}) - new = {r["sha256"]: r["_content"] for r in rows if r["sha256"] and r["sha256"] not in found} + row["key"] = hashlib.sha256(content).hexdigest() if content else None + keys[row["key"]] = content + found = nodes.cached("read_cache", set(keys) - {None}) + new = {k: c for k, c in keys.items() if k and k not in found} with ProcessPoolExecutor() as pool: read = dict(zip(new, pool.map(read_file, new.values()), strict=True)) - if read: - cache_rows = [{"sha256": sha, **result} for sha, result in read.items()] - dlt.pipeline("read_cache", destination=platform(), dataset_name="bronze").run( - dlt.resource( - cache_rows, - name="read_cache", - primary_key="sha256", - write_disposition="merge", - columns=READ_COLUMNS, - ) - ) + nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], READ_COLUMNS) found |= read for row in rows: - row.pop("_content") - result = found.get(row["sha256"], {"text": None, "ocr": False, "error": "empty"}) - row.update({k: result[k] for k in READ_COLUMNS}) - return nodes.write(pipeline_id, node.id, rows, nodes.key(pipeline_id, source), READ_COLUMNS) + result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"}) + row |= {k: result[k] for k in READ_COLUMNS} + return nodes.write(p, node.id, rows, READ_COLUMNS) -RUNNERS: dict[str, Callable] = {"source": nodes.run_source, "read": run_read} +def run_route(p: str, node: Route): + return nodes.write(p, node.id, [r for r in nodes.rows(p, node.inputs[0]) if matches(node, r)]) + + +def run_map(p: str, node: Map): + return nodes.write(p, node.id, [map_row(node, r) for r in nodes.rows(p, node.inputs[0])]) + + +def run_join(p: str, node: Join): + left, right = (list(nodes.rows(p, i)) for i in node.inputs) + return nodes.write(p, node.id, join(node, left, right, node.inputs[1])) + + +@cache +def _llm() -> tuple[OpenAI, str] | None: + """The configured OpenAI-compatible endpoint, if it answers; None otherwise.""" + if not (url := os.environ.get("LLM_URL")): + return None + client = OpenAI(base_url=url, api_key=os.environ.get("LLM_API_KEY", "none"), timeout=600) + try: + client.models.list() + except OpenAIError: + return None + return client, os.environ["LLM_MODEL"] + + +PROMPT = ( + "Extract every {entity} record stated in the document. For each field give its value " + "in the schema's terms and `quote`: the exact text of the document it was read from, " + "copied character by character. Leave out fields the document does not state.{hints}" +) + + +def _ask_llm(node: Extract, text: str) -> dict: + client, model = _llm() + system = PROMPT.format(entity=node.entity, hints=f"\n{node.hints}" if node.hints else "") + key = hashlib.sha256(json.dumps([model, system, text]).encode()).hexdigest() + if found := nodes.cached("llm_cache", {key}): + return json.loads(found[key]["answer"]) + reply = client.chat.completions.create( + model=model, temperature=0, seed=7, + messages=[{"role": "system", "content": system}, {"role": "user", "content": text}], + response_format={"type": "json_schema", "json_schema": { + "name": "answer", "schema": answer_schema(node.entity), "strict": True}}, + ) # fmt: skip + answer = reply.choices[0].message.content + nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {}) + return json.loads(answer) + + +def run_extract(p: str, node: Extract): + use_llm = node.method == "llm" or (node.method == "auto" and _llm() is not None) + out = [] + for row in nodes.rows(p, node.inputs[0]): + text = row.get(node.column) or "" + if use_llm: + found = ground(_ask_llm(node, text), text) + elif node.patterns: + found = apply_patterns(node, text) + else: + found = [({}, {}, ["no LLM answering and no patterns set"])] + for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]): + out.append({**values, RECORD: row[RECORD], "_index": index, + QUOTES: json.dumps(quotes, ensure_ascii=False), + HELD: json.dumps(held) if held else None}) # fmt: skip + return nodes.write(p, node.id, out) + + +def _comparison(field: str): + if field == "birth_date": + return cl.DateOfBirthComparison(field, input_is_string=True) + if field == "full_name": + return cl.NameComparison(field) + if field in ("record_number", "curp", "nss"): + return cl.LevenshteinAtThresholds(field, [1, 2]) + return cl.ExactMatch(field) + + +def run_link(p: str, node: Link): + """Persons from the node's rules (Splink deterministic linking and clustering). A person + whose records disagree on birth date or sex is held; pairs Splink scores above + `review` that the rules left apart are queued for review.""" + records: dict[str, dict] = {} + for i in node.inputs: + for row in nodes.rows(p, i): + if row.get(HELD): + continue + mine = records.setdefault(row[RECORD], {"unique_id": row[RECORD]}) + for f in node.fields: + if row.get(f) is not None and mine.get(f) is None: + mine[f] = str(row[f]) + frame = pd.DataFrame(list(records.values())) + fields = [f for f in node.fields if f in frame and frame[f].notna().any()] + frame = frame[["unique_id", *fields]] + rules = node.rules or node.default_rules() + rules = [r for r in rules if all(f"l.{f}" not in r or f in fields for f in node.fields)] + settings = SettingsCreator( + link_type="dedupe_only", + comparisons=[_comparison(f) for f in fields], + blocking_rules_to_generate_predictions=rules, + ) + linker = Linker(DuckDBAPI().register(frame), settings, log_level=None) + sure = linker.inference.deterministic_link() + clusters = linker.clustering.cluster_pairwise_predictions_at_threshold(sure) + persons = clusters.as_pandas_dataframe()[["unique_id", "cluster_id"]].merge(frame) + facts = [f for f in ("birth_date", "sex") if f in fields] + torn = set() + if facts: + spread = persons.groupby("cluster_id")[facts].nunique() + torn = set(spread[(spread > 1).any(axis=1)].index) + held = json.dumps(["records of this person disagree on birth date or sex"]) + nodes.write(p, node.id, [ + {RECORD: r.unique_id, "person_id": r.cluster_id, + HELD: held if r.cluster_id in torn else None} + for r in persons.itertuples() + ], {HELD: {"data_type": "text", "nullable": True}}) # fmt: skip + + linker.training.estimate_u_using_random_sampling(max_pairs=1e6) + person = dict(zip(persons.unique_id, persons.cluster_id, strict=True)) + maybe = linker.inference.predict(threshold_match_probability=node.review).as_pandas_dataframe() + return nodes.write(p, f"{node.id}__review", [ + {"record_l": r.unique_id_l, "record_r": r.unique_id_r, "probability": r.match_probability} + for r in maybe.itertuples() if person[r.unique_id_l] != person[r.unique_id_r] + ]) # fmt: skip + + +def run_target(p: str, node: Target, kinds: dict[str, str]): + link = next(i for i in node.inputs if kinds[i] == "link") + linked = {r[RECORD]: r for r in nodes.rows(p, link)} + person = {k: r["person_id"] for k, r in linked.items()} + model = ENTITIES[node.entity] + out = [] + for i in (i for i in node.inputs if i != link): + for row in nodes.rows(p, i): + values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None} + held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values) + if row[RECORD] not in person: + held.append("no identity linked to this record") + else: + held += json.loads(linked[row[RECORD]].get(HELD) or "[]") + staged = { + "person_id": person.get(row[RECORD]), RECORD: row[RECORD], + "_index": row.get("_index", 0), QUOTES: row.get(QUOTES), + HELD: json.dumps(held) if held else None, + "_raw": json.dumps(values, default=str, ensure_ascii=False) if held else None, + } # fmt: skip + if not held: + staged |= model.model_validate(values).model_dump() + out.append(staged) + return nodes.stage(node.entity, p, node.id, out, silver.columns(node.entity)) + + +RUNNERS: dict[str, Callable] = { + "source": nodes.run_source, "read": run_read, "route": run_route, "map": run_map, + "join": run_join, "extract": run_extract, "link": run_link, +} # fmt: skip def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print) -> None: + kinds = {n.id: n.kind for n in pipeline.nodes} for node in pipeline.order(): - if node.kind not in RUNNERS: - raise NotImplementedError(f"{node.id}: {node.kind} nodes run from step 4") - RUNNERS[node.kind](pipeline_id, node) + if node.kind == "target": + run_target(pipeline_id, node, kinds) + else: + RUNNERS[node.kind](pipeline_id, node) log(f"{node.id} ({node.kind}) done") + if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}): + silver.build(entities) + log(f"silver: {', '.join(entities)}") diff --git a/pyproject.toml b/pyproject.toml index 6ef36e5..11f37bb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,8 +8,12 @@ dependencies = [ "persistance", "dagster", "dagster-webserver", - "dagster-dbt", "mlflow-skinny", + "openai>=3.59.0", + "splink>=5.0.0", + "markitdown[docx,xlsx]>=0.1.9", + "ocrmypdf>=17.14.2", + "pdfplumber>=0.11.11", ] [build-system] diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..7d27f8e --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,63 @@ +"""A fresh platform per test, on SQLite and on PostgreSQL, and the way an operator runs it: +save a pipeline, run the `ingest` job (each run in its own process, as Dagster does).""" + +import json +import os +import subprocess +from pathlib import Path +from types import SimpleNamespace + +import pytest +from sqlalchemy import create_engine, make_url, text + + +def run(env, *args): + subprocess.run(args, env=env, check=True) + + +def ingest(env, pipeline="site"): + config = Path(env["ISSSTELEON_DATA"]) / "run.json" + config.write_text(json.dumps({"ops": {"run_pipeline": {"config": {"pipeline": pipeline}}}})) + run(env, "dagster", "job", "execute", "-m", "models.definitions", "-j", "ingest", + "--config", str(config)) # fmt: skip + + +@pytest.fixture(params=["sqlite", "postgres"]) +def platform(request, tmp_path): + """Env for a fresh platform on each backend, and a SQL connection to read it back.""" + (tmp_path / "dagster").mkdir() + env = { + **os.environ, + "ISSSTELEON_DATA": str(tmp_path), + "DLT_DATA_DIR": str(tmp_path / "dlt"), + "DAGSTER_HOME": str(tmp_path / "dagster"), + } + if request.param == "sqlite": + url = env["PLATFORM_DATABASE_URL"] = f"sqlite:///{tmp_path / 'platform.db'}" + attach = [f"ATTACH '{tmp_path}/platform__{s}.db' AS {s}" for s in ("bronze", "silver")] + else: + pg = os.environ["POSTGRES_TEST_URL"] # required: run with `docker compose run --rm test` + env.update(PLATFORM_DATABASE_URL=pg, DBT_TARGET="postgres") + url = make_url(pg).set(drivername="postgresql+psycopg2") + attach = [] + with create_engine(url).begin() as con: + for schema in ("bronze", "silver", "config"): + con.exec_driver_sql(f"drop schema if exists {schema} cascade") + + def count(table: str) -> int: + with create_engine(url).connect() as con: + for statement in attach: + con.exec_driver_sql(statement) + return con.execute(text(f"select count(*) from {table}")).scalar() + + def query(sql: str): + with create_engine(url).connect() as con: + for statement in attach: + con.exec_driver_sql(statement) + return con.execute(text(sql)).fetchall() + + return SimpleNamespace( + env=env, count=count, query=query, + run=lambda *args: run(env, *args), + ingest=lambda pipeline="site": ingest(env, pipeline), + ) # fmt: skip diff --git a/tests/test_ingest.py b/tests/test_ingest.py index ad3dc01..7f6f0c6 100644 --- a/tests/test_ingest.py +++ b/tests/test_ingest.py @@ -2,16 +2,11 @@ the rules point at is read into text (scanned ones through OCR).""" import json -import os import re import shutil import sqlite3 -import subprocess from pathlib import Path -import pytest -from sqlalchemy import create_engine, make_url, text - from synthetic.site import build FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures" / "hospital" @@ -53,56 +48,8 @@ FILES = "dlt.sources.filesystem:filesystem" READERS = "dlt.sources.filesystem:readers" -@pytest.fixture(params=["sqlite", "postgres"]) -def platform(request, tmp_path): - """Env for a fresh platform on each backend, and a SQL connection to read it back.""" - (tmp_path / "dagster").mkdir() - env = { - **os.environ, - "ISSSTELEON_DATA": str(tmp_path), - "DLT_DATA_DIR": str(tmp_path / "dlt"), - "DAGSTER_HOME": str(tmp_path / "dagster"), - } - if request.param == "sqlite": - url = env["PLATFORM_DATABASE_URL"] = f"sqlite:///{tmp_path / 'platform.db'}" - attach = [f"ATTACH '{tmp_path}/platform__bronze.db' AS bronze"] - else: - pg = os.environ["POSTGRES_TEST_URL"] # required: run with `docker compose run --rm test` - env.update(PLATFORM_DATABASE_URL=pg, DBT_TARGET="postgres") - url = make_url(pg).set(drivername="postgresql+psycopg2") - attach = [] - with create_engine(url).begin() as con: - for schema in ("bronze", "config"): - con.exec_driver_sql(f"drop schema if exists {schema} cascade") - - def count(table: str) -> int: - with create_engine(url).connect() as con: - for statement in attach: - con.exec_driver_sql(statement) - return con.execute(text(f"select count(*) from bronze.{table}")).scalar() - - def query(sql: str): - with create_engine(url).connect() as con: - for statement in attach: - con.exec_driver_sql(statement) - return con.execute(text(sql)).fetchall() - - return env, count, query - - -def run(env, *args): - subprocess.run(args, env=env, check=True) - - -def ingest(env): - config = Path(env["ISSSTELEON_DATA"]) / "run.json" - config.write_text(json.dumps({"ops": {"run_pipeline": {"config": {"pipeline": "site"}}}})) - run(env, "dagster", "job", "execute", "-m", "models.definitions", "-j", "ingest", - "--config", str(config)) # fmt: skip - - def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_path): - env, count, query = platform + count, query = platform.count, platform.query tables = {} for name in ("cacu", "cama"): shutil.copy(FIXTURES / f"hospital_{name}.db", tmp_path / f"hospital_{name}.db") @@ -111,7 +58,7 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat tables[name] = [t for (t,) in found] truth = build(FIXTURES / "hospital_cacu.db", tmp_path / "site")["records"] (tmp_path / "pipeline.json").write_text(json.dumps(graph(tmp_path, tables))) - run(env, "python", "-m", "persistance.config_log", "site", str(tmp_path / "pipeline.json")) + platform.run("python", "-m", "persistance.config_log", "site", str(tmp_path / "pipeline.json")) by_place = {} for r in truth: @@ -131,17 +78,17 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat expected[f"{name}_{t}"] = con.execute(f"select count(*) from {t}").fetchone()[0] def counts(): - return {node: count(f"n__site__{node}") for node in expected} + return {node: count(f"bronze.n__site__{node}") for node in expected} for _ in range(2): # loading the same site again changes nothing - ingest(env) + platform.ingest() assert counts() == expected - read_once = query("select sha256, _dlt_load_id from bronze.read_cache order by sha256") + read_once = query("select key, _dlt_load_id from bronze.read_cache order by key") assert len(read_once) == expected["archivos"] + expected["pdfs"] # each file read once with sqlite3.connect(tmp_path / "hospital_cacu.db") as con: # a corrected record updates con.execute("update paciente set pac_codigo_postal = '64000' where pac_id = 1") - ingest(env) + platform.ingest() assert counts() == expected corrected = "select pac_codigo_postal from bronze.n__site__cacu_paciente where pac_id = 1" assert query(corrected) == [("64000",)] @@ -155,6 +102,6 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat assert bool(ocr) == r["scanned"] # OCR runs on scans, and only on scans if "record_number" in r["identity"]: # even scanned, the identifier reads back exactly assert r["identity"]["record_number"] in txt, (r["where"], txt) - assert query("select sha256, _dlt_load_id from bronze.read_cache order by sha256") == ( + assert query("select key, _dlt_load_id from bronze.read_cache order by key") == ( read_once ) # reruns never read a file again diff --git a/tests/test_silver.py b/tests/test_silver.py new file mode 100644 index 0000000..4fb9d56 --- /dev/null +++ b/tests/test_silver.py @@ -0,0 +1,107 @@ +"""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") + )