From 71e77f0c7ed06e9120169843dea19dd14a7d0890 Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 6 Nov 2026 00:40:50 -0600 Subject: [PATCH] models cohorts list and show: a cohort's builds from both sources, and one build's file, hash and lineage --- README.md | 1 + models/__main__.py | 60 +++++++++++++++++++++ models/io/storage.py | 39 ++++++++++++++ tests/io/test_build_listing.py | 95 ++++++++++++++++++++++++++++++++++ 4 files changed, 195 insertions(+) create mode 100644 tests/io/test_build_listing.py diff --git a/README.md b/README.md index feb22a0..5c469b4 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ WebApi. | `steps/cohort.py`, `steps/cohort_file.py` | The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage. | | `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. | | `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/.parquet` and writes only when its rows change. The timeline comes from dbt's view `_linea_de_tiempo`. | +| `cohorts list`, `cohorts show` | `python -m models cohorts list cacu cohorte_vigilancia [--source kit\|dbt]` lists the builds of both sources, newest first, and whether each has its file (dbt's from their files alone); `cohorts show … --source kit\|dbt --build N` prints one build's file, hash, parameters, rules and attrition as JSON (`io/storage.py`: `list_builds`, `describe_build`). | | `steps/risks.py`, `pipelines/store_risks.py` | Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), through `cohorte_repository`: one preliminary risk per member at the model's horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (`armado_id`), so estimates of dbt builds are refused. `python -m models store cacu cin2_logistic --input file.parquet`, or `run … --estimate --store --output file.parquet`. | | `steps/report.py`, `io/rendering.py`, `pipelines/report_eda.py` | A model's exploratory notebook as an MLflow report: `python -m models report eda cacu cin2_logistic [--source kit\|dbt] [--build N] [--notebook path] [--kernel name]` runs `notebooks//01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it with Quarto to one HTML page, and logs the page and the notebook without outputs as a run of the experiment `-/`, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. Needs Quarto (`QUARTO_BIN`) and a Python with Jupyter (`QUARTO_PYTHON`). | | `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. | diff --git a/models/__main__.py b/models/__main__.py index 7ac6715..189de5f 100644 --- a/models/__main__.py +++ b/models/__main__.py @@ -259,6 +259,53 @@ def _cohort_export(args: argparse.Namespace) -> int: return 0 +def _cohort_list(args: argparse.Namespace) -> int: + """Prints the cohort's builds: dbt's from their files, the kit's from the database.""" + from importlib import import_module + + from persistance.settings import settings + + from models.io.storage import cohorts_root, list_builds + + url = f"{args.domain}/{args.cohort}" + try: + root = cohorts_root(getattr(settings, f"{args.domain}_database_url")) + except ValueError as error: + print(error, file=sys.stderr) + return 1 + cohorts = None if args.source == "dbt" else import_module(f"persistance.{args.domain}").cohorte_repository + rows = [row for row in list_builds(root, url, cohorts) if args.source in (None, row["source"])] + if not rows: + print(f"{url}: no builds", file=sys.stderr) + return 1 + print(f"{'source':<6} {'build':>5} {'datos_as_of':<11} {'members':>7} {'created':<25} file") + for row in rows: + print(f"{row['source']:<6} {row['build']:>5} {row['datos_as_of'] or '':<11} {row['n_members'] or '':>7} " + f"{(row['created'] or '')[:25]:<25} {row['file'] or '(not exported)'}") + return 0 + + +def _cohort_show(args: argparse.Namespace) -> int: + """Prints one build's file, hash and lineage as JSON.""" + import json + from importlib import import_module + + from persistance.settings import settings + + from models.io.storage import cohorts_root, describe_build + + url = f"{args.domain}/{args.cohort}" + try: + root = cohorts_root(getattr(settings, f"{args.domain}_database_url")) + cohorts = import_module(f"persistance.{args.domain}").cohorte_repository if args.source == "kit" else None + described = describe_build(root, url, args.source, args.build, cohorts) + except (ValueError, LookupError) as error: + print(error, file=sys.stderr) + return 1 + print(json.dumps(described, indent=2, ensure_ascii=False)) + return 0 + + def _cohort_export_checked(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: if args.source == "dbt" and not args.manifest: parser.error("--source dbt needs --manifest") @@ -290,6 +337,19 @@ def build_parser() -> argparse.ArgumentParser: export.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --source dbt") export.set_defaults(run=lambda args: _cohort_export_checked(export, args)) + listing = actions.add_parser("list", help="the cohort's builds, from both sources, and whether each has its file") + listing.add_argument("domain", choices=["cacu", "cama", "tea"]) + listing.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia") + listing.add_argument("--source", choices=["kit", "dbt"], help="only one source's builds; dbt's read no database") + listing.set_defaults(run=_cohort_list) + + show = actions.add_parser("show", help="one build's file, hash, parameters, rules and attrition") + show.add_argument("domain", choices=["cacu", "cama", "tea"]) + show.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia") + show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose build: the kit's or dbt's rules'") + show.add_argument("--build", type=int, required=True, help="the build's number") + show.set_defaults(run=_cohort_show) + train = commands.add_parser("train", help="train a model on a cohort build's file and register a version") train.add_argument("domain", choices=["cacu", "cama", "tea"]) train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") diff --git a/models/io/storage.py b/models/io/storage.py index d1414b0..99246ed 100644 --- a/models/io/storage.py +++ b/models/io/storage.py @@ -6,6 +6,7 @@ beside them, numbered in order, so a lookup of the kit's builds never picks one repository is used, so a model folder reading its cohort file never loads the database layer. """ +import hashlib import importlib import json import os @@ -64,6 +65,44 @@ def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path return path +def list_builds(root: Path, url: str, cohorts=None) -> list[dict]: + """One row per build of the cohort, newest first within each source: dbt's builds from their files' metadata, and, + with `cohorts` (the domain's `cohorte_repository`), the kit's builds and whether each has its file. Without + `cohorts` only files are read, never the database.""" + rows = [] + for number in reversed(_numbers(dbt_build_path(root, url, 0).parent)): + path = dbt_build_path(root, url, number) + lineage = read_metadata(path) + rows.append({"source": "dbt", "build": number, "datos_as_of": lineage.get("datos_as_of"), + "n_members": lineage.get("n_members"), "created": lineage.get("built_at"), "file": str(path)}) + for build in (cohorts.builds(url) if cohorts is not None else []): + path = cohort_path(root, url, build.armado_id) + rows.append({"source": "kit", "build": build.armado_id, "datos_as_of": build.datos_as_of.isoformat(), + "n_members": str(build.n_miembros), "created": build.armado_en.isoformat(), + "file": str(path) if path.exists() else None}) + return rows + + +def describe_build(root: Path, url: str, source: str, build: int, cohorts=None) -> dict: + """One build: its file and hash, and its lineage with the parameters, rules and attrition decoded. A kit build + without a file is described from `cohorts` (the domain's `cohorte_repository`). `LookupError` if there's no such + build.""" + path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build) + if path.exists(): + lineage = read_metadata(path) + for key in ("parametros", "rules", "attrition"): + if lineage.get(key): + lineage[key] = json.loads(lineage[key]) + digest = hashlib.sha256(path.read_bytes()).hexdigest() + return {"source": source, "build": build, "file": str(path), "file_sha256": digest, "lineage": lineage} + stored = cohorts.build(build) if source == "kit" and cohorts is not None else None + if stored is None or stored.url != url: + raise LookupError(f"no {source} build {build} of {url}") + return {"source": "kit", "build": build, "file": None, "file_sha256": None, + "lineage": {"url": stored.url, "version": stored.version, "datos_as_of": stored.datos_as_of.isoformat(), + "n_members": str(stored.n_miembros), "huella": stored.huella, "armado_en": stored.armado_en.isoformat()}} + + def read_cohort(path: str | Path) -> pd.DataFrame: """The build's rows, after checking the file's schema without reading them.""" schema = pq.read_schema(path) diff --git a/tests/io/test_build_listing.py b/tests/io/test_build_listing.py new file mode 100644 index 0000000..3daca17 --- /dev/null +++ b/tests/io/test_build_listing.py @@ -0,0 +1,95 @@ +"""What this module covers: listing and describing a cohort's builds (`models.io.storage.list_builds`, +`describe_build`) and the `models cohorts list` and `cohorts show` commands. + +Fixtures: `root`, a cohorts folder with dbt builds 1 and 2 and kit build 7's file; `kit`, a stand-in of the cohort +repository with kit builds 7 (exported) and 8 (not exported). +""" + +import json +from datetime import date, datetime, timezone +from types import SimpleNamespace + +import pyarrow as pa +import pyarrow.parquet as pq +import pytest + +from models.__main__ import main +from models.io.storage import cohort_path, dbt_build_path, describe_build, list_builds + +URL = "cacu/cohorte_vigilancia" +ATTRITION = [{"step": "all_patients", "n": 3, "excluded": None}, {"step": "indexed", "n": 2, "excluded": 1}] + + +def _file(path, **metadata): + path.parent.mkdir(parents=True, exist_ok=True) + pq.write_table(pa.table({"pac_id": [1]}).replace_schema_metadata({k: str(v) for k, v in metadata.items()}), path) + + +@pytest.fixture +def root(tmp_path): + for number in (1, 2): + _file(dbt_build_path(tmp_path, URL, number), producer="dbt", build=number, datos_as_of="2026-12-31", + n_members=2, built_at=f"2026-11-0{number}T00:00:00+00:00", rules=json.dumps(["prior_event"]), + parametros=json.dumps({"cutoff": "2026-12-31"}), attrition=json.dumps(ATTRITION)) + _file(cohort_path(tmp_path, URL, 7), producer="kit", armado_id=7, datos_as_of="2026-12-31", n_members=2) + return tmp_path + + +def _kit_build(armado_id): + return SimpleNamespace(armado_id=armado_id, url=URL, version="0.2.0", datos_as_of=date(2026, 12, 31), n_miembros=2, + huella="h", armado_en=datetime(2026, 10, armado_id, tzinfo=timezone.utc)) + + +@pytest.fixture +def kit(): + builds = {8: _kit_build(8), 7: _kit_build(7)} + return SimpleNamespace(builds=lambda url: list(builds.values()) if url == URL else [], build=builds.get) + + +def test_both_sources_are_listed_newest_first_with_their_files(root, kit): + """Pins down: dbt's builds come from their files, newest first, and the kit's from the repository, each saying + whether its file exists. Fails if a source is dropped, the order is by name, or an unexported build shows a file.""" + rows = list_builds(root, URL, kit) + + assert [(r["source"], r["build"]) for r in rows] == [("dbt", 2), ("dbt", 1), ("kit", 8), ("kit", 7)] + assert rows[2]["file"] is None and rows[3]["file"].endswith("7.parquet") + assert rows[0]["created"] == "2026-11-02T00:00:00+00:00" + + +def test_without_the_repository_only_files_are_read(root): + """Pins down: listing dbt's builds needs no database. Fails if `list_builds` reaches for the kit's builds anyway.""" + assert [r["source"] for r in list_builds(root, URL)] == ["dbt", "dbt"] + + +def test_a_dbt_build_is_described_with_its_lineage_decoded(root): + """Pins down: `describe_build` gives the file, its hash, and the parameters, rules and attrition as JSON values, + not strings. Fails if the hash is missing or the lineage stays encoded.""" + described = describe_build(root, URL, "dbt", 2) + + assert len(described["file_sha256"]) == 64 + assert described["lineage"]["attrition"] == ATTRITION and described["lineage"]["rules"] == ["prior_event"] + assert described["lineage"]["parametros"] == {"cutoff": "2026-12-31"} + + +def test_an_unexported_kit_build_is_described_from_the_database(root, kit): + """Pins down: a kit build without a file still has its lineage, from the repository; an unknown build is a + `LookupError`. Fails if an unexported build is reported as missing, or a missing one as empty.""" + described = describe_build(root, URL, "kit", 8, kit) + + assert described["file"] is None and described["lineage"]["n_members"] == "2" + with pytest.raises(LookupError): + describe_build(root, URL, "kit", 9, kit) + with pytest.raises(LookupError): + describe_build(root, URL, "dbt", 9) + + +def test_the_commands_print_the_dbt_builds(root, monkeypatch, capsys): + """Pins down: `cohorts list --source dbt` and `cohorts show` work from the files alone. Fails if either opens the + database for dbt's builds, or `show` prints something other than JSON.""" + monkeypatch.setenv("COHORTS_DIR", str(root)) + + assert main(["cohorts", "list", "cacu", "cohorte_vigilancia", "--source", "dbt"]) == 0 + listed = capsys.readouterr().out + assert "dbt/2.parquet" in listed and "dbt/1.parquet" in listed + assert main(["cohorts", "show", "cacu", "cohorte_vigilancia", "--build", "1"]) == 0 + assert json.loads(capsys.readouterr().out)["build"] == 1