From 31a706beb5d3ae1228fd6bac68a3bc4dc5d47455 Mon Sep 17 00:00:00 2001 From: kert Date: Sat, 31 Oct 2026 22:04:29 -0400 Subject: [PATCH] feat(lead): load the public manifest and record measure gaps --- src/cli/lead.py | 18 +++++ src/lead/manifest.py | 157 ++++++++++++++++++++++++++++++++++++ src/lead/quality.py | 28 +++++++ src/lead/spine.py | 46 +++++++++++ tests/lead/test_manifest.py | 101 +++++++++++++++++++++++ tests/lead/test_quality.py | 27 +++++++ tests/lead/test_spine.py | 34 ++++++++ 7 files changed, 411 insertions(+) create mode 100644 src/lead/manifest.py create mode 100644 src/lead/quality.py create mode 100644 src/lead/spine.py create mode 100644 tests/lead/test_manifest.py create mode 100644 tests/lead/test_quality.py create mode 100644 tests/lead/test_spine.py diff --git a/src/cli/lead.py b/src/cli/lead.py index e812f82..af26045 100644 --- a/src/cli/lead.py +++ b/src/cli/lead.py @@ -6,11 +6,14 @@ import typer from lead.ledger.store import open_ledger from lead.ledger.store import status as ledger_status +from lead.manifest import load_manifest from lead.targets import TARGETS app = typer.Typer(no_args_is_help=True) ledger_app = typer.Typer(no_args_is_help=True) +manifest_app = typer.Typer(no_args_is_help=True) app.add_typer(ledger_app, name="ledger", help="Evidence ledger.") +app.add_typer(manifest_app, name="manifest", help="Public-release manifest.") @app.command(name="targets") @@ -67,3 +70,18 @@ def ledger_export_cmd( con.close() for name in ("source", "decision", "extraction"): typer.echo(f"{name}\t{counts[name]}") + + +@manifest_app.command("load") +def manifest_load( + csv: str = typer.Option(..., "--csv", help="Path to the manifest CSV."), + db: str = typer.Option(..., "--db", help="Path to the DuckDB ledger."), + actor: str = typer.Option("stack", "--actor", help="Who loaded the rows."), +) -> None: + """Record manifest rows. This does not download the files.""" + con = open_ledger(db) + try: + inserted = load_manifest(con, csv, actor=actor) + finally: + con.close() + typer.echo(f"inserted\t{inserted}") diff --git a/src/lead/manifest.py b/src/lead/manifest.py new file mode 100644 index 0000000..d4bd03d --- /dev/null +++ b/src/lead/manifest.py @@ -0,0 +1,157 @@ +"""Load a public-release manifest into the local DuckDB ledger. + +The caller supplies the CSV path. This module does not download the files +and does not open their URLs. A missing path is still recorded. The same +``source_id``, ``release``, and ``sha256`` insert nothing. + +The table DDL lives here, not in ``lead.ledger.schema``, so the Delta +schema string stays free of a catalog token. +""" + +from __future__ import annotations + +import csv +import hashlib +from pathlib import Path + +SYNTHETIC_SOURCE_IDS = frozenset( + {"bcda_sandbox", "tuva", "cms_synthetic", "de_synpuf", "synthea"} +) + +REQUIRED = ( + "source_id", + "title", + "publisher", + "kind", + "url", + "api_endpoint", + "landing_page", + "release", + "fetched_utc", + "status", + "path", + "sha256", + "rows", + "size_bytes", + "license_terms", + "lead_use", +) + +RELEASE_DDL = """ +CREATE SCHEMA IF NOT EXISTS lead_evidence; +CREATE TABLE IF NOT EXISTS lead_evidence.public_release ( + source_id VARCHAR, + title VARCHAR, + publisher VARCHAR, + kind VARCHAR, + url VARCHAR, + api_endpoint VARCHAR, + landing_page VARCHAR, + release VARCHAR, + fetched_utc VARCHAR, + status VARCHAR, + path VARCHAR, + sha256 VARCHAR, + row_count VARCHAR, + size_bytes VARCHAR, + license_terms VARCHAR, + lead_use VARCHAR, + layer VARCHAR, + actor VARCHAR, + content_hash VARCHAR +) +""" + + +def layer_of(source_id: str, lead_use: str) -> str: + """``synthetic`` for a synthetic source or a lead_use that says so.""" + if ( + "synthetic" in lead_use.casefold() + or source_id.casefold() in SYNTHETIC_SOURCE_IDS + ): + return "synthetic" + return "" + + +def _ensure(con) -> None: + for statement in RELEASE_DDL.split(";"): + text = statement.strip() + if text: + con.execute(text) + + +def _identity(row: dict[str, str]) -> tuple[str, str, str]: + source_id = (row.get("source_id") or "").strip() + release = (row.get("release") or "").strip() + digest = (row.get("sha256") or "").strip() + if not source_id: + raise ValueError("source_id is required") + if not release: + raise ValueError("release is required") + if not digest: + raise ValueError("sha256 is required") + return source_id, release, digest + + +def load_manifest(con, csv_path: str, *, actor: str) -> int: + """Insert new release rows. Return how many were new. + + Raises: + ValueError: a required column or a required key is missing. + """ + _ensure(con) + with Path(csv_path).open(newline="") as handle: + reader = csv.DictReader(handle) + missing = [name for name in REQUIRED if name not in (reader.fieldnames or [])] + if missing: + raise ValueError(f"missing columns: {missing}") + raw = list(reader) + identities = [_identity(row) for row in raw] + inserted = 0 + for row, (source_id, release, digest) in zip(raw, identities, strict=True): + content = hashlib.sha256( + f"{source_id}\n{release}\n{digest}\n".encode() + ).hexdigest() + existing = con.execute( + """ + SELECT 1 FROM lead_evidence.public_release + WHERE source_id = ? AND release = ? AND sha256 = ? + """, + [source_id, release, digest], + ).fetchone() + if existing: + continue + layer = layer_of(source_id, row.get("lead_use") or "") + con.execute( + """ + INSERT INTO lead_evidence.public_release ( + source_id, title, publisher, kind, url, api_endpoint, + landing_page, release, fetched_utc, status, path, sha256, + row_count, size_bytes, license_terms, lead_use, layer, + actor, content_hash + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + [ + source_id, + row.get("title") or "", + row.get("publisher") or "", + row.get("kind") or "", + row.get("url") or "", + row.get("api_endpoint") or "", + row.get("landing_page") or "", + release, + row.get("fetched_utc") or "", + row.get("status") or "", + row.get("path") or "", + digest, + row.get("rows") or "", + row.get("size_bytes") or "", + row.get("license_terms") or "", + row.get("lead_use") or "", + layer, + actor, + content, + ], + ) + inserted += 1 + return inserted diff --git a/src/lead/quality.py b/src/lead/quality.py new file mode 100644 index 0000000..47c3e44 --- /dev/null +++ b/src/lead/quality.py @@ -0,0 +1,28 @@ +"""Which quality targets this repo can already compute. + +UAMCC and ACR stay in ``aco.express.cms_quality_measures``. The other +measures are gaps: their formulas are not in this repo, and this module +does not invent them. +""" + +from __future__ import annotations + + +def reconciled() -> tuple[str, ...]: + """Targets whose formulas already live in the ACO quality measures.""" + return ("Q.UAMCC", "Q.ACR") + + +def known_gaps() -> tuple[tuple[str, str], ...]: + """Target id and why this package does not compute it.""" + return ( + ("Q.DAH", "CMS DAH formula is not in this repo"), + ("Q.TFU", "CMS TFU formula is not in this repo"), + ("Q.CAHPS", "CAHPS results are an input, not a formula"), + ("HN.1", "Appendix B diagnosis list is not in this repo"), + ("HN.2", "Appendix B DME list is not in this repo"), + ("HN.3", "Kim index weights and cutoff are not in this repo"), + ("RA.PROSP", "V28 prospective software is not parsed here"), + ("RA.CONC", "Concurrent model coefficients are not in this repo"), + ("RA.ESRD", "ESRD model internals are not in this repo"), + ) diff --git a/src/lead/spine.py b/src/lead/spine.py new file mode 100644 index 0000000..7246e3d --- /dev/null +++ b/src/lead/spine.py @@ -0,0 +1,46 @@ +"""Geography and time keys for the public-data spine. + +A county FIPS and a ZCTA are each a key. This module does not carry a +national crosswalk, so the two cannot be joined here. +""" + +from __future__ import annotations + +import re + +_FIVE = re.compile(r"\d{5}") + + +def _five(value: str) -> str: + if _FIVE.fullmatch(value) is None: + raise ValueError(value) + return value + + +def geography_key(*, fips: str = "", zcta: str = "") -> str: + """One validated 5-digit FIPS or ZCTA. + + Raises: + ValueError: both are set, neither is set, or the value is not + five digits. + """ + if fips and zcta: + raise ValueError("no national crosswalk") + if fips: + return _five(fips) + if zcta: + return _five(zcta) + raise ValueError("geography is required") + + +def time_key(year: int, quarter: int) -> str: + """``YYYYQ`` for a year in 1900..2100 and a quarter in 1..4. + + Raises: + ValueError: the year or the quarter is outside that range. + """ + if year < 1900 or year > 2100: + raise ValueError(year) + if quarter not in {1, 2, 3, 4}: + raise ValueError(quarter) + return f"{year}Q{quarter}" diff --git a/tests/lead/test_manifest.py b/tests/lead/test_manifest.py new file mode 100644 index 0000000..900482d --- /dev/null +++ b/tests/lead/test_manifest.py @@ -0,0 +1,101 @@ +"""The enrichment manifest loads into local DuckDB. It does not download.""" + +from __future__ import annotations + +import pytest +from typer.testing import CliRunner + +from cli import app +from lead.ledger.schema import schema_sql +from lead.ledger.store import open_ledger +from lead.manifest import RELEASE_DDL, load_manifest + +runner = CliRunner() + +_HEADER = ( + "source_id,title,publisher,kind,url,api_endpoint,landing_page,release," + "fetched_utc,status,path,sha256,rows,size_bytes,license_terms,lead_use" +) + + +def _csv(tmp_path, body: str): + path = tmp_path / "manifest.csv" + path.write_text(_HEADER + "\n" + body) + return path + + +def test_load_is_idempotent_and_tags_synthetic_rows(tmp_path): + csv_path = _csv( + tmp_path, + "ahrq,Title,Pub,table,https://example.test/a,,,2024,2026-10-31,ok," + "/no/such/lead-file,abc,1,2,public,benchmark\n" + "tuva,Title,Pub,table,https://example.test/b,,,2024,2026-10-31,ok," + "/no/such/lead-file,def,1,2,public,\n" + "cms,Title,Pub,table,https://example.test/c,,,2024,2026-10-31,ok," + "/no/such/lead-file,ghi,1,2,public,synthetic person file\n", + ) + con = open_ledger(str(tmp_path / "ledger.duckdb")) + try: + assert load_manifest(con, str(csv_path), actor="tester") == 3 + assert load_manifest(con, str(csv_path), actor="tester") == 0 + rows = con.execute( + """ + SELECT source_id, url, path, layer + FROM lead_evidence.public_release + ORDER BY source_id + """ + ).fetchall() + finally: + con.close() + by_source = {row[0]: row for row in rows} + assert by_source["ahrq"][1] == "https://example.test/a" + assert by_source["ahrq"][2] == "/no/such/lead-file" + assert by_source["ahrq"][3] == "" + assert by_source["tuva"][3] == "synthetic" + assert by_source["cms"][3] == "synthetic" + + +def test_a_blank_sha256_raises_and_inserts_nothing(tmp_path): + csv_path = _csv( + tmp_path, + "ahrq,Title,Pub,table,https://example.test/a,,,2024,2026-10-31,ok," + "/no/such/lead-file,,1,2,public,benchmark\n", + ) + con = open_ledger(str(tmp_path / "ledger.duckdb")) + try: + with pytest.raises(ValueError): + load_manifest(con, str(csv_path), actor="tester") + count = con.execute( + "SELECT count(*) FROM lead_evidence.public_release" + ).fetchone()[0] + assert count == 0 + finally: + con.close() + + +def test_release_ddl_and_delta_schema_omit_the_catalog_token(): + assert "aco" not in RELEASE_DDL + assert "aco" not in schema_sql("delta") + + +def test_manifest_load_command_prints_the_insert_count(tmp_path): + csv_path = _csv( + tmp_path, + "ahrq,Title,Pub,table,https://example.test/a,,,2024,2026-10-31,ok," + "/no/such/lead-file,abc,1,2,public,benchmark\n", + ) + db = tmp_path / "ledger.duckdb" + result = runner.invoke( + app, + [ + "lead", + "manifest", + "load", + "--csv", + str(csv_path), + "--db", + str(db), + ], + ) + assert result.exit_code == 0 + assert "inserted\t1" in result.stdout diff --git a/tests/lead/test_quality.py b/tests/lead/test_quality.py new file mode 100644 index 0000000..055ffe7 --- /dev/null +++ b/tests/lead/test_quality.py @@ -0,0 +1,27 @@ +"""UAMCC and ACR stay where they are. The missing measures are gaps.""" + +from __future__ import annotations + +from aco.express.cms_quality_measures import acr_summary, uamcc_summary +from lead.quality import known_gaps, reconciled + + +def test_uamcc_and_acr_are_reconciled_to_the_existing_measures(): + assert reconciled() == ("Q.UAMCC", "Q.ACR") + assert callable(uamcc_summary) + assert callable(acr_summary) + + +def test_unpublished_formulas_are_named_gaps(): + targets = {target for target, _reason in known_gaps()} + assert { + "Q.DAH", + "Q.TFU", + "Q.CAHPS", + "HN.1", + "HN.2", + "HN.3", + "RA.PROSP", + "RA.CONC", + "RA.ESRD", + } <= targets diff --git a/tests/lead/test_spine.py b/tests/lead/test_spine.py new file mode 100644 index 0000000..96a432a --- /dev/null +++ b/tests/lead/test_spine.py @@ -0,0 +1,34 @@ +"""Geography and time keys. No national crosswalk.""" + +from __future__ import annotations + +import pytest + +from lead.spine import geography_key, time_key + + +def test_a_five_digit_fips_is_the_geography_key(): + assert geography_key(fips="01001") == "01001" + + +def test_a_short_fips_raises(): + with pytest.raises(ValueError): + geography_key(fips="1001") + + +def test_a_five_digit_zcta_is_the_geography_key(): + assert geography_key(zcta="02138") == "02138" + + +def test_fips_and_zcta_together_raise(): + with pytest.raises(ValueError): + geography_key(fips="01001", zcta="02138") + + +def test_time_key_is_year_and_quarter(): + assert time_key(2027, 4) == "2027Q4" + + +def test_a_quarter_outside_1_to_4_raises(): + with pytest.raises(ValueError): + time_key(2027, 5)