{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Continuous integration for data\n",
    "\n",
    "Check every change to the warehouse's code before it reaches the warehouse. A CI script builds the project as it is on main and as it is on the branch, on the same test data, in warehouses of their own; runs every test; lists what the change touches; compares the two builds table by table; and writes a report. Run it on two pull requests, then hand it to GitHub Actions.\n",
    "\n",
    "The lesson's page: https://monstrous.com.ng/learn/data-engineering/series-2/09-continuous-integration/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install what this lesson needs (in Colab, or any fresh environment)\n",
    "%pip install -q dlt[duckdb] dbt-core dbt-duckdb duckdb pandas numpy rdkit pyyaml\n",
    "\n",
    "import pathlib\n",
    "import urllib.request\n",
    "if not pathlib.Path(\"chemlib.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/shared/chemlib.py\", \"chemlib.py\")\n",
    "if not pathlib.Path(\"labdata.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/labdata.py\", \"labdata.py\")\n",
    "if not pathlib.Path(\"labstack.py\").exists():\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/labstack.py\", \"labstack.py\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/dbt_project.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/dbt_project.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/dbt_project.yml\", \"stages/after-06/lab_dbt/dbt_project.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/macros/generate_schema_name.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/macros/generate_schema_name.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/macros/generate_schema_name.sql\", \"stages/after-06/lab_dbt/macros/generate_schema_name.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/macros/unique_combination.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/macros/unique_combination.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/macros/unique_combination.sql\", \"stages/after-06/lab_dbt/macros/unique_combination.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/_marts.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/_marts.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/_marts.yml\", \"stages/after-06/lab_dbt/models/marts/_marts.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_compound.py\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_compound.py\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/dim_compound.py\", \"stages/after-06/lab_dbt/models/marts/dim_compound.py\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_compound_history.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_compound_history.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/dim_compound_history.sql\", \"stages/after-06/lab_dbt/models/marts/dim_compound_history.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_date.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_date.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/dim_date.sql\", \"stages/after-06/lab_dbt/models/marts/dim_date.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_target.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/dim_target.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/dim_target.sql\", \"stages/after-06/lab_dbt/models/marts/dim_target.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/fact_measurement.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/fact_measurement.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/fact_measurement.sql\", \"stages/after-06/lab_dbt/models/marts/fact_measurement.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/marts/measurements_wide.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/marts/measurements_wide.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/marts/measurements_wide.sql\", \"stages/after-06/lab_dbt/models/marts/measurements_wide.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/staging/_sources.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/staging/_sources.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/staging/_sources.yml\", \"stages/after-06/lab_dbt/models/staging/_sources.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/staging/_staging.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/staging/_staging.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/staging/_staging.yml\", \"stages/after-06/lab_dbt/models/staging/_staging.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/staging/stg_compounds.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/staging/stg_compounds.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/staging/stg_compounds.sql\", \"stages/after-06/lab_dbt/models/staging/stg_compounds.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/models/staging/stg_results.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/models/staging/stg_results.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/models/staging/stg_results.sql\", \"stages/after-06/lab_dbt/models/staging/stg_results.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/profiles.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/profiles.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/profiles.yml\", \"stages/after-06/lab_dbt/profiles.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/seeds/targets.csv\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/seeds/targets.csv\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/seeds/targets.csv\", \"stages/after-06/lab_dbt/seeds/targets.csv\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/seeds/unit_to_nm.csv\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/seeds/unit_to_nm.csv\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/seeds/unit_to_nm.csv\", \"stages/after-06/lab_dbt/seeds/unit_to_nm.csv\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/snapshots/registry_history.yml\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/snapshots/registry_history.yml\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/snapshots/registry_history.yml\", \"stages/after-06/lab_dbt/snapshots/registry_history.yml\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/tests/pic50_matches_ic50.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/tests/pic50_matches_ic50.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/tests/pic50_matches_ic50.sql\", \"stages/after-06/lab_dbt/tests/pic50_matches_ic50.sql\")\n",
    "if not pathlib.Path(\"stages/after-06/lab_dbt/tests/potency_in_plausible_range.sql\").exists():\n",
    "    pathlib.Path(\"stages/after-06/lab_dbt/tests/potency_in_plausible_range.sql\").parent.mkdir(parents=True, exist_ok=True)\n",
    "    urllib.request.urlretrieve(\"https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/stages/after-06/lab_dbt/tests/potency_in_plausible_range.sql\", \"stages/after-06/lab_dbt/tests/potency_in_plausible_range.sql\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Modules 5 to 8 check the *data*: tests on every build, contracts, alerts when a week looks wrong.\n",
    "This module checks the *code*. The dbt project changes every week: a new column for the chemists,\n",
    "a fixed join, a faster model. Each change is a chance to break something, and the warehouse is a\n",
    "bad place to find out, because by then the dashboards have been showing the broken numbers.\n",
    "\n",
    "**Continuous integration** (CI) means that every change is built and tested automatically before\n",
    "it is merged into the main version of the code. A change is proposed as a **pull request**: a\n",
    "request to merge a **branch** (a copy of the code with the change) into `main`. A CI service such\n",
    "as **GitHub Actions** then runs a script on a fresh machine, and the pull request shows whether it\n",
    "passed. In [Series 1, Module 13](../../series-1/13-versioning-everything/) we versioned code,\n",
    "environments and data; this course's own repository runs every lesson of every module this way on\n",
    "each change ([its workflow](https://github.com/David-Alobo/monstrous-learn/blob/main/.github/workflows/ci.yml)).\n",
    "\n",
    "For a warehouse, \"it builds and the tests pass\" is not quite enough. A reviewer also wants to know\n",
    "**what the change does to the data**: which tables it touches, and how their contents differ. A\n",
    "change can pass every test and still alter a thousand potencies. So the CI of this module answers\n",
    "three questions for every pull request:\n",
    "\n",
    "1. Does the project still build, and do its tests pass?\n",
    "2. Which models does the change touch, directly or downstream?\n",
    "3. How do those models' contents differ from `main`'s?\n",
    "\n",
    "![Continuous integration for the warehouse: a pull request's branch and main are each built on eight weeks of test data in a warehouse of their own; CI then answers three questions (do the tests pass, what does the change touch, how do the contents differ) in report.md; if it passed a person reviews and merges, if it failed branch protection blocks the merge](https://raw.githubusercontent.com/David-Alobo/monstrous-learn/main/data-engineering/series-2/09-continuous-integration/figures/ci-flow.svg)\n",
    "\n",
    "By the end of this module you will be able to:\n",
    "\n",
    "- build a disposable copy of the warehouse from test data, without touching the real one;\n",
    "- use dbt's **state** selection to list what a change touches;\n",
    "- compare two builds of a model, column by column and row by row (a **data diff**);\n",
    "- write a CI script that ends with a report and an exit code;\n",
    "- run it in GitHub Actions on every pull request, and make passing it a condition for merging.\n",
    "\n",
    "## Setup\n",
    "\n",
    "The lab's code lives in a repository of its own, made here in `work/lab-repo/`: Module 6's dbt\n",
    "project, and the CI script and workflow this module writes. The script is run as a separate\n",
    "program, exactly as GitHub Actions would run it, with Python's `subprocess` module. `yaml` (PyYAML)\n",
    "reads the workflow file back to check it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import os\n",
    "import shutil\n",
    "import subprocess\n",
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "import yaml\n",
    "\n",
    "import labstack\n",
    "\n",
    "logging.basicConfig(level=logging.INFO, format=\"%(levelname)s %(message)s\", force=True)\n",
    "log = logging.getLogger(__name__)\n",
    "\n",
    "# where the lesson writes its files (git-ignored); change it to write somewhere else\n",
    "WORK = Path(\"work\")\n",
    "REPO = WORK / \"lab-repo\"  # the lab's repository: the dbt project, ci.py and the workflow\n",
    "BRANCHES = WORK / \"branches\"  # each pull request's version of the dbt project\n",
    "\n",
    "shutil.rmtree(WORK, ignore_errors=True)  # start clean\n",
    "labstack.dbt_project(REPO / \"lab_dbt\", after=6)\n",
    "\n",
    "\n",
    "def write(path: Path, text: str) -> None:\n",
    "    \"\"\"Save a file (made, with its folders, if it is new).\"\"\"\n",
    "    path.parent.mkdir(parents=True, exist_ok=True)\n",
    "    path.write_text(text.lstrip(\"\\n\"), encoding=\"utf-8\", newline=\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. A warehouse of its own\n",
    "\n",
    "CI must never touch the real warehouse: a broken change would break it, and two pull requests\n",
    "built at once would overwrite each other. So each build goes into a **disposable** warehouse,\n",
    "made for the run and thrown away after. The dbt project of [Module\n",
    "4](../04-transformations-with-lineage/) was written for this: its profile reads the database's path\n",
    "from the environment variable `LAB_WAREHOUSE`, so the same project can build into any file.\n",
    "\n",
    "The other half is data. CI cannot use the lab's real data: the CI machine should not hold it, and a\n",
    "build on a year of data would take too long for every pull request. It builds on **test data**\n",
    "instead: small, known, and the same every time. Many teams keep a sample of production data, with\n",
    "anything sensitive removed; this lab has something better, its synthetic weeks (`labdata`), which\n",
    "contain every problem the lab has met. `labstack.warehouse_at` loads and snapshots them week by\n",
    "week into whatever warehouse `LAB_WAREHOUSE` names.\n",
    "\n",
    "## 2. The CI script\n",
    "\n",
    "`ci.py` builds the project twice on the same test data: as it is on `main` (the **base**) and as it\n",
    "is on the pull request's branch (the **head**). Building both, instead of comparing the branch with\n",
    "production, means that any difference between them comes from the change alone, never from the\n",
    "data. Its steps:\n",
    "\n",
    "- `build` copies a project into the run's own folder, points `LAB_WAREHOUSE` at a new database\n",
    "  there, loads the test data, and runs `dbt build`;\n",
    "- `changed` asks dbt which models the change touches. dbt saves a **manifest** of the project with\n",
    "  every build (Module 4, section 5); given the base's manifest with `--state`, the selector\n",
    "  `state:modified` picks the models whose code differs from it, and `+` adds everything downstream;\n",
    "- `diff` compares one model's two builds. The head's warehouse **attaches** the base's (DuckDB can\n",
    "  open a second database file under a name, here `base`), and SQL's `EXCEPT` returns the rows of\n",
    "  one table that are not in the other, compared on the columns both have;\n",
    "- the report says what passed, what failed, what changed and how, as Markdown, and the script ends\n",
    "  with exit code 1 if anything failed, which is how a CI service knows the check did not pass\n",
    "  ([Series 1, Module 10](../../series-1/10-pipelines-that-survive-failure/), section 1)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "write(REPO / \"ci.py\", '''\n",
    "\"\"\"Continuous integration for the lab's warehouse: build main and a branch, test, compare.\n",
    "\n",
    "Usage: python ci.py --base MAIN_PROJECT --head BRANCH_PROJECT --out FOLDER\n",
    "\"\"\"\n",
    "\n",
    "import argparse\n",
    "import logging\n",
    "import os\n",
    "import shutil\n",
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "import duckdb\n",
    "\n",
    "import labdata\n",
    "import labstack\n",
    "\n",
    "WEEKS = 8  # how many weeks of the lab's synthetic test data to build on\n",
    "QUIET = logging.getLogger(\"ci.dbt\")  # one line per model: in dbt's own log, not the report\n",
    "QUIET.propagate = False\n",
    "RUN_SPECIFIC = {\"load_id\"}  # columns that differ between any two builds: left out of the diff\n",
    "\n",
    "\n",
    "def build(project: Path, folder: Path) -> tuple[Path, list]:\n",
    "    \"\"\"Build a copy of a dbt project on the test data, in a warehouse of its own.\"\"\"\n",
    "    copy = shutil.copytree(project, folder / \"lab_dbt\",\n",
    "                           ignore=shutil.ignore_patterns(\"target\", \"logs\"))\n",
    "    os.environ[\"LAB_WAREHOUSE\"] = str((folder / \"lab.duckdb\").resolve())\n",
    "    labstack.warehouse_at(labdata.Lab(), WEEKS, folder, project=copy, build=False)\n",
    "    return copy, labstack.dbt(copy, \"build\", log=QUIET)\n",
    "\n",
    "\n",
    "def changed(head: Path, base: Path) -> list[str]:\n",
    "    \"\"\"The models the head changes, and every model downstream of them.\"\"\"\n",
    "    state = str((base / \"target\").resolve())\n",
    "    return sorted(labstack.dbt(head, \"ls\", \"--select\", \"state:modified+\", \"--state\", state,\n",
    "                               \"--resource-type\", \"model\", \"--output\", \"name\"))\n",
    "\n",
    "\n",
    "def diff(db: duckdb.DuckDBPyConnection, model: str) -> dict | None:\n",
    "    \"\"\"How a model differs between the base (attached as `base`) and the head.\n",
    "\n",
    "    None if the model was not built on the branch (dbt skips models after a failed test).\n",
    "    \"\"\"\n",
    "    def columns(database: str) -> list[str]:\n",
    "        return [row[0] for row in db.execute(\n",
    "            \"SELECT column_name FROM information_schema.columns \"\n",
    "            \"WHERE table_catalog = ? AND table_name = ? ORDER BY ordinal_position\",\n",
    "            [database, model]).fetchall()]\n",
    "\n",
    "    head_cols, base_cols = columns(\"lab\"), columns(\"base\")\n",
    "    if not head_cols:\n",
    "        return None\n",
    "    schema = db.execute(\"SELECT table_schema FROM information_schema.tables \"\n",
    "                        \"WHERE table_catalog = 'lab' AND table_name = ?\", [model]).fetchall()[0][0]\n",
    "    common = \", \".join(f'\"{c}\"' for c in head_cols\n",
    "                       if c in base_cols and c not in RUN_SPECIFIC)\n",
    "    head_table, base_table = f\"lab.{schema}.{model}\", f\"base.{schema}.{model}\"\n",
    "\n",
    "    def count(sql: str) -> int:\n",
    "        return db.execute(f\"SELECT count(*) FROM ({sql})\").fetchall()[0][0]\n",
    "\n",
    "    return {\n",
    "        \"rows on main\": count(f\"SELECT * FROM {base_table}\"),\n",
    "        \"rows on branch\": count(f\"SELECT * FROM {head_table}\"),\n",
    "        \"rows that differ\": count(f\"SELECT {common} FROM {head_table} EXCEPT ALL \"\n",
    "                                  f\"SELECT {common} FROM {base_table}\"),\n",
    "        \"columns added\": [c for c in head_cols if c not in base_cols],\n",
    "        \"columns removed\": [c for c in base_cols if c not in head_cols],\n",
    "    }\n",
    "\n",
    "\n",
    "def main() -> int:\n",
    "    parser = argparse.ArgumentParser(description=__doc__)\n",
    "    parser.add_argument(\"--base\", type=Path, required=True)\n",
    "    parser.add_argument(\"--head\", type=Path, required=True)\n",
    "    parser.add_argument(\"--out\", type=Path, required=True)\n",
    "    args = parser.parse_args()\n",
    "    shutil.rmtree(args.out, ignore_errors=True)\n",
    "    base, _ = build(args.base, args.out / \"base\")\n",
    "    head, results = build(args.head, args.out / \"head\")\n",
    "\n",
    "    failed = sorted(r.node.name for r in results if str(r.status) in (\"fail\", \"error\"))\n",
    "    passed = sum(str(r.status) == \"pass\" for r in results)\n",
    "    lines = [\"## Warehouse CI\", \"\",\n",
    "             f\"**{'FAILED' if failed else 'Passed'}**: {passed} tests passed, \"\n",
    "             f\"{len(failed)} failed.\", \"\"]\n",
    "    lines += [f\"- failed: `{name}`\" for name in failed]\n",
    "    touched = changed(head, base)\n",
    "    lines += [\"\", \"### Models this change touches\", \"\"]\n",
    "    lines += [f\"- `{model}`\" for model in touched] or [\"- none\"]\n",
    "    with duckdb.connect(os.environ[\"LAB_WAREHOUSE\"]) as db:\n",
    "        db.execute(f\"ATTACH '{(args.out / 'base' / 'lab.duckdb').resolve()}' AS base (READ_ONLY)\")\n",
    "        lines += [\"\", \"### How their contents differ from main\", \"\",\n",
    "                  \"| model | rows on main | rows on branch | rows that differ | columns added \"\n",
    "                  \"| columns removed |\", \"|---|---|---|---|---|---|\"]\n",
    "        for model in touched:\n",
    "            d = diff(db, model)\n",
    "            if d is None:\n",
    "                lines.append(f\"| `{model}` | not built on the branch (skipped) | | | | |\")\n",
    "                continue\n",
    "            lines.append(f\"| `{model}` | {d['rows on main']} | {d['rows on branch']} | \"\n",
    "                         f\"{d['rows that differ']} | {', '.join(d['columns added']) or '-'} | \"\n",
    "                         f\"{', '.join(d['columns removed']) or '-'} |\")\n",
    "    report = \"\\\\n\".join(lines) + \"\\\\n\"\n",
    "    (args.out / \"report.md\").write_text(report, encoding=\"utf-8\")\n",
    "    print(report)\n",
    "    return 1 if failed else 0\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    sys.exit(main())\n",
    "''')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The script is written inside a Python string, so its own backslashes are doubled (`\"\\\\n\"` becomes\n",
    "`\"\\n\"` in the file). It is about a hundred lines: every step is a dbt command, a SQL query or a\n",
    "file copy, so the script is mostly the order they run in and the report.\n",
    "\n",
    "## 3. Two pull requests\n",
    "\n",
    "A pull request is a branch with a change. Here a branch is a copy of the dbt project with the change\n",
    "made; in the lab's repository it would be a Git branch, and the CI service would check it out.\n",
    "`pull_request` makes one, and `run_ci` runs the CI script on it, as a separate program, and shows\n",
    "what it printed. `PYTHONPATH` tells that program where to find `labdata` and `labstack`, as the\n",
    "lab's repository would."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pull_request(name: str, model: str, old: str, new: str) -> Path:\n",
    "    \"\"\"A branch: a copy of main's dbt project with one passage of one model changed.\"\"\"\n",
    "    project = shutil.copytree(REPO / \"lab_dbt\", BRANCHES / name / \"lab_dbt\")\n",
    "    path = project / model\n",
    "    text = path.read_text(encoding=\"utf-8\")\n",
    "    assert text.count(old) == 1, f\"{model}: the passage to change is not there exactly once\"\n",
    "    path.write_text(text.replace(old, new), encoding=\"utf-8\", newline=\"\\n\")\n",
    "    return project\n",
    "\n",
    "\n",
    "def run_ci(head: Path, name: str) -> int:\n",
    "    \"\"\"Run ci.py on a branch, as a CI service would, and show its report.\"\"\"\n",
    "    folders = [os.getcwd(), *(p for p in sys.path if p)]  # here, and where Python looks\n",
    "    env = {**os.environ, \"PYTHONPATH\": os.pathsep.join(folders)}\n",
    "    done = subprocess.run(\n",
    "        [sys.executable, str(REPO / \"ci.py\"), \"--base\", str(REPO / \"lab_dbt\"),\n",
    "         \"--head\", str(head), \"--out\", str(WORK / \"ci\" / name)],\n",
    "        env=env, capture_output=True, text=True, encoding=\"utf-8\",\n",
    "    )\n",
    "    print(done.stdout)\n",
    "    log.info(\"ci.py ended with exit code %d\", done.returncode)\n",
    "    return done.returncode"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first pull request is the one a chemist asked for: the compound dimension should carry the\n",
    "topological polar surface area (TPSA), a property that tracks how well a molecule passes through\n",
    "membranes. One line in the Python model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "dim_compound\n",
      "fact_measurement\n",
      "measurements_wide\n",
      "## Warehouse CI\n",
      "\n",
      "**Passed**: 24 tests passed, 0 failed.\n",
      "\n",
      "\n",
      "### Models this change touches\n",
      "\n",
      "- `dim_compound`\n",
      "- `fact_measurement`\n",
      "- `measurements_wide`\n",
      "\n",
      "### How their contents differ from main\n",
      "\n",
      "| model | rows on main | rows on branch | rows that differ | columns added | columns removed |\n",
      "|---|---|---|---|---|---|\n",
      "| `dim_compound` | 320 | 320 | 0 | tpsa | - |\n",
      "| `fact_measurement` | 1032 | 1032 | 0 | - | - |\n",
      "| `measurements_wide` | 992 | 992 | 0 | - | - |\n",
      "\n",
      "\n",
      "INFO ci.py ended with exit code 0\n"
     ]
    }
   ],
   "source": [
    "tpsa = pull_request(\n",
    "    \"add-tpsa\", \"models/marts/dim_compound.py\",\n",
    "    '    compounds[\"heavy_atoms\"] = [m.GetNumHeavyAtoms() for m in mols]\\n',\n",
    "    '    compounds[\"heavy_atoms\"] = [m.GetNumHeavyAtoms() for m in mols]\\n'\n",
    "    '    compounds[\"tpsa\"] = [round(Descriptors.TPSA(m), 1) for m in mols]\\n',\n",
    ")\n",
    "exit_code = run_ci(tpsa, \"add-tpsa\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The CI passed, and the report says exactly what a reviewer needs. The change touches\n",
    "`dim_compound` and the two models built from it; `dim_compound` gained one column; and no row of\n",
    "any of them changed on the columns they already had, so no number anyone relies on moved. (The\n",
    "diff leaves out `load_id`, which records dlt's load and so differs between any two builds:\n",
    "`RUN_SPECIFIC` in the script lists such columns.) That\n",
    "last line is the one tests cannot give: the tests say the new code is right, the diff says what it\n",
    "did to the data.\n",
    "\n",
    "The second pull request looks harmless too. Someone thinks pIC50s with fifteen decimals look\n",
    "untidy in the dashboards and rounds them, in the staging model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "fact_measurement\n",
      "measurements_wide\n",
      "stg_results\n",
      "## Warehouse CI\n",
      "\n",
      "**FAILED**: 23 tests passed, 1 failed.\n",
      "\n",
      "- failed: `pic50_matches_ic50`\n",
      "\n",
      "### Models this change touches\n",
      "\n",
      "- `fact_measurement`\n",
      "- `measurements_wide`\n",
      "- `stg_results`\n",
      "\n",
      "### How their contents differ from main\n",
      "\n",
      "| model | rows on main | rows on branch | rows that differ | columns added | columns removed |\n",
      "|---|---|---|---|---|---|\n",
      "| `fact_measurement` | 1032 | 1032 | 1030 | - | - |\n",
      "| `measurements_wide` | not built on the branch (skipped) | | | | |\n",
      "| `stg_results` | 1032 | 1032 | 1030 | - | - |\n",
      "\n",
      "\n",
      "INFO ci.py ended with exit code 1\n"
     ]
    }
   ],
   "source": [
    "rounded = pull_request(\n",
    "    \"round-pic50\", \"models/staging/stg_results.sql\",\n",
    "    \"       9 - log10(value * u.factor)   as pic50,\\n\",\n",
    "    \"       round(9 - log10(value * u.factor), 2) as pic50,\\n\",\n",
    ")\n",
    "exit_code = run_ci(rounded, \"round-pic50\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The CI failed, and for a good reason. The singular test of [Module 5](../05-tests-and-contracts/)\n",
    "says every pIC50 is exactly 9 − log₁₀ of its IC50; rounded values are not. The diff shows the cost:\n",
    "1,030 of the 1,032 results have a different pIC50 from `main`'s, in staging and in the fact table.\n",
    "The wide view was not built at all, because dbt skips what is built from a model whose test failed\n",
    "(Module 5): on `main` the dashboards would have kept their last good data. Rounding belongs where numbers are shown (the dashboard), not where they are stored, and the\n",
    "CI said so before anything reached the warehouse. Without the test, the pull request would have\n",
    "passed, but the diff would still have told the reviewer that a thousand potencies moved.\n",
    "\n",
    "## 4. In GitHub Actions\n",
    "\n",
    "GitHub Actions runs **workflows**: YAML files in the repository's `.github/workflows/` folder that\n",
    "say when to run (`on`), on what machine (`runs-on`) and which **steps**. A step either runs a\n",
    "command (`run`) or uses a ready-made **action** (`uses`), such as `actions/checkout`, which fetches\n",
    "the repository. Here is the lab's workflow:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "keys: ['name', True, 'jobs']\n",
      "- Fetch the branch, and main's history\n",
      "- Put main's version of the code next to the branch's\n",
      "- Install uv\n",
      "- Install the lab's packages, as locked\n",
      "- Build main and the branch on the test data, test and compare\n",
      "- Show the report on the run's page\n",
      "- Keep the report\n"
     ]
    }
   ],
   "source": [
    "write(REPO / \".github\" / \"workflows\" / \"warehouse-ci.yml\", \"\"\"\n",
    "name: warehouse-ci\n",
    "on:\n",
    "  pull_request:\n",
    "    paths: [\"lab_dbt/**\", \"ci.py\"]  # only changes to the warehouse's code\n",
    "jobs:\n",
    "  build-and-compare:\n",
    "    runs-on: ubuntu-latest\n",
    "    steps:\n",
    "      - name: Fetch the branch, and main's history\n",
    "        uses: actions/checkout@v4\n",
    "        with:\n",
    "          fetch-depth: 0\n",
    "      - name: Put main's version of the code next to the branch's\n",
    "        run: git worktree add ../main origin/main\n",
    "      - name: Install uv\n",
    "        uses: astral-sh/setup-uv@v6\n",
    "      - name: Install the lab's packages, as locked\n",
    "        run: uv sync --locked\n",
    "      - name: Build main and the branch on the test data, test and compare\n",
    "        run: uv run python ci.py --base ../main/lab_dbt --head lab_dbt --out ci-out\n",
    "      - name: Show the report on the run's page\n",
    "        if: always()\n",
    "        run: cat ci-out/report.md >> \"$GITHUB_STEP_SUMMARY\"\n",
    "      - name: Keep the report\n",
    "        if: always()\n",
    "        uses: actions/upload-artifact@v4\n",
    "        with:\n",
    "          name: warehouse-ci-report\n",
    "          path: ci-out/report.md\n",
    "\"\"\")\n",
    "workflow = yaml.safe_load((REPO / \".github\" / \"workflows\" / \"warehouse-ci.yml\")\n",
    "                          .read_text(encoding=\"utf-8\"))\n",
    "print(\"keys:\", list(workflow))\n",
    "for step in workflow[\"jobs\"][\"build-and-compare\"][\"steps\"]:\n",
    "    print(\"-\", step[\"name\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Most of it reads as written. `fetch-depth: 0` fetches the whole history, so that `main` can be put\n",
    "next to the branch with `git worktree` (a second folder with another version of the same\n",
    "repository). `if: always()` runs a step even when an earlier one failed: a failed CI is exactly when\n",
    "the report matters most. `$GITHUB_STEP_SUMMARY` is a file whose contents GitHub shows on the run's\n",
    "page, so the report appears there as formatted Markdown.\n",
    "\n",
    "One line of the output is a surprise: the key `on` came back as `True`. PyYAML follows an old\n",
    "version of YAML in which `on`, `yes` and `true` all mean the same thing; GitHub reads it as the word\n",
    "`on`. The workflow is right, and it is a useful reminder that YAML is read by programs that do not\n",
    "always agree.\n",
    "\n",
    "Two settings on GitHub finish the job, in the repository's settings under **Branches**:\n",
    "\n",
    "- a **branch protection rule** for `main` that requires the `build-and-compare` check to pass, so a\n",
    "  pull request whose CI failed cannot be merged;\n",
    "- **required reviews**, so a person reads the report before merging: CI says what a change does,\n",
    "  people decide whether that is what the lab wants.\n",
    "\n",
    "The lab's secrets stay out of all this. CI builds on synthetic data, so it needs no password; a\n",
    "team whose CI must reach a real database gives it a separate, read-only account, stored as a GitHub\n",
    "**secret** and read from the environment, never written in the workflow ([Series 1, Module\n",
    "4](../../series-1/04-databases-and-schemas/), section 9).\n",
    "\n",
    "In [Module 10](../10-structure-activity-dashboards/) the warehouse finally reaches the chemists:\n",
    "dashboards of their series, built on the marts these modules have made, tested and watched.\n",
    "\n",
    "## Try it yourself\n",
    "\n",
    "The homework is a few questions, answered by running code like the code above: in a new cell at\n",
    "the end of the notebook, or in a script. It is at the end of the lesson's page, and in\n",
    "`homework.md` in the module's folder. The answers are published after the cohort's deadline.\n",
    "\n",
    "## Further reading\n",
    "\n",
    "- The GitHub Actions documentation. *Understanding GitHub Actions*: workflows, events, jobs,\n",
    "  steps and actions. <https://docs.github.com/en/actions/get-started/understand-github-actions>\n",
    "- The dbt documentation. *Node selector methods*, `state`: selecting what changed against a\n",
    "  manifest, as used by \"slim CI\". <https://docs.getdbt.com/reference/node-selection/methods>\n",
    "- The DuckDB documentation. *ATTACH*: several database files in one connection.\n",
    "  <https://duckdb.org/docs/stable/sql/statements/attach>\n",
    "- Humble, J. & Farley, D. (2010). *Continuous Delivery: Reliable Software Releases through Build,\n",
    "  Test, and Deployment Automation*. Addison-Wesley. Chapter 3, on continuous integration."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
