Files
models/models/__main__.py
T
edgar ea6db36b23 dbt is the only definition of a cohort: the stored build runs dbt's queries
The WebApi cycle's build (models.cohorts.build.build_of) runs the cohort's queries from dbt's manifest with the same
chain as the export, instead of a Python frame per cohort; the TOML definitions, their frames and definition.py are
removed. A cohort may have no exclusions (cacu/cohorte_total, for models whose rules don't fit SQL) and an optional
`variables` query; the population meta carries the cohort's version. cohort_urls lists a domain's cohorts in the
manifest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 19:52:05 -06:00

473 lines
24 KiB
Python

"""The package's command line: `python -m models <command>`.
Each area adds its subcommands to `build_parser`. Heavy imports (MLflow, the kit) belong inside the
command that needs them, so `--help` stays immediate.
"""
import argparse
import sys
from collections.abc import Sequence
def _show_help(parser: argparse.ArgumentParser) -> int:
"""A command without actions yet shows its help and fails, rather than appearing to have run."""
parser.print_help()
return 2
def _scenario(args: argparse.Namespace):
"""The scenario's `model.toml`; `None` and a message on stderr if there's no such model."""
from models.dags.training import Scenario
try:
return Scenario.load(args.domain, args.scenario)
except LookupError as error:
print(error, file=sys.stderr)
return None
def _cohort_file(args: argparse.Namespace, scenario):
"""The build's exported file; `None` and a message on stderr if it's missing."""
from persistance.settings import settings
from models.io.storage import cohorts_root, dbt_build_path, find_cohort_file, latest_dbt_build
url = scenario.cohort
command = f"python -m models cohorts export {url.replace('/', ' ')}" + (" --source dbt" if args.source == "dbt" else "")
try:
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
if args.source == "kit":
return find_cohort_file(root, url, args.armado)
if args.armado is not None:
if not (path := dbt_build_path(root, url, args.armado)).exists():
raise FileNotFoundError(f"dbt build {args.armado} of {url} isn't exported: no {path}")
return path
if not (latest := latest_dbt_build(root, url)):
raise FileNotFoundError(f"no exported dbt builds of {url} under {root}")
return latest[1]
except (FileNotFoundError, ValueError) as error:
print(f"{error}: export it with `{command}`", file=sys.stderr)
return None
def _cohort_source(args: argparse.Namespace, scenario):
"""Where the build's rows come from: a kit build from the database (`--read db`, the default), or an exported
file (`--read file`, and always for dbt's builds, which only exist as files). `None` and a message if missing."""
from models.io.storage import CohortFile, KitBuild
if args.source == "kit" and getattr(args, "read", "file") == "db":
from importlib import import_module
cohorts = import_module(f"persistance.{args.domain}").cohort_repository
build_id = args.armado if args.armado is not None else cohorts.latest_build(scenario.cohort)
if build_id is None:
print(f"no kit builds of {scenario.cohort}", file=sys.stderr)
return None
return KitBuild(args.domain, build_id, cohorts=cohorts)
path = _cohort_file(args, scenario)
return CohortFile(path) if path else None
def _describe(source) -> str:
return str(getattr(source, "path", None) or f"kit build {source.build_id}")
def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
"""Trains the model on the build, always as a new version."""
if args.environment == "prod" and args.armado is None:
parser.error("a prod run names its cohort build: --build (ML-03)")
if not (scenario := _scenario(args)) or not (source := _cohort_source(args, scenario)):
return 1
from models.dags.training import train
print(f"{args.domain}/{args.scenario} version {train(scenario, source, args.environment.upper())}, "
f"from {_describe(source)}")
return 0
def _estimate_step(args: argparse.Namespace, scenario, source) -> int:
from models.dags.estimation import estimate
try:
resolved, written = estimate(scenario, source, args.output, args.version)
except LookupError as error:
print(error, file=sys.stderr)
return 1
print(f"{'estimated' if written else 'already estimated'}: version {resolved.version}, from {_describe(source)}, "
f"to {args.output}")
return 0
def _store_step(args: argparse.Namespace, estimate_path) -> int:
from models.pipelines.store_risks import store_estimate
try:
batch, written = store_estimate(estimate_path, args.domain)
except (LookupError, ValueError, FileNotFoundError) as error:
print(error, file=sys.stderr)
return 1
print(f"{'stored' if written else 'already stored'}: batch {batch}, from {estimate_path}")
return 0
def _store(args: argparse.Namespace) -> int:
"""Stores an estimate file as a batch of risks in the domain's database."""
return _store_step(args, args.input)
def _report_eda(args: argparse.Namespace) -> int:
"""Runs the model's exploratory notebook on a build's file and keeps the rendered page as an MLflow report."""
from pathlib import Path
from models.reports.eda import report_eda
from models.reports.rendering import RenderError
if not (scenario := _scenario(args)) or not (path := _cohort_file(args, scenario)):
return 1
notebook = Path(args.notebook) if args.notebook else scenario.folder / "notebooks" / "01_eda.ipynb"
if not notebook.exists():
print(f"no notebook at {notebook}", file=sys.stderr)
return 1
try:
run_id, written = report_eda(notebook, path, args.domain, args.scenario, kernel=args.kernel)
except RenderError as error:
print(error, file=sys.stderr)
return 1
print(f"{'reported' if written else 'already reported'}: run {run_id}, {notebook.name} on {path}")
return 0
def _serve_notebooks(args: argparse.Namespace) -> int:
"""The runner container's loop (`models.reports.notebook_jobs.serve`)."""
import os
from pathlib import Path
from models.reports.notebook_jobs import JOBS_DIR_ENV, serve
folder = args.jobs or os.environ.get(JOBS_DIR_ENV)
if not folder:
print(f"no jobs folder: pass --jobs or set {JOBS_DIR_ENV}", file=sys.stderr)
return 2
serve(Path(folder), once=args.once)
return 0
def _estimate(args: argparse.Namespace) -> int:
"""Scores the build with a registered version and writes the output file."""
if not (scenario := _scenario(args)) or not (source := _cohort_source(args, scenario)):
return 1
return _estimate_step(args, scenario, source)
def _promote_step(args: argparse.Namespace, version: str) -> int:
"""Promotes through the same gate the WebApi's promote route uses (MLD-01/01b):
a version missing its checklist (validation reports, routine records, a saved
model) is rejected here exactly as it would be there, rather than set directly."""
from models.io.registry import PRODUCTION_ALIAS, PromotionBlocked, registered_name, registry
from mlflow import MlflowException
name = registered_name(args.domain, args.scenario)
try:
current = registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS).version
except MlflowException:
current = None
if str(current) == str(version):
print(f"already in production: version {version}")
return 0
try:
registry.promote(args.domain, args.scenario, version)
except PromotionBlocked as blocked:
failed = ", ".join(f"{c.code} ({c.requirement})" for c in blocked.checks if not c.passed)
print(f"not promoted, missing: {failed}", file=sys.stderr)
return 1
print(f"in production: version {version}")
return 0
def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
"""Runs the steps asked for, in their order. A step whose result already exists is a no-op."""
if not (args.export or args.train or args.promote or args.estimate or args.store):
parser.error("name at least one step: --export, --train, --promote, --estimate, --store")
if (args.estimate or args.store) and not args.output:
parser.error("--estimate and --store need --output")
if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"):
parser.error("a prod run names its cohort build: --build (ML-03)")
if args.export and args.source == "dbt" and not args.manifest:
parser.error("--export with --source dbt needs --manifest")
if args.export and args.source == "dbt" and args.armado is not None:
parser.error("a dbt build is numbered when it's exported: --build can't go with --export --source dbt")
if args.train and args.version:
parser.error("--version names an existing version: it can't go with --train")
if not (scenario := _scenario(args)):
return 1
if args.export:
args.read = "file"
cohort = scenario.cohort.split("/", 1)[1]
export = argparse.Namespace(domain=args.domain, cohort=cohort, source=args.source, build=args.armado,
manifest=args.manifest)
if args.source == "dbt":
export.build = None
if code := _cohort_export(export):
return code
if not (args.train or args.promote or args.estimate):
return _store_step(args, args.output) if args.store else 0
if not (source := _cohort_source(args, scenario)):
return 1
version = args.version
if args.train or (args.promote and not version):
from models.dags.training import find_trained, train
environment = args.environment.upper()
version = find_trained(scenario, source, environment)
if args.train and version:
print(f"already trained: version {version}, from {_describe(source)}")
elif args.train:
version = train(scenario, source, environment)
print(f"trained: version {version}, from {_describe(source)}")
elif not version:
print(f"no {environment} version trained on {_describe(source)}: use --train or --version", file=sys.stderr)
return 1
if args.promote and (code := _promote_step(args, version)):
return code
if args.estimate and (code := _estimate_step(args, scenario, source)):
return code
return _store_step(args, args.output) if args.store else 0
def _cohort_build(args: argparse.Namespace) -> int:
"""Runs the cohort's rules and shows its attrition, or only its graph. Stores nothing."""
from sqlalchemy.exc import DBAPIError
from importlib import import_module
from models.io.contracts import CohortDefinitionError
from models.io.storage import read_queries
from models.pipelines.cohort_build import build_cohort, build_driver, mermaid
url = f"{args.domain}/{args.cohort}"
try:
queries = read_queries(args.manifest, url)
if args.graph:
print(mermaid(build_driver(queries).graph))
return 0
built = build_cohort(queries, import_module(f"persistance.{args.domain}").dbt_query_repository)
except (FileNotFoundError, CohortDefinitionError) as error:
print(error, file=sys.stderr)
return 1
except DBAPIError as error:
print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? "
f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr)
return 1
print(built.attrition.to_string(index=False))
print(f"{url}: {len(built.study_population)} members, not stored")
return 0
def _cohort_export(args: argparse.Namespace) -> int:
"""Exports a build to its Parquet file: the kit's stored build, or one built now from dbt's rules."""
from importlib import import_module
from persistance.edges.dbt import DbtRelationError
from persistance.settings import settings
from sqlalchemy.exc import DBAPIError
from models.io.contracts import CohortDefinitionError
from models.io.storage import read_queries
from models.io.storage import cohorts_root
from models.pipelines.export_cohort import export_dbt_build, export_kit_build
url = f"{args.domain}/{args.cohort}"
repositories = import_module(f"persistance.{args.domain}")
timeline = repositories.timeline_repository
try:
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
if args.source == "dbt":
queries = read_queries(args.manifest, url)
path, outcome = export_dbt_build(queries, repositories.dbt_query_repository, timeline, root, args.domain)
else:
path, outcome = export_kit_build(repositories.cohort_repository, timeline, root, args.domain, url, args.build)
except PermissionError as error:
print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr)
return 1
except DBAPIError as error:
print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? "
f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr)
return 1
except (FileNotFoundError, LookupError, ValueError, DbtRelationError) as error:
print(error, file=sys.stderr)
return 1
print(f"{outcome}: {path}")
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}").cohort_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}").cohort_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")
if args.source == "dbt" and args.build is not None:
parser.error("--build names a kit build: it can't go with --source dbt")
return _cohort_export(args)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="python -m models", description="Commands of the screening models.")
commands = parser.add_subparsers(dest="command", metavar="<command>", required=True)
cohorts = commands.add_parser("cohorts", help="the cohort builds and their Parquet files")
cohorts.set_defaults(run=lambda args: _show_help(cohorts))
actions = cohorts.add_subparsers(dest="action", metavar="<action>")
build = actions.add_parser("build", help="run a cohort's rules and show its attrition; stores nothing")
build.add_argument("domain", choices=["cacu", "cama", "tea"])
build.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
build.add_argument("--manifest", required=True, help="the manifest.json `dbt compile` wrote")
build.add_argument("--graph", action="store_true", help="print the chain as a Mermaid diagram without running it")
build.set_defaults(run=_cohort_build)
export = actions.add_parser("export", help="export a build to its Parquet file, once")
export.add_argument("domain", choices=["cacu", "cama", "tea"])
export.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
export.add_argument("--source", choices=["kit", "dbt"], default="kit",
help="the kit's stored build, or one built now from dbt's rules")
export.add_argument("--build", type=int, help="the kit build's armado_id; the cohort's latest by default")
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="kit: a build the WebApi cycle stored; dbt: one built now (both from 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 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")
train.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
train.add_argument("--read", choices=["db", "file"], default="db",
help="a kit build read from the database, or its exported file; dbt's builds are files")
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
train.set_defaults(run=lambda args: _train(train, args))
estimate = commands.add_parser("estimate", help="score a cohort build with a registered version")
estimate.add_argument("domain", choices=["cacu", "cama", "tea"])
estimate.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
estimate.add_argument("--output", required=True, help="the Parquet file to write")
estimate.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
estimate.add_argument("--read", choices=["db", "file"], default="db",
help="a kit build read from the database, or its exported file; dbt's builds are files")
estimate.add_argument("--version", help="the model version; the one in production by default")
estimate.set_defaults(run=_estimate)
report = commands.add_parser("report", help="notebooks run on a build's file and kept as MLflow reports")
report.set_defaults(run=lambda args: _show_help(report))
reports = report.add_subparsers(dest="action", metavar="<report>")
eda = reports.add_parser("eda", help="render the exploratory notebook with Quarto and log it to MLflow")
eda.add_argument("domain", choices=["cacu", "cama", "tea"])
eda.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
eda.add_argument("--notebook", help="the notebook; the scenario's <scenario>/notebooks/01_eda.ipynb by default")
eda.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
eda.add_argument("--kernel", help="the Jupyter kernel to run it with; the notebook's own by default")
eda.set_defaults(run=_report_eda)
store = commands.add_parser("store", help="store an estimate file as a batch of risks in the domain's database")
store.add_argument("domain", choices=["cacu", "cama", "tea"])
store.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
store.add_argument("--input", required=True, help="the Parquet file `estimate` wrote")
store.set_defaults(run=_store)
run = commands.add_parser("run", help="run the pipeline's steps you name; those already done are no-ops")
run.add_argument("domain", choices=["cacu", "cama", "tea"])
run.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
run.add_argument("--export", action="store_true", help="export the build to its Parquet file")
run.add_argument("--train", action="store_true", help="train, unless a version from this file, code and environment exists")
run.add_argument("--promote", action="store_true", help="set the production alias on that version, or on --version")
run.add_argument("--estimate", action="store_true", help="score the build with --version, or the one in production")
run.add_argument("--store", action="store_true", help="store the estimate in --output as a batch of risks")
run.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
run.add_argument("--read", choices=["db", "file"], default="db",
help="a kit build read from the database, or its exported file; dbt's builds are files")
run.add_argument("--version", help="an existing model version, for --promote and --estimate")
run.add_argument("--environment", choices=["dev", "prod"], default="dev")
run.add_argument("--output", help="the Parquet file --estimate writes and --store reads")
run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt")
run.set_defaults(run=lambda args: _run(run, args))
notebooks = commands.add_parser("notebooks", help="the runner of notebooks uploaded to the platform")
notebooks.set_defaults(run=lambda args: _show_help(notebooks))
notebook_actions = notebooks.add_subparsers(dest="action", metavar="<action>")
serve = notebook_actions.add_parser("serve", help="run each job left in the jobs folder, one at a time")
serve.add_argument("--jobs", help="the jobs folder; NOTEBOOK_JOBS_DIR by default")
serve.add_argument("--once", action="store_true", help="run the jobs waiting now and stop")
serve.set_defaults(run=_serve_notebooks)
return parser
def main(argv: Sequence[str] | None = None) -> int:
args = build_parser().parse_args(argv)
return args.run(args)
if __name__ == "__main__":
sys.exit(main())